Tools.cpp 379 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474
  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 const char *getSparcAsmModeForCPU(StringRef Name,
  52. const llvm::Triple &Triple) {
  53. if (Triple.getArch() == llvm::Triple::sparcv9) {
  54. return llvm::StringSwitch<const char *>(Name)
  55. .Case("niagara", "-Av9b")
  56. .Case("niagara2", "-Av9b")
  57. .Case("niagara3", "-Av9d")
  58. .Case("niagara4", "-Av9d")
  59. .Default("-Av9");
  60. } else {
  61. return llvm::StringSwitch<const char *>(Name)
  62. .Case("v8", "-Av8")
  63. .Case("supersparc", "-Av8")
  64. .Case("sparclite", "-Asparclite")
  65. .Case("f934", "-Asparclite")
  66. .Case("hypersparc", "-Av8")
  67. .Case("sparclite86x", "-Asparclite")
  68. .Case("sparclet", "-Asparclet")
  69. .Case("tsc701", "-Asparclet")
  70. .Case("v9", "-Av8plus")
  71. .Case("ultrasparc", "-Av8plus")
  72. .Case("ultrasparc3", "-Av8plus")
  73. .Case("niagara", "-Av8plusb")
  74. .Case("niagara2", "-Av8plusb")
  75. .Case("niagara3", "-Av8plusd")
  76. .Case("niagara4", "-Av8plusd")
  77. .Default("-Av8");
  78. }
  79. }
  80. /// CheckPreprocessingOptions - Perform some validation of preprocessing
  81. /// arguments that is shared with gcc.
  82. static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
  83. if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
  84. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
  85. !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
  86. D.Diag(diag::err_drv_argument_only_allowed_with)
  87. << A->getBaseArg().getAsString(Args)
  88. << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
  89. }
  90. }
  91. }
  92. /// CheckCodeGenerationOptions - Perform some validation of code generation
  93. /// arguments that is shared with gcc.
  94. static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
  95. // In gcc, only ARM checks this, but it seems reasonable to check universally.
  96. if (Args.hasArg(options::OPT_static))
  97. if (const Arg *A =
  98. Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
  99. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  100. << "-static";
  101. }
  102. // Add backslashes to escape spaces and other backslashes.
  103. // This is used for the space-separated argument list specified with
  104. // the -dwarf-debug-flags option.
  105. static void EscapeSpacesAndBackslashes(const char *Arg,
  106. SmallVectorImpl<char> &Res) {
  107. for (; *Arg; ++Arg) {
  108. switch (*Arg) {
  109. default:
  110. break;
  111. case ' ':
  112. case '\\':
  113. Res.push_back('\\');
  114. break;
  115. }
  116. Res.push_back(*Arg);
  117. }
  118. }
  119. // Quote target names for inclusion in GNU Make dependency files.
  120. // Only the characters '$', '#', ' ', '\t' are quoted.
  121. static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
  122. for (unsigned i = 0, e = Target.size(); i != e; ++i) {
  123. switch (Target[i]) {
  124. case ' ':
  125. case '\t':
  126. // Escape the preceding backslashes
  127. for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
  128. Res.push_back('\\');
  129. // Escape the space/tab
  130. Res.push_back('\\');
  131. break;
  132. case '$':
  133. Res.push_back('$');
  134. break;
  135. case '#':
  136. Res.push_back('\\');
  137. break;
  138. default:
  139. break;
  140. }
  141. Res.push_back(Target[i]);
  142. }
  143. }
  144. static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
  145. const char *ArgName, const char *EnvVar) {
  146. const char *DirList = ::getenv(EnvVar);
  147. bool CombinedArg = false;
  148. if (!DirList)
  149. return; // Nothing to do.
  150. StringRef Name(ArgName);
  151. if (Name.equals("-I") || Name.equals("-L"))
  152. CombinedArg = true;
  153. StringRef Dirs(DirList);
  154. if (Dirs.empty()) // Empty string should not add '.'.
  155. return;
  156. StringRef::size_type Delim;
  157. while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
  158. if (Delim == 0) { // Leading colon.
  159. if (CombinedArg) {
  160. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  161. } else {
  162. CmdArgs.push_back(ArgName);
  163. CmdArgs.push_back(".");
  164. }
  165. } else {
  166. if (CombinedArg) {
  167. CmdArgs.push_back(
  168. Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
  169. } else {
  170. CmdArgs.push_back(ArgName);
  171. CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
  172. }
  173. }
  174. Dirs = Dirs.substr(Delim + 1);
  175. }
  176. if (Dirs.empty()) { // Trailing colon.
  177. if (CombinedArg) {
  178. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  179. } else {
  180. CmdArgs.push_back(ArgName);
  181. CmdArgs.push_back(".");
  182. }
  183. } else { // Add the last path.
  184. if (CombinedArg) {
  185. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
  186. } else {
  187. CmdArgs.push_back(ArgName);
  188. CmdArgs.push_back(Args.MakeArgString(Dirs));
  189. }
  190. }
  191. }
  192. static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
  193. const ArgList &Args, ArgStringList &CmdArgs) {
  194. const Driver &D = TC.getDriver();
  195. // Add extra linker input arguments which are not treated as inputs
  196. // (constructed via -Xarch_).
  197. Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
  198. for (const auto &II : Inputs) {
  199. if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
  200. // Don't try to pass LLVM inputs unless we have native support.
  201. D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
  202. // Add filenames immediately.
  203. if (II.isFilename()) {
  204. CmdArgs.push_back(II.getFilename());
  205. continue;
  206. }
  207. // Otherwise, this is a linker input argument.
  208. const Arg &A = II.getInputArg();
  209. // Handle reserved library options.
  210. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
  211. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  212. else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
  213. TC.AddCCKextLibArgs(Args, CmdArgs);
  214. else if (A.getOption().matches(options::OPT_z)) {
  215. // Pass -z prefix for gcc linker compatibility.
  216. A.claim();
  217. A.render(Args, CmdArgs);
  218. } else {
  219. A.renderAsInput(Args, CmdArgs);
  220. }
  221. }
  222. // LIBRARY_PATH - included following the user specified library paths.
  223. // and only supported on native toolchains.
  224. if (!TC.isCrossCompiling())
  225. addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
  226. }
  227. /// \brief Determine whether Objective-C automated reference counting is
  228. /// enabled.
  229. static bool isObjCAutoRefCount(const ArgList &Args) {
  230. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  231. }
  232. /// \brief Determine whether we are linking the ObjC runtime.
  233. static bool isObjCRuntimeLinked(const ArgList &Args) {
  234. if (isObjCAutoRefCount(Args)) {
  235. Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
  236. return true;
  237. }
  238. return Args.hasArg(options::OPT_fobjc_link_runtime);
  239. }
  240. static bool forwardToGCC(const Option &O) {
  241. // Don't forward inputs from the original command line. They are added from
  242. // InputInfoList.
  243. return O.getKind() != Option::InputClass &&
  244. !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
  245. }
  246. void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
  247. const Driver &D, const ArgList &Args,
  248. ArgStringList &CmdArgs,
  249. const InputInfo &Output,
  250. const InputInfoList &Inputs,
  251. const ToolChain *AuxToolChain) const {
  252. Arg *A;
  253. CheckPreprocessingOptions(D, Args);
  254. Args.AddLastArg(CmdArgs, options::OPT_C);
  255. Args.AddLastArg(CmdArgs, options::OPT_CC);
  256. // Handle dependency file generation.
  257. if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
  258. (A = Args.getLastArg(options::OPT_MD)) ||
  259. (A = Args.getLastArg(options::OPT_MMD))) {
  260. // Determine the output location.
  261. const char *DepFile;
  262. if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
  263. DepFile = MF->getValue();
  264. C.addFailureResultFile(DepFile, &JA);
  265. } else if (Output.getType() == types::TY_Dependencies) {
  266. DepFile = Output.getFilename();
  267. } else if (A->getOption().matches(options::OPT_M) ||
  268. A->getOption().matches(options::OPT_MM)) {
  269. DepFile = "-";
  270. } else {
  271. DepFile = getDependencyFileName(Args, Inputs);
  272. C.addFailureResultFile(DepFile, &JA);
  273. }
  274. CmdArgs.push_back("-dependency-file");
  275. CmdArgs.push_back(DepFile);
  276. // Add a default target if one wasn't specified.
  277. if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
  278. const char *DepTarget;
  279. // If user provided -o, that is the dependency target, except
  280. // when we are only generating a dependency file.
  281. Arg *OutputOpt = Args.getLastArg(options::OPT_o);
  282. if (OutputOpt && Output.getType() != types::TY_Dependencies) {
  283. DepTarget = OutputOpt->getValue();
  284. } else {
  285. // Otherwise derive from the base input.
  286. //
  287. // FIXME: This should use the computed output file location.
  288. SmallString<128> P(Inputs[0].getBaseInput());
  289. llvm::sys::path::replace_extension(P, "o");
  290. DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
  291. }
  292. CmdArgs.push_back("-MT");
  293. SmallString<128> Quoted;
  294. QuoteTarget(DepTarget, Quoted);
  295. CmdArgs.push_back(Args.MakeArgString(Quoted));
  296. }
  297. if (A->getOption().matches(options::OPT_M) ||
  298. A->getOption().matches(options::OPT_MD))
  299. CmdArgs.push_back("-sys-header-deps");
  300. if ((isa<PrecompileJobAction>(JA) &&
  301. !Args.hasArg(options::OPT_fno_module_file_deps)) ||
  302. Args.hasArg(options::OPT_fmodule_file_deps))
  303. CmdArgs.push_back("-module-file-deps");
  304. }
  305. if (Args.hasArg(options::OPT_MG)) {
  306. if (!A || A->getOption().matches(options::OPT_MD) ||
  307. A->getOption().matches(options::OPT_MMD))
  308. D.Diag(diag::err_drv_mg_requires_m_or_mm);
  309. CmdArgs.push_back("-MG");
  310. }
  311. Args.AddLastArg(CmdArgs, options::OPT_MP);
  312. Args.AddLastArg(CmdArgs, options::OPT_MV);
  313. // Convert all -MQ <target> args to -MT <quoted target>
  314. for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
  315. A->claim();
  316. if (A->getOption().matches(options::OPT_MQ)) {
  317. CmdArgs.push_back("-MT");
  318. SmallString<128> Quoted;
  319. QuoteTarget(A->getValue(), Quoted);
  320. CmdArgs.push_back(Args.MakeArgString(Quoted));
  321. // -MT flag - no change
  322. } else {
  323. A->render(Args, CmdArgs);
  324. }
  325. }
  326. // Add -i* options, and automatically translate to
  327. // -include-pch/-include-pth for transparent PCH support. It's
  328. // wonky, but we include looking for .gch so we can support seamless
  329. // replacement into a build system already set up to be generating
  330. // .gch files.
  331. bool RenderedImplicitInclude = false;
  332. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  333. if (A->getOption().matches(options::OPT_include)) {
  334. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  335. RenderedImplicitInclude = true;
  336. // Use PCH if the user requested it.
  337. bool UsePCH = D.CCCUsePCH;
  338. bool FoundPTH = false;
  339. bool FoundPCH = false;
  340. SmallString<128> P(A->getValue());
  341. // We want the files to have a name like foo.h.pch. Add a dummy extension
  342. // so that replace_extension does the right thing.
  343. P += ".dummy";
  344. if (UsePCH) {
  345. llvm::sys::path::replace_extension(P, "pch");
  346. if (llvm::sys::fs::exists(P))
  347. FoundPCH = true;
  348. }
  349. if (!FoundPCH) {
  350. llvm::sys::path::replace_extension(P, "pth");
  351. if (llvm::sys::fs::exists(P))
  352. FoundPTH = true;
  353. }
  354. if (!FoundPCH && !FoundPTH) {
  355. llvm::sys::path::replace_extension(P, "gch");
  356. if (llvm::sys::fs::exists(P)) {
  357. FoundPCH = UsePCH;
  358. FoundPTH = !UsePCH;
  359. }
  360. }
  361. if (FoundPCH || FoundPTH) {
  362. if (IsFirstImplicitInclude) {
  363. A->claim();
  364. if (UsePCH)
  365. CmdArgs.push_back("-include-pch");
  366. else
  367. CmdArgs.push_back("-include-pth");
  368. CmdArgs.push_back(Args.MakeArgString(P));
  369. continue;
  370. } else {
  371. // Ignore the PCH if not first on command line and emit warning.
  372. D.Diag(diag::warn_drv_pch_not_first_include) << P
  373. << A->getAsString(Args);
  374. }
  375. }
  376. }
  377. // Not translated, render as usual.
  378. A->claim();
  379. A->render(Args, CmdArgs);
  380. }
  381. Args.AddAllArgs(CmdArgs,
  382. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  383. options::OPT_F, options::OPT_index_header_map});
  384. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  385. // FIXME: There is a very unfortunate problem here, some troubled
  386. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  387. // really support that we would have to parse and then translate
  388. // those options. :(
  389. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  390. options::OPT_Xpreprocessor);
  391. // -I- is a deprecated GCC feature, reject it.
  392. if (Arg *A = Args.getLastArg(options::OPT_I_))
  393. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  394. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  395. // -isysroot to the CC1 invocation.
  396. StringRef sysroot = C.getSysRoot();
  397. if (sysroot != "") {
  398. if (!Args.hasArg(options::OPT_isysroot)) {
  399. CmdArgs.push_back("-isysroot");
  400. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  401. }
  402. }
  403. // Parse additional include paths from environment variables.
  404. // FIXME: We should probably sink the logic for handling these from the
  405. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  406. // CPATH - included following the user specified includes (but prior to
  407. // builtin and standard includes).
  408. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  409. // C_INCLUDE_PATH - system includes enabled when compiling C.
  410. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  411. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  412. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  413. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  414. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  415. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  416. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  417. // Optional AuxToolChain indicates that we need to include headers
  418. // for more than one target. If that's the case, add include paths
  419. // from AuxToolChain right after include paths of the same kind for
  420. // the current target.
  421. // Add C++ include arguments, if needed.
  422. if (types::isCXX(Inputs[0].getType())) {
  423. getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  424. if (AuxToolChain)
  425. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  426. }
  427. // Add system include arguments.
  428. getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
  429. if (AuxToolChain)
  430. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  431. // Add CUDA include arguments, if needed.
  432. if (types::isCuda(Inputs[0].getType()))
  433. getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
  434. }
  435. // FIXME: Move to target hook.
  436. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  437. switch (Triple.getArch()) {
  438. default:
  439. return true;
  440. case llvm::Triple::aarch64:
  441. case llvm::Triple::aarch64_be:
  442. case llvm::Triple::arm:
  443. case llvm::Triple::armeb:
  444. case llvm::Triple::thumb:
  445. case llvm::Triple::thumbeb:
  446. if (Triple.isOSDarwin() || Triple.isOSWindows())
  447. return true;
  448. return false;
  449. case llvm::Triple::ppc:
  450. case llvm::Triple::ppc64:
  451. if (Triple.isOSDarwin())
  452. return true;
  453. return false;
  454. case llvm::Triple::hexagon:
  455. case llvm::Triple::ppc64le:
  456. case llvm::Triple::systemz:
  457. case llvm::Triple::xcore:
  458. return false;
  459. }
  460. }
  461. static bool isNoCommonDefault(const llvm::Triple &Triple) {
  462. switch (Triple.getArch()) {
  463. default:
  464. return false;
  465. case llvm::Triple::xcore:
  466. case llvm::Triple::wasm32:
  467. case llvm::Triple::wasm64:
  468. return true;
  469. }
  470. }
  471. // ARM tools start.
  472. // Get SubArch (vN).
  473. static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
  474. llvm::StringRef Arch = Triple.getArchName();
  475. return llvm::ARM::parseArchVersion(Arch);
  476. }
  477. // True if M-profile.
  478. static bool isARMMProfile(const llvm::Triple &Triple) {
  479. llvm::StringRef Arch = Triple.getArchName();
  480. unsigned Profile = llvm::ARM::parseArchProfile(Arch);
  481. return Profile == llvm::ARM::PK_M;
  482. }
  483. // Get Arch/CPU from args.
  484. static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
  485. llvm::StringRef &CPU, bool FromAs = false) {
  486. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  487. CPU = A->getValue();
  488. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  489. Arch = A->getValue();
  490. if (!FromAs)
  491. return;
  492. for (const Arg *A :
  493. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  494. StringRef Value = A->getValue();
  495. if (Value.startswith("-mcpu="))
  496. CPU = Value.substr(6);
  497. if (Value.startswith("-march="))
  498. Arch = Value.substr(7);
  499. }
  500. }
  501. // Handle -mhwdiv=.
  502. // FIXME: Use ARMTargetParser.
  503. static void getARMHWDivFeatures(const Driver &D, const Arg *A,
  504. const ArgList &Args, StringRef HWDiv,
  505. std::vector<const char *> &Features) {
  506. unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
  507. if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
  508. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  509. }
  510. // Handle -mfpu=.
  511. static void getARMFPUFeatures(const Driver &D, const Arg *A,
  512. const ArgList &Args, StringRef FPU,
  513. std::vector<const char *> &Features) {
  514. unsigned FPUID = llvm::ARM::parseFPU(FPU);
  515. if (!llvm::ARM::getFPUFeatures(FPUID, Features))
  516. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  517. }
  518. // Decode ARM features from string like +[no]featureA+[no]featureB+...
  519. static bool DecodeARMFeatures(const Driver &D, StringRef text,
  520. std::vector<const char *> &Features) {
  521. SmallVector<StringRef, 8> Split;
  522. text.split(Split, StringRef("+"), -1, false);
  523. for (StringRef Feature : Split) {
  524. const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
  525. if (FeatureName)
  526. Features.push_back(FeatureName);
  527. else
  528. return false;
  529. }
  530. return true;
  531. }
  532. // Check if -march is valid by checking if it can be canonicalised and parsed.
  533. // getARMArch is used here instead of just checking the -march value in order
  534. // to handle -march=native correctly.
  535. static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
  536. llvm::StringRef ArchName,
  537. std::vector<const char *> &Features,
  538. const llvm::Triple &Triple) {
  539. std::pair<StringRef, StringRef> Split = ArchName.split("+");
  540. std::string MArch = arm::getARMArch(ArchName, Triple);
  541. if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
  542. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  543. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  544. }
  545. // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
  546. static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
  547. llvm::StringRef CPUName, llvm::StringRef ArchName,
  548. std::vector<const char *> &Features,
  549. const llvm::Triple &Triple) {
  550. std::pair<StringRef, StringRef> Split = CPUName.split("+");
  551. std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
  552. if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
  553. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  554. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  555. }
  556. static bool useAAPCSForMachO(const llvm::Triple &T) {
  557. // The backend is hardwired to assume AAPCS for M-class processors, ensure
  558. // the frontend matches that.
  559. return T.getEnvironment() == llvm::Triple::EABI ||
  560. T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
  561. }
  562. // Select the float ABI as determined by -msoft-float, -mhard-float, and
  563. // -mfloat-abi=.
  564. arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
  565. const Driver &D = TC.getDriver();
  566. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
  567. auto SubArch = getARMSubArchVersionNumber(Triple);
  568. arm::FloatABI ABI = FloatABI::Invalid;
  569. if (Arg *A =
  570. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  571. options::OPT_mfloat_abi_EQ)) {
  572. if (A->getOption().matches(options::OPT_msoft_float)) {
  573. ABI = FloatABI::Soft;
  574. } else if (A->getOption().matches(options::OPT_mhard_float)) {
  575. ABI = FloatABI::Hard;
  576. } else {
  577. ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
  578. .Case("soft", FloatABI::Soft)
  579. .Case("softfp", FloatABI::SoftFP)
  580. .Case("hard", FloatABI::Hard)
  581. .Default(FloatABI::Invalid);
  582. if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  583. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  584. ABI = FloatABI::Soft;
  585. }
  586. }
  587. // It is incorrect to select hard float ABI on MachO platforms if the ABI is
  588. // "apcs-gnu".
  589. if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
  590. ABI == FloatABI::Hard) {
  591. D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
  592. << Triple.getArchName();
  593. }
  594. }
  595. // If unspecified, choose the default based on the platform.
  596. if (ABI == FloatABI::Invalid) {
  597. switch (Triple.getOS()) {
  598. case llvm::Triple::Darwin:
  599. case llvm::Triple::MacOSX:
  600. case llvm::Triple::IOS:
  601. case llvm::Triple::TvOS: {
  602. // Darwin defaults to "softfp" for v6 and v7.
  603. ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  604. break;
  605. }
  606. case llvm::Triple::WatchOS:
  607. ABI = FloatABI::Hard;
  608. break;
  609. // FIXME: this is invalid for WindowsCE
  610. case llvm::Triple::Win32:
  611. ABI = FloatABI::Hard;
  612. break;
  613. case llvm::Triple::FreeBSD:
  614. switch (Triple.getEnvironment()) {
  615. case llvm::Triple::GNUEABIHF:
  616. ABI = FloatABI::Hard;
  617. break;
  618. default:
  619. // FreeBSD defaults to soft float
  620. ABI = FloatABI::Soft;
  621. break;
  622. }
  623. break;
  624. default:
  625. switch (Triple.getEnvironment()) {
  626. case llvm::Triple::GNUEABIHF:
  627. case llvm::Triple::EABIHF:
  628. ABI = FloatABI::Hard;
  629. break;
  630. case llvm::Triple::GNUEABI:
  631. case llvm::Triple::EABI:
  632. // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
  633. ABI = FloatABI::SoftFP;
  634. break;
  635. case llvm::Triple::Android:
  636. ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  637. break;
  638. default:
  639. // Assume "soft", but warn the user we are guessing.
  640. ABI = FloatABI::Soft;
  641. if (Triple.getOS() != llvm::Triple::UnknownOS ||
  642. !Triple.isOSBinFormatMachO())
  643. D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
  644. break;
  645. }
  646. }
  647. }
  648. assert(ABI != FloatABI::Invalid && "must select an ABI");
  649. return ABI;
  650. }
  651. static void getARMTargetFeatures(const ToolChain &TC,
  652. const llvm::Triple &Triple,
  653. const ArgList &Args,
  654. std::vector<const char *> &Features,
  655. bool ForAS) {
  656. const Driver &D = TC.getDriver();
  657. bool KernelOrKext =
  658. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  659. arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
  660. const Arg *WaCPU = nullptr, *WaFPU = nullptr;
  661. const Arg *WaHDiv = nullptr, *WaArch = nullptr;
  662. if (!ForAS) {
  663. // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
  664. // yet (it uses the -mfloat-abi and -msoft-float options), and it is
  665. // stripped out by the ARM target. We should probably pass this a new
  666. // -target-option, which is handled by the -cc1/-cc1as invocation.
  667. //
  668. // FIXME2: For consistency, it would be ideal if we set up the target
  669. // machine state the same when using the frontend or the assembler. We don't
  670. // currently do that for the assembler, we pass the options directly to the
  671. // backend and never even instantiate the frontend TargetInfo. If we did,
  672. // and used its handleTargetFeatures hook, then we could ensure the
  673. // assembler and the frontend behave the same.
  674. // Use software floating point operations?
  675. if (ABI == arm::FloatABI::Soft)
  676. Features.push_back("+soft-float");
  677. // Use software floating point argument passing?
  678. if (ABI != arm::FloatABI::Hard)
  679. Features.push_back("+soft-float-abi");
  680. } else {
  681. // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
  682. // to the assembler correctly.
  683. for (const Arg *A :
  684. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  685. StringRef Value = A->getValue();
  686. if (Value.startswith("-mfpu=")) {
  687. WaFPU = A;
  688. } else if (Value.startswith("-mcpu=")) {
  689. WaCPU = A;
  690. } else if (Value.startswith("-mhwdiv=")) {
  691. WaHDiv = A;
  692. } else if (Value.startswith("-march=")) {
  693. WaArch = A;
  694. }
  695. }
  696. }
  697. // Check -march. ClangAs gives preference to -Wa,-march=.
  698. const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
  699. StringRef ArchName;
  700. if (WaArch) {
  701. if (ArchArg)
  702. D.Diag(clang::diag::warn_drv_unused_argument)
  703. << ArchArg->getAsString(Args);
  704. ArchName = StringRef(WaArch->getValue()).substr(7);
  705. checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
  706. // FIXME: Set Arch.
  707. D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
  708. } else if (ArchArg) {
  709. ArchName = ArchArg->getValue();
  710. checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
  711. }
  712. // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
  713. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  714. StringRef CPUName;
  715. if (WaCPU) {
  716. if (CPUArg)
  717. D.Diag(clang::diag::warn_drv_unused_argument)
  718. << CPUArg->getAsString(Args);
  719. CPUName = StringRef(WaCPU->getValue()).substr(6);
  720. checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
  721. } else if (CPUArg) {
  722. CPUName = CPUArg->getValue();
  723. checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
  724. }
  725. // Add CPU features for generic CPUs
  726. if (CPUName == "native") {
  727. llvm::StringMap<bool> HostFeatures;
  728. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  729. for (auto &F : HostFeatures)
  730. Features.push_back(
  731. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  732. }
  733. // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
  734. const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
  735. if (WaFPU) {
  736. if (FPUArg)
  737. D.Diag(clang::diag::warn_drv_unused_argument)
  738. << FPUArg->getAsString(Args);
  739. getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
  740. Features);
  741. } else if (FPUArg) {
  742. getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
  743. }
  744. // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
  745. const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
  746. if (WaHDiv) {
  747. if (HDivArg)
  748. D.Diag(clang::diag::warn_drv_unused_argument)
  749. << HDivArg->getAsString(Args);
  750. getARMHWDivFeatures(D, WaHDiv, Args,
  751. StringRef(WaHDiv->getValue()).substr(8), Features);
  752. } else if (HDivArg)
  753. getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
  754. // Setting -msoft-float effectively disables NEON because of the GCC
  755. // implementation, although the same isn't true of VFP or VFP3.
  756. if (ABI == arm::FloatABI::Soft) {
  757. Features.push_back("-neon");
  758. // Also need to explicitly disable features which imply NEON.
  759. Features.push_back("-crypto");
  760. }
  761. // En/disable crc code generation.
  762. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  763. if (A->getOption().matches(options::OPT_mcrc))
  764. Features.push_back("+crc");
  765. else
  766. Features.push_back("-crc");
  767. }
  768. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
  769. Features.insert(Features.begin(), "+v8.1a");
  770. }
  771. // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
  772. // neither options are specified, see if we are compiling for kernel/kext and
  773. // decide whether to pass "+long-calls" based on the OS and its version.
  774. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  775. options::OPT_mno_long_calls)) {
  776. if (A->getOption().matches(options::OPT_mlong_calls))
  777. Features.push_back("+long-calls");
  778. } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  779. !Triple.isWatchOS()) {
  780. Features.push_back("+long-calls");
  781. }
  782. // Kernel code has more strict alignment requirements.
  783. if (KernelOrKext)
  784. Features.push_back("+strict-align");
  785. else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  786. options::OPT_munaligned_access)) {
  787. if (A->getOption().matches(options::OPT_munaligned_access)) {
  788. // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
  789. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  790. D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
  791. } else
  792. Features.push_back("+strict-align");
  793. } else {
  794. // Assume pre-ARMv6 doesn't support unaligned accesses.
  795. //
  796. // ARMv6 may or may not support unaligned accesses depending on the
  797. // SCTLR.U bit, which is architecture-specific. We assume ARMv6
  798. // Darwin and NetBSD targets support unaligned accesses, and others don't.
  799. //
  800. // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
  801. // which raises an alignment fault on unaligned accesses. Linux
  802. // defaults this bit to 0 and handles it as a system-wide (not
  803. // per-process) setting. It is therefore safe to assume that ARMv7+
  804. // Linux targets support unaligned accesses. The same goes for NaCl.
  805. //
  806. // The above behavior is consistent with GCC.
  807. int VersionNum = getARMSubArchVersionNumber(Triple);
  808. if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
  809. if (VersionNum < 6 ||
  810. Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  811. Features.push_back("+strict-align");
  812. } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
  813. if (VersionNum < 7)
  814. Features.push_back("+strict-align");
  815. } else
  816. Features.push_back("+strict-align");
  817. }
  818. // llvm does not support reserving registers in general. There is support
  819. // for reserving r9 on ARM though (defined as a platform-specific register
  820. // in ARM EABI).
  821. if (Args.hasArg(options::OPT_ffixed_r9))
  822. Features.push_back("+reserve-r9");
  823. // The kext linker doesn't know how to deal with movw/movt.
  824. if (KernelOrKext)
  825. Features.push_back("+no-movt");
  826. }
  827. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  828. ArgStringList &CmdArgs, bool KernelOrKext) const {
  829. // Select the ABI to use.
  830. // FIXME: Support -meabi.
  831. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  832. const char *ABIName = nullptr;
  833. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  834. ABIName = A->getValue();
  835. } else if (Triple.isOSBinFormatMachO()) {
  836. if (useAAPCSForMachO(Triple)) {
  837. ABIName = "aapcs";
  838. } else if (Triple.isWatchOS()) {
  839. ABIName = "aapcs16";
  840. } else {
  841. ABIName = "apcs-gnu";
  842. }
  843. } else if (Triple.isOSWindows()) {
  844. // FIXME: this is invalid for WindowsCE
  845. ABIName = "aapcs";
  846. } else {
  847. // Select the default based on the platform.
  848. switch (Triple.getEnvironment()) {
  849. case llvm::Triple::Android:
  850. case llvm::Triple::GNUEABI:
  851. case llvm::Triple::GNUEABIHF:
  852. ABIName = "aapcs-linux";
  853. break;
  854. case llvm::Triple::EABIHF:
  855. case llvm::Triple::EABI:
  856. ABIName = "aapcs";
  857. break;
  858. default:
  859. if (Triple.getOS() == llvm::Triple::NetBSD)
  860. ABIName = "apcs-gnu";
  861. else
  862. ABIName = "aapcs";
  863. break;
  864. }
  865. }
  866. CmdArgs.push_back("-target-abi");
  867. CmdArgs.push_back(ABIName);
  868. // Determine floating point ABI from the options & target defaults.
  869. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  870. if (ABI == arm::FloatABI::Soft) {
  871. // Floating point operations and argument passing are soft.
  872. // FIXME: This changes CPP defines, we need -target-soft-float.
  873. CmdArgs.push_back("-msoft-float");
  874. CmdArgs.push_back("-mfloat-abi");
  875. CmdArgs.push_back("soft");
  876. } else if (ABI == arm::FloatABI::SoftFP) {
  877. // Floating point operations are hard, but argument passing is soft.
  878. CmdArgs.push_back("-mfloat-abi");
  879. CmdArgs.push_back("soft");
  880. } else {
  881. // Floating point operations and argument passing are hard.
  882. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  883. CmdArgs.push_back("-mfloat-abi");
  884. CmdArgs.push_back("hard");
  885. }
  886. // Forward the -mglobal-merge option for explicit control over the pass.
  887. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  888. options::OPT_mno_global_merge)) {
  889. CmdArgs.push_back("-backend-option");
  890. if (A->getOption().matches(options::OPT_mno_global_merge))
  891. CmdArgs.push_back("-arm-global-merge=false");
  892. else
  893. CmdArgs.push_back("-arm-global-merge=true");
  894. }
  895. if (!Args.hasFlag(options::OPT_mimplicit_float,
  896. options::OPT_mno_implicit_float, true))
  897. CmdArgs.push_back("-no-implicit-float");
  898. }
  899. // ARM tools end.
  900. /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
  901. /// targeting.
  902. static std::string getAArch64TargetCPU(const ArgList &Args) {
  903. Arg *A;
  904. std::string CPU;
  905. // If we have -mtune or -mcpu, use that.
  906. if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
  907. CPU = StringRef(A->getValue()).lower();
  908. } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
  909. StringRef Mcpu = A->getValue();
  910. CPU = Mcpu.split("+").first.lower();
  911. }
  912. // Handle CPU name is 'native'.
  913. if (CPU == "native")
  914. return llvm::sys::getHostCPUName();
  915. else if (CPU.size())
  916. return CPU;
  917. // Make sure we pick "cyclone" if -arch is used.
  918. // FIXME: Should this be picked by checking the target triple instead?
  919. if (Args.getLastArg(options::OPT_arch))
  920. return "cyclone";
  921. return "generic";
  922. }
  923. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  924. ArgStringList &CmdArgs) const {
  925. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  926. llvm::Triple Triple(TripleStr);
  927. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  928. Args.hasArg(options::OPT_mkernel) ||
  929. Args.hasArg(options::OPT_fapple_kext))
  930. CmdArgs.push_back("-disable-red-zone");
  931. if (!Args.hasFlag(options::OPT_mimplicit_float,
  932. options::OPT_mno_implicit_float, true))
  933. CmdArgs.push_back("-no-implicit-float");
  934. const char *ABIName = nullptr;
  935. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  936. ABIName = A->getValue();
  937. else if (Triple.isOSDarwin())
  938. ABIName = "darwinpcs";
  939. else
  940. ABIName = "aapcs";
  941. CmdArgs.push_back("-target-abi");
  942. CmdArgs.push_back(ABIName);
  943. if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
  944. options::OPT_mno_fix_cortex_a53_835769)) {
  945. CmdArgs.push_back("-backend-option");
  946. if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
  947. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  948. else
  949. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
  950. } else if (Triple.isAndroid()) {
  951. // Enabled A53 errata (835769) workaround by default on android
  952. CmdArgs.push_back("-backend-option");
  953. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  954. }
  955. // Forward the -mglobal-merge option for explicit control over the pass.
  956. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  957. options::OPT_mno_global_merge)) {
  958. CmdArgs.push_back("-backend-option");
  959. if (A->getOption().matches(options::OPT_mno_global_merge))
  960. CmdArgs.push_back("-aarch64-global-merge=false");
  961. else
  962. CmdArgs.push_back("-aarch64-global-merge=true");
  963. }
  964. }
  965. // Get CPU and ABI names. They are not independent
  966. // so we have to calculate them together.
  967. void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
  968. StringRef &CPUName, StringRef &ABIName) {
  969. const char *DefMips32CPU = "mips32r2";
  970. const char *DefMips64CPU = "mips64r2";
  971. // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
  972. // default for mips64(el)?-img-linux-gnu.
  973. if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  974. Triple.getEnvironment() == llvm::Triple::GNU) {
  975. DefMips32CPU = "mips32r6";
  976. DefMips64CPU = "mips64r6";
  977. }
  978. // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
  979. if (Triple.isAndroid())
  980. DefMips64CPU = "mips64r6";
  981. // MIPS3 is the default for mips64*-unknown-openbsd.
  982. if (Triple.getOS() == llvm::Triple::OpenBSD)
  983. DefMips64CPU = "mips3";
  984. if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
  985. CPUName = A->getValue();
  986. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  987. ABIName = A->getValue();
  988. // Convert a GNU style Mips ABI name to the name
  989. // accepted by LLVM Mips backend.
  990. ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
  991. .Case("32", "o32")
  992. .Case("64", "n64")
  993. .Default(ABIName);
  994. }
  995. // Setup default CPU and ABI names.
  996. if (CPUName.empty() && ABIName.empty()) {
  997. switch (Triple.getArch()) {
  998. default:
  999. llvm_unreachable("Unexpected triple arch name");
  1000. case llvm::Triple::mips:
  1001. case llvm::Triple::mipsel:
  1002. CPUName = DefMips32CPU;
  1003. break;
  1004. case llvm::Triple::mips64:
  1005. case llvm::Triple::mips64el:
  1006. CPUName = DefMips64CPU;
  1007. break;
  1008. }
  1009. }
  1010. if (ABIName.empty()) {
  1011. // Deduce ABI name from the target triple.
  1012. if (Triple.getArch() == llvm::Triple::mips ||
  1013. Triple.getArch() == llvm::Triple::mipsel)
  1014. ABIName = "o32";
  1015. else
  1016. ABIName = "n64";
  1017. }
  1018. if (CPUName.empty()) {
  1019. // Deduce CPU name from ABI name.
  1020. CPUName = llvm::StringSwitch<const char *>(ABIName)
  1021. .Cases("o32", "eabi", DefMips32CPU)
  1022. .Cases("n32", "n64", DefMips64CPU)
  1023. .Default("");
  1024. }
  1025. // FIXME: Warn on inconsistent use of -march and -mabi.
  1026. }
  1027. std::string mips::getMipsABILibSuffix(const ArgList &Args,
  1028. const llvm::Triple &Triple) {
  1029. StringRef CPUName, ABIName;
  1030. tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1031. return llvm::StringSwitch<std::string>(ABIName)
  1032. .Case("o32", "")
  1033. .Case("n32", "32")
  1034. .Case("n64", "64");
  1035. }
  1036. // Convert ABI name to the GNU tools acceptable variant.
  1037. static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
  1038. return llvm::StringSwitch<llvm::StringRef>(ABI)
  1039. .Case("o32", "32")
  1040. .Case("n64", "64")
  1041. .Default(ABI);
  1042. }
  1043. // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
  1044. // and -mfloat-abi=.
  1045. static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
  1046. mips::FloatABI ABI = mips::FloatABI::Invalid;
  1047. if (Arg *A =
  1048. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1049. options::OPT_mfloat_abi_EQ)) {
  1050. if (A->getOption().matches(options::OPT_msoft_float))
  1051. ABI = mips::FloatABI::Soft;
  1052. else if (A->getOption().matches(options::OPT_mhard_float))
  1053. ABI = mips::FloatABI::Hard;
  1054. else {
  1055. ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
  1056. .Case("soft", mips::FloatABI::Soft)
  1057. .Case("hard", mips::FloatABI::Hard)
  1058. .Default(mips::FloatABI::Invalid);
  1059. if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1060. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1061. ABI = mips::FloatABI::Hard;
  1062. }
  1063. }
  1064. }
  1065. // If unspecified, choose the default based on the platform.
  1066. if (ABI == mips::FloatABI::Invalid) {
  1067. // Assume "hard", because it's a default value used by gcc.
  1068. // When we start to recognize specific target MIPS processors,
  1069. // we will be able to select the default more correctly.
  1070. ABI = mips::FloatABI::Hard;
  1071. }
  1072. assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
  1073. return ABI;
  1074. }
  1075. static void AddTargetFeature(const ArgList &Args,
  1076. std::vector<const char *> &Features,
  1077. OptSpecifier OnOpt, OptSpecifier OffOpt,
  1078. StringRef FeatureName) {
  1079. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  1080. if (A->getOption().matches(OnOpt))
  1081. Features.push_back(Args.MakeArgString("+" + FeatureName));
  1082. else
  1083. Features.push_back(Args.MakeArgString("-" + FeatureName));
  1084. }
  1085. }
  1086. static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1087. const ArgList &Args,
  1088. std::vector<const char *> &Features) {
  1089. StringRef CPUName;
  1090. StringRef ABIName;
  1091. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1092. ABIName = getGnuCompatibleMipsABIName(ABIName);
  1093. AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
  1094. options::OPT_mabicalls, "noabicalls");
  1095. mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
  1096. if (FloatABI == mips::FloatABI::Soft) {
  1097. // FIXME: Note, this is a hack. We need to pass the selected float
  1098. // mode to the MipsTargetInfoBase to define appropriate macros there.
  1099. // Now it is the only method.
  1100. Features.push_back("+soft-float");
  1101. }
  1102. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  1103. StringRef Val = StringRef(A->getValue());
  1104. if (Val == "2008") {
  1105. if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
  1106. Features.push_back("+nan2008");
  1107. else {
  1108. Features.push_back("-nan2008");
  1109. D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
  1110. }
  1111. } else if (Val == "legacy") {
  1112. if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
  1113. Features.push_back("-nan2008");
  1114. else {
  1115. Features.push_back("+nan2008");
  1116. D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
  1117. }
  1118. } else
  1119. D.Diag(diag::err_drv_unsupported_option_argument)
  1120. << A->getOption().getName() << Val;
  1121. }
  1122. AddTargetFeature(Args, Features, options::OPT_msingle_float,
  1123. options::OPT_mdouble_float, "single-float");
  1124. AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
  1125. "mips16");
  1126. AddTargetFeature(Args, Features, options::OPT_mmicromips,
  1127. options::OPT_mno_micromips, "micromips");
  1128. AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
  1129. "dsp");
  1130. AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
  1131. "dspr2");
  1132. AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
  1133. "msa");
  1134. // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
  1135. // pass -mfpxx
  1136. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  1137. options::OPT_mfp64)) {
  1138. if (A->getOption().matches(options::OPT_mfp32))
  1139. Features.push_back(Args.MakeArgString("-fp64"));
  1140. else if (A->getOption().matches(options::OPT_mfpxx)) {
  1141. Features.push_back(Args.MakeArgString("+fpxx"));
  1142. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1143. } else
  1144. Features.push_back(Args.MakeArgString("+fp64"));
  1145. } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
  1146. Features.push_back(Args.MakeArgString("+fpxx"));
  1147. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1148. }
  1149. AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
  1150. options::OPT_modd_spreg, "nooddspreg");
  1151. }
  1152. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1153. ArgStringList &CmdArgs) const {
  1154. const Driver &D = getToolChain().getDriver();
  1155. StringRef CPUName;
  1156. StringRef ABIName;
  1157. const llvm::Triple &Triple = getToolChain().getTriple();
  1158. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1159. CmdArgs.push_back("-target-abi");
  1160. CmdArgs.push_back(ABIName.data());
  1161. mips::FloatABI ABI = getMipsFloatABI(D, Args);
  1162. if (ABI == mips::FloatABI::Soft) {
  1163. // Floating point operations and argument passing are soft.
  1164. CmdArgs.push_back("-msoft-float");
  1165. CmdArgs.push_back("-mfloat-abi");
  1166. CmdArgs.push_back("soft");
  1167. } else {
  1168. // Floating point operations and argument passing are hard.
  1169. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1170. CmdArgs.push_back("-mfloat-abi");
  1171. CmdArgs.push_back("hard");
  1172. }
  1173. if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
  1174. if (A->getOption().matches(options::OPT_mxgot)) {
  1175. CmdArgs.push_back("-mllvm");
  1176. CmdArgs.push_back("-mxgot");
  1177. }
  1178. }
  1179. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1180. options::OPT_mno_ldc1_sdc1)) {
  1181. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1182. CmdArgs.push_back("-mllvm");
  1183. CmdArgs.push_back("-mno-ldc1-sdc1");
  1184. }
  1185. }
  1186. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1187. options::OPT_mno_check_zero_division)) {
  1188. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1189. CmdArgs.push_back("-mllvm");
  1190. CmdArgs.push_back("-mno-check-zero-division");
  1191. }
  1192. }
  1193. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1194. StringRef v = A->getValue();
  1195. CmdArgs.push_back("-mllvm");
  1196. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1197. A->claim();
  1198. }
  1199. }
  1200. /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
  1201. static std::string getPPCTargetCPU(const ArgList &Args) {
  1202. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1203. StringRef CPUName = A->getValue();
  1204. if (CPUName == "native") {
  1205. std::string CPU = llvm::sys::getHostCPUName();
  1206. if (!CPU.empty() && CPU != "generic")
  1207. return CPU;
  1208. else
  1209. return "";
  1210. }
  1211. return llvm::StringSwitch<const char *>(CPUName)
  1212. .Case("common", "generic")
  1213. .Case("440", "440")
  1214. .Case("440fp", "440")
  1215. .Case("450", "450")
  1216. .Case("601", "601")
  1217. .Case("602", "602")
  1218. .Case("603", "603")
  1219. .Case("603e", "603e")
  1220. .Case("603ev", "603ev")
  1221. .Case("604", "604")
  1222. .Case("604e", "604e")
  1223. .Case("620", "620")
  1224. .Case("630", "pwr3")
  1225. .Case("G3", "g3")
  1226. .Case("7400", "7400")
  1227. .Case("G4", "g4")
  1228. .Case("7450", "7450")
  1229. .Case("G4+", "g4+")
  1230. .Case("750", "750")
  1231. .Case("970", "970")
  1232. .Case("G5", "g5")
  1233. .Case("a2", "a2")
  1234. .Case("a2q", "a2q")
  1235. .Case("e500mc", "e500mc")
  1236. .Case("e5500", "e5500")
  1237. .Case("power3", "pwr3")
  1238. .Case("power4", "pwr4")
  1239. .Case("power5", "pwr5")
  1240. .Case("power5x", "pwr5x")
  1241. .Case("power6", "pwr6")
  1242. .Case("power6x", "pwr6x")
  1243. .Case("power7", "pwr7")
  1244. .Case("power8", "pwr8")
  1245. .Case("pwr3", "pwr3")
  1246. .Case("pwr4", "pwr4")
  1247. .Case("pwr5", "pwr5")
  1248. .Case("pwr5x", "pwr5x")
  1249. .Case("pwr6", "pwr6")
  1250. .Case("pwr6x", "pwr6x")
  1251. .Case("pwr7", "pwr7")
  1252. .Case("pwr8", "pwr8")
  1253. .Case("powerpc", "ppc")
  1254. .Case("powerpc64", "ppc64")
  1255. .Case("powerpc64le", "ppc64le")
  1256. .Default("");
  1257. }
  1258. return "";
  1259. }
  1260. static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1261. const ArgList &Args,
  1262. std::vector<const char *> &Features) {
  1263. for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
  1264. StringRef Name = A->getOption().getName();
  1265. A->claim();
  1266. // Skip over "-m".
  1267. assert(Name.startswith("m") && "Invalid feature name.");
  1268. Name = Name.substr(1);
  1269. bool IsNegative = Name.startswith("no-");
  1270. if (IsNegative)
  1271. Name = Name.substr(3);
  1272. // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
  1273. // pass the correct option to the backend while calling the frontend
  1274. // option the same.
  1275. // TODO: Change the LLVM backend option maybe?
  1276. if (Name == "mfcrf")
  1277. Name = "mfocrf";
  1278. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  1279. }
  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 (IsThinLTO)
  1605. CmdArgs.push_back("-plugin-opt=thinlto");
  1606. }
  1607. /// This is a helper function for validating the optional refinement step
  1608. /// parameter in reciprocal argument strings. Return false if there is an error
  1609. /// parsing the refinement step. Otherwise, return true and set the Position
  1610. /// of the refinement step in the input string.
  1611. static bool getRefinementStep(StringRef In, const Driver &D,
  1612. const Arg &A, size_t &Position) {
  1613. const char RefinementStepToken = ':';
  1614. Position = In.find(RefinementStepToken);
  1615. if (Position != StringRef::npos) {
  1616. StringRef Option = A.getOption().getName();
  1617. StringRef RefStep = In.substr(Position + 1);
  1618. // Allow exactly one numeric character for the additional refinement
  1619. // step parameter. This is reasonable for all currently-supported
  1620. // operations and architectures because we would expect that a larger value
  1621. // of refinement steps would cause the estimate "optimization" to
  1622. // under-perform the native operation. Also, if the estimate does not
  1623. // converge quickly, it probably will not ever converge, so further
  1624. // refinement steps will not produce a better answer.
  1625. if (RefStep.size() != 1) {
  1626. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1627. return false;
  1628. }
  1629. char RefStepChar = RefStep[0];
  1630. if (RefStepChar < '0' || RefStepChar > '9') {
  1631. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1632. return false;
  1633. }
  1634. }
  1635. return true;
  1636. }
  1637. /// The -mrecip flag requires processing of many optional parameters.
  1638. static void ParseMRecip(const Driver &D, const ArgList &Args,
  1639. ArgStringList &OutStrings) {
  1640. StringRef DisabledPrefixIn = "!";
  1641. StringRef DisabledPrefixOut = "!";
  1642. StringRef EnabledPrefixOut = "";
  1643. StringRef Out = "-mrecip=";
  1644. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  1645. if (!A)
  1646. return;
  1647. unsigned NumOptions = A->getNumValues();
  1648. if (NumOptions == 0) {
  1649. // No option is the same as "all".
  1650. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  1651. return;
  1652. }
  1653. // Pass through "all", "none", or "default" with an optional refinement step.
  1654. if (NumOptions == 1) {
  1655. StringRef Val = A->getValue(0);
  1656. size_t RefStepLoc;
  1657. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  1658. return;
  1659. StringRef ValBase = Val.slice(0, RefStepLoc);
  1660. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  1661. OutStrings.push_back(Args.MakeArgString(Out + Val));
  1662. return;
  1663. }
  1664. }
  1665. // Each reciprocal type may be enabled or disabled individually.
  1666. // Check each input value for validity, concatenate them all back together,
  1667. // and pass through.
  1668. llvm::StringMap<bool> OptionStrings;
  1669. OptionStrings.insert(std::make_pair("divd", false));
  1670. OptionStrings.insert(std::make_pair("divf", false));
  1671. OptionStrings.insert(std::make_pair("vec-divd", false));
  1672. OptionStrings.insert(std::make_pair("vec-divf", false));
  1673. OptionStrings.insert(std::make_pair("sqrtd", false));
  1674. OptionStrings.insert(std::make_pair("sqrtf", false));
  1675. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  1676. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  1677. for (unsigned i = 0; i != NumOptions; ++i) {
  1678. StringRef Val = A->getValue(i);
  1679. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  1680. // Ignore the disablement token for string matching.
  1681. if (IsDisabled)
  1682. Val = Val.substr(1);
  1683. size_t RefStep;
  1684. if (!getRefinementStep(Val, D, *A, RefStep))
  1685. return;
  1686. StringRef ValBase = Val.slice(0, RefStep);
  1687. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  1688. if (OptionIter == OptionStrings.end()) {
  1689. // Try again specifying float suffix.
  1690. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  1691. if (OptionIter == OptionStrings.end()) {
  1692. // The input name did not match any known option string.
  1693. D.Diag(diag::err_drv_unknown_argument) << Val;
  1694. return;
  1695. }
  1696. // The option was specified without a float or double suffix.
  1697. // Make sure that the double entry was not already specified.
  1698. // The float entry will be checked below.
  1699. if (OptionStrings[ValBase.str() + 'd']) {
  1700. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1701. return;
  1702. }
  1703. }
  1704. if (OptionIter->second == true) {
  1705. // Duplicate option specified.
  1706. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1707. return;
  1708. }
  1709. // Mark the matched option as found. Do not allow duplicate specifiers.
  1710. OptionIter->second = true;
  1711. // If the precision was not specified, also mark the double entry as found.
  1712. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  1713. OptionStrings[ValBase.str() + 'd'] = true;
  1714. // Build the output string.
  1715. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  1716. Out = Args.MakeArgString(Out + Prefix + Val);
  1717. if (i != NumOptions - 1)
  1718. Out = Args.MakeArgString(Out + ",");
  1719. }
  1720. OutStrings.push_back(Args.MakeArgString(Out));
  1721. }
  1722. static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1723. const ArgList &Args,
  1724. std::vector<const char *> &Features) {
  1725. // If -march=native, autodetect the feature list.
  1726. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1727. if (StringRef(A->getValue()) == "native") {
  1728. llvm::StringMap<bool> HostFeatures;
  1729. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  1730. for (auto &F : HostFeatures)
  1731. Features.push_back(
  1732. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  1733. }
  1734. }
  1735. if (Triple.getArchName() == "x86_64h") {
  1736. // x86_64h implies quite a few of the more modern subtarget features
  1737. // for Haswell class CPUs, but not all of them. Opt-out of a few.
  1738. Features.push_back("-rdrnd");
  1739. Features.push_back("-aes");
  1740. Features.push_back("-pclmul");
  1741. Features.push_back("-rtm");
  1742. Features.push_back("-hle");
  1743. Features.push_back("-fsgsbase");
  1744. }
  1745. const llvm::Triple::ArchType ArchType = Triple.getArch();
  1746. // Add features to be compatible with gcc for Android.
  1747. if (Triple.isAndroid()) {
  1748. if (ArchType == llvm::Triple::x86_64) {
  1749. Features.push_back("+sse4.2");
  1750. Features.push_back("+popcnt");
  1751. } else
  1752. Features.push_back("+ssse3");
  1753. }
  1754. // Set features according to the -arch flag on MSVC.
  1755. if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1756. StringRef Arch = A->getValue();
  1757. bool ArchUsed = false;
  1758. // First, look for flags that are shared in x86 and x86-64.
  1759. if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
  1760. if (Arch == "AVX" || Arch == "AVX2") {
  1761. ArchUsed = true;
  1762. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1763. }
  1764. }
  1765. // Then, look for x86-specific flags.
  1766. if (ArchType == llvm::Triple::x86) {
  1767. if (Arch == "IA32") {
  1768. ArchUsed = true;
  1769. } else if (Arch == "SSE" || Arch == "SSE2") {
  1770. ArchUsed = true;
  1771. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1772. }
  1773. }
  1774. if (!ArchUsed)
  1775. D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
  1776. }
  1777. // Now add any that the user explicitly requested on the command line,
  1778. // which may override the defaults.
  1779. for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
  1780. StringRef Name = A->getOption().getName();
  1781. A->claim();
  1782. // Skip over "-m".
  1783. assert(Name.startswith("m") && "Invalid feature name.");
  1784. Name = Name.substr(1);
  1785. bool IsNegative = Name.startswith("no-");
  1786. if (IsNegative)
  1787. Name = Name.substr(3);
  1788. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  1789. }
  1790. }
  1791. void Clang::AddX86TargetArgs(const ArgList &Args,
  1792. ArgStringList &CmdArgs) const {
  1793. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1794. Args.hasArg(options::OPT_mkernel) ||
  1795. Args.hasArg(options::OPT_fapple_kext))
  1796. CmdArgs.push_back("-disable-red-zone");
  1797. // Default to avoid implicit floating-point for kernel/kext code, but allow
  1798. // that to be overridden with -mno-soft-float.
  1799. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  1800. Args.hasArg(options::OPT_fapple_kext));
  1801. if (Arg *A = Args.getLastArg(
  1802. options::OPT_msoft_float, options::OPT_mno_soft_float,
  1803. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  1804. const Option &O = A->getOption();
  1805. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  1806. O.matches(options::OPT_msoft_float));
  1807. }
  1808. if (NoImplicitFloat)
  1809. CmdArgs.push_back("-no-implicit-float");
  1810. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  1811. StringRef Value = A->getValue();
  1812. if (Value == "intel" || Value == "att") {
  1813. CmdArgs.push_back("-mllvm");
  1814. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  1815. } else {
  1816. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  1817. << A->getOption().getName() << Value;
  1818. }
  1819. }
  1820. }
  1821. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  1822. ArgStringList &CmdArgs) const {
  1823. CmdArgs.push_back("-mqdsp6-compat");
  1824. CmdArgs.push_back("-Wreturn-type");
  1825. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  1826. std::string N = llvm::utostr(G.getValue());
  1827. std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
  1828. CmdArgs.push_back("-mllvm");
  1829. CmdArgs.push_back(Args.MakeArgString(Opt));
  1830. }
  1831. if (!Args.hasArg(options::OPT_fno_short_enums))
  1832. CmdArgs.push_back("-fshort-enums");
  1833. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  1834. CmdArgs.push_back("-mllvm");
  1835. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  1836. }
  1837. CmdArgs.push_back("-mllvm");
  1838. CmdArgs.push_back("-machine-sink-split=0");
  1839. }
  1840. // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
  1841. static bool DecodeAArch64Features(const Driver &D, StringRef text,
  1842. std::vector<const char *> &Features) {
  1843. SmallVector<StringRef, 8> Split;
  1844. text.split(Split, StringRef("+"), -1, false);
  1845. for (StringRef Feature : Split) {
  1846. const char *result = llvm::StringSwitch<const char *>(Feature)
  1847. .Case("fp", "+fp-armv8")
  1848. .Case("simd", "+neon")
  1849. .Case("crc", "+crc")
  1850. .Case("crypto", "+crypto")
  1851. .Case("fp16", "+fullfp16")
  1852. .Case("profile", "+spe")
  1853. .Case("nofp", "-fp-armv8")
  1854. .Case("nosimd", "-neon")
  1855. .Case("nocrc", "-crc")
  1856. .Case("nocrypto", "-crypto")
  1857. .Case("nofp16", "-fullfp16")
  1858. .Case("noprofile", "-spe")
  1859. .Default(nullptr);
  1860. if (result)
  1861. Features.push_back(result);
  1862. else if (Feature == "neon" || Feature == "noneon")
  1863. D.Diag(diag::err_drv_no_neon_modifier);
  1864. else
  1865. return false;
  1866. }
  1867. return true;
  1868. }
  1869. // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
  1870. // decode CPU and feature.
  1871. static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
  1872. std::vector<const char *> &Features) {
  1873. std::pair<StringRef, StringRef> Split = Mcpu.split("+");
  1874. CPU = Split.first;
  1875. if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
  1876. CPU == "cortex-a72" || CPU == "cortex-a35") {
  1877. Features.push_back("+neon");
  1878. Features.push_back("+crc");
  1879. Features.push_back("+crypto");
  1880. } else if (CPU == "generic") {
  1881. Features.push_back("+neon");
  1882. } else {
  1883. return false;
  1884. }
  1885. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  1886. return false;
  1887. return true;
  1888. }
  1889. static bool
  1890. getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
  1891. const ArgList &Args,
  1892. std::vector<const char *> &Features) {
  1893. std::string MarchLowerCase = March.lower();
  1894. std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
  1895. if (Split.first == "armv8-a" || Split.first == "armv8a") {
  1896. // ok, no additional features.
  1897. } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
  1898. Features.push_back("+v8.1a");
  1899. } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
  1900. Features.push_back("+v8.2a");
  1901. } else {
  1902. return false;
  1903. }
  1904. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  1905. return false;
  1906. return true;
  1907. }
  1908. static bool
  1909. getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  1910. const ArgList &Args,
  1911. std::vector<const char *> &Features) {
  1912. StringRef CPU;
  1913. std::string McpuLowerCase = Mcpu.lower();
  1914. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
  1915. return false;
  1916. return true;
  1917. }
  1918. static bool
  1919. getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
  1920. const ArgList &Args,
  1921. std::vector<const char *> &Features) {
  1922. std::string MtuneLowerCase = Mtune.lower();
  1923. // Handle CPU name is 'native'.
  1924. if (MtuneLowerCase == "native")
  1925. MtuneLowerCase = llvm::sys::getHostCPUName();
  1926. if (MtuneLowerCase == "cyclone") {
  1927. Features.push_back("+zcm");
  1928. Features.push_back("+zcz");
  1929. }
  1930. return true;
  1931. }
  1932. static bool
  1933. getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  1934. const ArgList &Args,
  1935. std::vector<const char *> &Features) {
  1936. StringRef CPU;
  1937. std::vector<const char *> DecodedFeature;
  1938. std::string McpuLowerCase = Mcpu.lower();
  1939. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
  1940. return false;
  1941. return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
  1942. }
  1943. static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
  1944. std::vector<const char *> &Features) {
  1945. Arg *A;
  1946. bool success = true;
  1947. // Enable NEON by default.
  1948. Features.push_back("+neon");
  1949. if ((A = Args.getLastArg(options::OPT_march_EQ)))
  1950. success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
  1951. else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
  1952. success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  1953. else if (Args.hasArg(options::OPT_arch))
  1954. success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
  1955. Features);
  1956. if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
  1957. success =
  1958. getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
  1959. else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
  1960. success =
  1961. getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  1962. else if (Args.hasArg(options::OPT_arch))
  1963. success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
  1964. Args, Features);
  1965. if (!success)
  1966. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  1967. if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
  1968. Features.push_back("-fp-armv8");
  1969. Features.push_back("-crypto");
  1970. Features.push_back("-neon");
  1971. }
  1972. // En/disable crc
  1973. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  1974. if (A->getOption().matches(options::OPT_mcrc))
  1975. Features.push_back("+crc");
  1976. else
  1977. Features.push_back("-crc");
  1978. }
  1979. if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  1980. options::OPT_munaligned_access))
  1981. if (A->getOption().matches(options::OPT_mno_unaligned_access))
  1982. Features.push_back("+strict-align");
  1983. if (Args.hasArg(options::OPT_ffixed_x18))
  1984. Features.push_back("+reserve-x18");
  1985. }
  1986. static void getHexagonTargetFeatures(const ArgList &Args,
  1987. std::vector<const char *> &Features) {
  1988. bool HasHVX = false, HasHVXD = false;
  1989. for (auto &A : Args) {
  1990. auto &Opt = A->getOption();
  1991. if (Opt.matches(options::OPT_mhexagon_hvx))
  1992. HasHVX = true;
  1993. else if (Opt.matches(options::OPT_mno_hexagon_hvx))
  1994. HasHVXD = HasHVX = false;
  1995. else if (Opt.matches(options::OPT_mhexagon_hvx_double))
  1996. HasHVXD = HasHVX = true;
  1997. else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
  1998. HasHVXD = false;
  1999. else
  2000. continue;
  2001. A->claim();
  2002. }
  2003. Features.push_back(HasHVX ? "+hvx" : "-hvx");
  2004. Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
  2005. }
  2006. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  2007. std::vector<const char *> &Features) {
  2008. for (const Arg *A : Args.filtered(options::OPT_m_wasm_Features_Group)) {
  2009. StringRef Name = A->getOption().getName();
  2010. A->claim();
  2011. // Skip over "-m".
  2012. assert(Name.startswith("m") && "Invalid feature name.");
  2013. Name = Name.substr(1);
  2014. bool IsNegative = Name.startswith("no-");
  2015. if (IsNegative)
  2016. Name = Name.substr(3);
  2017. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  2018. }
  2019. }
  2020. static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  2021. const ArgList &Args, ArgStringList &CmdArgs,
  2022. bool ForAS) {
  2023. const Driver &D = TC.getDriver();
  2024. std::vector<const char *> Features;
  2025. switch (Triple.getArch()) {
  2026. default:
  2027. break;
  2028. case llvm::Triple::mips:
  2029. case llvm::Triple::mipsel:
  2030. case llvm::Triple::mips64:
  2031. case llvm::Triple::mips64el:
  2032. getMIPSTargetFeatures(D, Triple, Args, Features);
  2033. break;
  2034. case llvm::Triple::arm:
  2035. case llvm::Triple::armeb:
  2036. case llvm::Triple::thumb:
  2037. case llvm::Triple::thumbeb:
  2038. getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
  2039. break;
  2040. case llvm::Triple::ppc:
  2041. case llvm::Triple::ppc64:
  2042. case llvm::Triple::ppc64le:
  2043. getPPCTargetFeatures(D, Triple, Args, Features);
  2044. break;
  2045. case llvm::Triple::systemz:
  2046. getSystemZTargetFeatures(Args, Features);
  2047. break;
  2048. case llvm::Triple::aarch64:
  2049. case llvm::Triple::aarch64_be:
  2050. getAArch64TargetFeatures(D, Args, Features);
  2051. break;
  2052. case llvm::Triple::x86:
  2053. case llvm::Triple::x86_64:
  2054. getX86TargetFeatures(D, Triple, Args, Features);
  2055. break;
  2056. case llvm::Triple::hexagon:
  2057. getHexagonTargetFeatures(Args, Features);
  2058. break;
  2059. case llvm::Triple::wasm32:
  2060. case llvm::Triple::wasm64:
  2061. getWebAssemblyTargetFeatures(Args, Features);
  2062. break;
  2063. }
  2064. // Find the last of each feature.
  2065. llvm::StringMap<unsigned> LastOpt;
  2066. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2067. const char *Name = Features[I];
  2068. assert(Name[0] == '-' || Name[0] == '+');
  2069. LastOpt[Name + 1] = I;
  2070. }
  2071. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2072. // If this feature was overridden, ignore it.
  2073. const char *Name = Features[I];
  2074. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
  2075. assert(LastI != LastOpt.end());
  2076. unsigned Last = LastI->second;
  2077. if (Last != I)
  2078. continue;
  2079. CmdArgs.push_back("-target-feature");
  2080. CmdArgs.push_back(Name);
  2081. }
  2082. }
  2083. static bool
  2084. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  2085. const llvm::Triple &Triple) {
  2086. // We use the zero-cost exception tables for Objective-C if the non-fragile
  2087. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  2088. // later.
  2089. if (runtime.isNonFragile())
  2090. return true;
  2091. if (!Triple.isMacOSX())
  2092. return false;
  2093. return (!Triple.isMacOSXVersionLT(10, 5) &&
  2094. (Triple.getArch() == llvm::Triple::x86_64 ||
  2095. Triple.getArch() == llvm::Triple::arm));
  2096. }
  2097. /// Adds exception related arguments to the driver command arguments. There's a
  2098. /// master flag, -fexceptions and also language specific flags to enable/disable
  2099. /// C++ and Objective-C exceptions. This makes it possible to for example
  2100. /// disable C++ exceptions but enable Objective-C exceptions.
  2101. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  2102. const ToolChain &TC, bool KernelOrKext,
  2103. const ObjCRuntime &objcRuntime,
  2104. ArgStringList &CmdArgs) {
  2105. const Driver &D = TC.getDriver();
  2106. const llvm::Triple &Triple = TC.getTriple();
  2107. if (KernelOrKext) {
  2108. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  2109. // arguments now to avoid warnings about unused arguments.
  2110. Args.ClaimAllArgs(options::OPT_fexceptions);
  2111. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  2112. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  2113. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  2114. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  2115. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  2116. return;
  2117. }
  2118. // See if the user explicitly enabled exceptions.
  2119. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  2120. false);
  2121. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  2122. // is not necessarily sensible, but follows GCC.
  2123. if (types::isObjC(InputType) &&
  2124. Args.hasFlag(options::OPT_fobjc_exceptions,
  2125. options::OPT_fno_objc_exceptions, true)) {
  2126. CmdArgs.push_back("-fobjc-exceptions");
  2127. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  2128. }
  2129. if (types::isCXX(InputType)) {
  2130. // Disable C++ EH by default on XCore, PS4, and MSVC.
  2131. // FIXME: Remove MSVC from this list once things work.
  2132. bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
  2133. !Triple.isPS4CPU() &&
  2134. !Triple.isWindowsMSVCEnvironment();
  2135. Arg *ExceptionArg = Args.getLastArg(
  2136. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  2137. options::OPT_fexceptions, options::OPT_fno_exceptions);
  2138. if (ExceptionArg)
  2139. CXXExceptionsEnabled =
  2140. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  2141. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  2142. if (CXXExceptionsEnabled) {
  2143. if (Triple.isPS4CPU()) {
  2144. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  2145. assert(ExceptionArg &&
  2146. "On the PS4 exceptions should only be enabled if passing "
  2147. "an argument");
  2148. if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
  2149. const Arg *RTTIArg = TC.getRTTIArg();
  2150. assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
  2151. D.Diag(diag::err_drv_argument_not_allowed_with)
  2152. << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
  2153. } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
  2154. D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
  2155. } else
  2156. assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
  2157. CmdArgs.push_back("-fcxx-exceptions");
  2158. EH = true;
  2159. }
  2160. }
  2161. if (EH)
  2162. CmdArgs.push_back("-fexceptions");
  2163. }
  2164. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  2165. bool Default = true;
  2166. if (TC.getTriple().isOSDarwin()) {
  2167. // The native darwin assembler doesn't support the linker_option directives,
  2168. // so we disable them if we think the .s file will be passed to it.
  2169. Default = TC.useIntegratedAs();
  2170. }
  2171. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  2172. Default);
  2173. }
  2174. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  2175. const ToolChain &TC) {
  2176. bool UseDwarfDirectory =
  2177. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  2178. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  2179. return !UseDwarfDirectory;
  2180. }
  2181. /// \brief Check whether the given input tree contains any compilation actions.
  2182. static bool ContainsCompileAction(const Action *A) {
  2183. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  2184. return true;
  2185. for (const auto &Act : *A)
  2186. if (ContainsCompileAction(Act))
  2187. return true;
  2188. return false;
  2189. }
  2190. /// \brief Check if -relax-all should be passed to the internal assembler.
  2191. /// This is done by default when compiling non-assembler source with -O0.
  2192. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  2193. bool RelaxDefault = true;
  2194. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2195. RelaxDefault = A->getOption().matches(options::OPT_O0);
  2196. if (RelaxDefault) {
  2197. RelaxDefault = false;
  2198. for (const auto &Act : C.getActions()) {
  2199. if (ContainsCompileAction(Act)) {
  2200. RelaxDefault = true;
  2201. break;
  2202. }
  2203. }
  2204. }
  2205. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  2206. RelaxDefault);
  2207. }
  2208. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  2209. // on mismatch. The StringRef input (rather than an Arg) allows
  2210. // for use by the "-Xassembler" option parser.
  2211. static unsigned DwarfVersionNum(StringRef ArgValue) {
  2212. return llvm::StringSwitch<unsigned>(ArgValue)
  2213. .Case("-gdwarf-2", 2)
  2214. .Case("-gdwarf-3", 3)
  2215. .Case("-gdwarf-4", 4)
  2216. .Default(0);
  2217. }
  2218. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2219. CodeGenOptions::DebugInfoKind DebugInfoKind,
  2220. unsigned DwarfVersion) {
  2221. switch (DebugInfoKind) {
  2222. case CodeGenOptions::DebugLineTablesOnly:
  2223. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  2224. break;
  2225. case CodeGenOptions::LimitedDebugInfo:
  2226. CmdArgs.push_back("-debug-info-kind=limited");
  2227. break;
  2228. case CodeGenOptions::FullDebugInfo:
  2229. CmdArgs.push_back("-debug-info-kind=standalone");
  2230. break;
  2231. default:
  2232. break;
  2233. }
  2234. if (DwarfVersion > 0)
  2235. CmdArgs.push_back(
  2236. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  2237. }
  2238. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2239. const ArgList &Args,
  2240. ArgStringList &CmdArgs,
  2241. const Driver &D) {
  2242. if (UseRelaxAll(C, Args))
  2243. CmdArgs.push_back("-mrelax-all");
  2244. // When passing -I arguments to the assembler we sometimes need to
  2245. // unconditionally take the next argument. For example, when parsing
  2246. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2247. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2248. // arg after parsing the '-I' arg.
  2249. bool TakeNextArg = false;
  2250. // When using an integrated assembler, translate -Wa, and -Xassembler
  2251. // options.
  2252. bool CompressDebugSections = false;
  2253. for (const Arg *A :
  2254. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  2255. A->claim();
  2256. for (StringRef Value : A->getValues()) {
  2257. if (TakeNextArg) {
  2258. CmdArgs.push_back(Value.data());
  2259. TakeNextArg = false;
  2260. continue;
  2261. }
  2262. switch (C.getDefaultToolChain().getArch()) {
  2263. default:
  2264. break;
  2265. case llvm::Triple::mips:
  2266. case llvm::Triple::mipsel:
  2267. case llvm::Triple::mips64:
  2268. case llvm::Triple::mips64el:
  2269. if (Value == "--trap") {
  2270. CmdArgs.push_back("-target-feature");
  2271. CmdArgs.push_back("+use-tcc-in-div");
  2272. continue;
  2273. }
  2274. if (Value == "--break") {
  2275. CmdArgs.push_back("-target-feature");
  2276. CmdArgs.push_back("-use-tcc-in-div");
  2277. continue;
  2278. }
  2279. if (Value.startswith("-msoft-float")) {
  2280. CmdArgs.push_back("-target-feature");
  2281. CmdArgs.push_back("+soft-float");
  2282. continue;
  2283. }
  2284. if (Value.startswith("-mhard-float")) {
  2285. CmdArgs.push_back("-target-feature");
  2286. CmdArgs.push_back("-soft-float");
  2287. continue;
  2288. }
  2289. break;
  2290. }
  2291. if (Value == "-force_cpusubtype_ALL") {
  2292. // Do nothing, this is the default and we don't support anything else.
  2293. } else if (Value == "-L") {
  2294. CmdArgs.push_back("-msave-temp-labels");
  2295. } else if (Value == "--fatal-warnings") {
  2296. CmdArgs.push_back("-massembler-fatal-warnings");
  2297. } else if (Value == "--noexecstack") {
  2298. CmdArgs.push_back("-mnoexecstack");
  2299. } else if (Value == "-compress-debug-sections" ||
  2300. Value == "--compress-debug-sections") {
  2301. CompressDebugSections = true;
  2302. } else if (Value == "-nocompress-debug-sections" ||
  2303. Value == "--nocompress-debug-sections") {
  2304. CompressDebugSections = false;
  2305. } else if (Value.startswith("-I")) {
  2306. CmdArgs.push_back(Value.data());
  2307. // We need to consume the next argument if the current arg is a plain
  2308. // -I. The next arg will be the include directory.
  2309. if (Value == "-I")
  2310. TakeNextArg = true;
  2311. } else if (Value.startswith("-gdwarf-")) {
  2312. // "-gdwarf-N" options are not cc1as options.
  2313. unsigned DwarfVersion = DwarfVersionNum(Value);
  2314. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2315. CmdArgs.push_back(Value.data());
  2316. } else {
  2317. RenderDebugEnablingArgs(
  2318. Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion);
  2319. }
  2320. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2321. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2322. // Do nothing, we'll validate it later.
  2323. } else {
  2324. D.Diag(diag::err_drv_unsupported_option_argument)
  2325. << A->getOption().getName() << Value;
  2326. }
  2327. }
  2328. }
  2329. if (CompressDebugSections) {
  2330. if (llvm::zlib::isAvailable())
  2331. CmdArgs.push_back("-compress-debug-sections");
  2332. else
  2333. D.Diag(diag::warn_debug_compression_unavailable);
  2334. }
  2335. }
  2336. // This adds the static libclang_rt.builtins-arch.a directly to the command line
  2337. // FIXME: Make sure we can also emit shared objects if they're requested
  2338. // and available, check for possible errors, etc.
  2339. static void addClangRT(const ToolChain &TC, const ArgList &Args,
  2340. ArgStringList &CmdArgs) {
  2341. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  2342. }
  2343. namespace {
  2344. enum OpenMPRuntimeKind {
  2345. /// An unknown OpenMP runtime. We can't generate effective OpenMP code
  2346. /// without knowing what runtime to target.
  2347. OMPRT_Unknown,
  2348. /// The LLVM OpenMP runtime. When completed and integrated, this will become
  2349. /// the default for Clang.
  2350. OMPRT_OMP,
  2351. /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
  2352. /// this runtime but can swallow the pragmas, and find and link against the
  2353. /// runtime library itself.
  2354. OMPRT_GOMP,
  2355. /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
  2356. /// OpenMP runtime. We support this mode for users with existing dependencies
  2357. /// on this runtime library name.
  2358. OMPRT_IOMP5
  2359. };
  2360. }
  2361. /// Compute the desired OpenMP runtime from the flag provided.
  2362. static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
  2363. const ArgList &Args) {
  2364. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  2365. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  2366. if (A)
  2367. RuntimeName = A->getValue();
  2368. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  2369. .Case("libomp", OMPRT_OMP)
  2370. .Case("libgomp", OMPRT_GOMP)
  2371. .Case("libiomp5", OMPRT_IOMP5)
  2372. .Default(OMPRT_Unknown);
  2373. if (RT == OMPRT_Unknown) {
  2374. if (A)
  2375. TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
  2376. << A->getOption().getName() << A->getValue();
  2377. else
  2378. // FIXME: We could use a nicer diagnostic here.
  2379. TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  2380. }
  2381. return RT;
  2382. }
  2383. static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  2384. const ArgList &Args) {
  2385. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  2386. options::OPT_fno_openmp, false))
  2387. return;
  2388. switch (getOpenMPRuntime(TC, Args)) {
  2389. case OMPRT_OMP:
  2390. CmdArgs.push_back("-lomp");
  2391. break;
  2392. case OMPRT_GOMP:
  2393. CmdArgs.push_back("-lgomp");
  2394. break;
  2395. case OMPRT_IOMP5:
  2396. CmdArgs.push_back("-liomp5");
  2397. break;
  2398. case OMPRT_Unknown:
  2399. // Already diagnosed.
  2400. break;
  2401. }
  2402. }
  2403. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  2404. ArgStringList &CmdArgs, StringRef Sanitizer,
  2405. bool IsShared) {
  2406. // Static runtimes must be forced into executable, so we wrap them in
  2407. // whole-archive.
  2408. if (!IsShared) CmdArgs.push_back("-whole-archive");
  2409. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
  2410. if (!IsShared) CmdArgs.push_back("-no-whole-archive");
  2411. }
  2412. // Tries to use a file with the list of dynamic symbols that need to be exported
  2413. // from the runtime library. Returns true if the file was found.
  2414. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  2415. ArgStringList &CmdArgs,
  2416. StringRef Sanitizer) {
  2417. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  2418. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  2419. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  2420. return true;
  2421. }
  2422. return false;
  2423. }
  2424. static void linkSanitizerRuntimeDeps(const ToolChain &TC,
  2425. ArgStringList &CmdArgs) {
  2426. // Force linking against the system libraries sanitizers depends on
  2427. // (see PR15823 why this is necessary).
  2428. CmdArgs.push_back("--no-as-needed");
  2429. CmdArgs.push_back("-lpthread");
  2430. CmdArgs.push_back("-lrt");
  2431. CmdArgs.push_back("-lm");
  2432. // There's no libdl on FreeBSD.
  2433. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
  2434. CmdArgs.push_back("-ldl");
  2435. }
  2436. static void
  2437. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2438. SmallVectorImpl<StringRef> &SharedRuntimes,
  2439. SmallVectorImpl<StringRef> &StaticRuntimes,
  2440. SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
  2441. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2442. // Collect shared runtimes.
  2443. if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
  2444. SharedRuntimes.push_back("asan");
  2445. }
  2446. // Collect static runtimes.
  2447. if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
  2448. // Don't link static runtimes into DSOs or if compiling for Android.
  2449. return;
  2450. }
  2451. if (SanArgs.needsAsanRt()) {
  2452. if (SanArgs.needsSharedAsanRt()) {
  2453. HelperStaticRuntimes.push_back("asan-preinit");
  2454. } else {
  2455. StaticRuntimes.push_back("asan");
  2456. if (SanArgs.linkCXXRuntimes())
  2457. StaticRuntimes.push_back("asan_cxx");
  2458. }
  2459. }
  2460. if (SanArgs.needsDfsanRt())
  2461. StaticRuntimes.push_back("dfsan");
  2462. if (SanArgs.needsLsanRt())
  2463. StaticRuntimes.push_back("lsan");
  2464. if (SanArgs.needsMsanRt()) {
  2465. StaticRuntimes.push_back("msan");
  2466. if (SanArgs.linkCXXRuntimes())
  2467. StaticRuntimes.push_back("msan_cxx");
  2468. }
  2469. if (SanArgs.needsTsanRt()) {
  2470. StaticRuntimes.push_back("tsan");
  2471. if (SanArgs.linkCXXRuntimes())
  2472. StaticRuntimes.push_back("tsan_cxx");
  2473. }
  2474. if (SanArgs.needsUbsanRt()) {
  2475. StaticRuntimes.push_back("ubsan_standalone");
  2476. if (SanArgs.linkCXXRuntimes())
  2477. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2478. }
  2479. if (SanArgs.needsSafeStackRt())
  2480. StaticRuntimes.push_back("safestack");
  2481. if (SanArgs.needsCfiRt())
  2482. StaticRuntimes.push_back("cfi");
  2483. }
  2484. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  2485. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  2486. static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2487. ArgStringList &CmdArgs) {
  2488. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  2489. HelperStaticRuntimes;
  2490. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  2491. HelperStaticRuntimes);
  2492. for (auto RT : SharedRuntimes)
  2493. addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
  2494. for (auto RT : HelperStaticRuntimes)
  2495. addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
  2496. bool AddExportDynamic = false;
  2497. for (auto RT : StaticRuntimes) {
  2498. addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
  2499. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2500. }
  2501. // If there is a static runtime with no dynamic list, force all the symbols
  2502. // to be dynamic to be sure we export sanitizer interface functions.
  2503. if (AddExportDynamic)
  2504. CmdArgs.push_back("-export-dynamic");
  2505. return !StaticRuntimes.empty();
  2506. }
  2507. static bool areOptimizationsEnabled(const ArgList &Args) {
  2508. // Find the last -O arg and see if it is non-zero.
  2509. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2510. return !A->getOption().matches(options::OPT_O0);
  2511. // Defaults to -O0.
  2512. return false;
  2513. }
  2514. static bool shouldUseFramePointerForTarget(const ArgList &Args,
  2515. const llvm::Triple &Triple) {
  2516. switch (Triple.getArch()) {
  2517. case llvm::Triple::xcore:
  2518. case llvm::Triple::wasm32:
  2519. case llvm::Triple::wasm64:
  2520. // XCore never wants frame pointers, regardless of OS.
  2521. // WebAssembly never wants frame pointers.
  2522. return false;
  2523. default:
  2524. break;
  2525. }
  2526. if (Triple.isOSLinux()) {
  2527. switch (Triple.getArch()) {
  2528. // Don't use a frame pointer on linux if optimizing for certain targets.
  2529. case llvm::Triple::mips64:
  2530. case llvm::Triple::mips64el:
  2531. case llvm::Triple::mips:
  2532. case llvm::Triple::mipsel:
  2533. case llvm::Triple::systemz:
  2534. case llvm::Triple::x86:
  2535. case llvm::Triple::x86_64:
  2536. return !areOptimizationsEnabled(Args);
  2537. default:
  2538. return true;
  2539. }
  2540. }
  2541. if (Triple.isOSWindows()) {
  2542. switch (Triple.getArch()) {
  2543. case llvm::Triple::x86:
  2544. return !areOptimizationsEnabled(Args);
  2545. case llvm::Triple::arm:
  2546. case llvm::Triple::thumb:
  2547. // Windows on ARM builds with FPO disabled to aid fast stack walking
  2548. return true;
  2549. default:
  2550. // All other supported Windows ISAs use xdata unwind information, so frame
  2551. // pointers are not generally useful.
  2552. return false;
  2553. }
  2554. }
  2555. return true;
  2556. }
  2557. static bool shouldUseFramePointer(const ArgList &Args,
  2558. const llvm::Triple &Triple) {
  2559. if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
  2560. options::OPT_fomit_frame_pointer))
  2561. return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
  2562. if (Args.hasArg(options::OPT_pg))
  2563. return true;
  2564. return shouldUseFramePointerForTarget(Args, Triple);
  2565. }
  2566. static bool shouldUseLeafFramePointer(const ArgList &Args,
  2567. const llvm::Triple &Triple) {
  2568. if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
  2569. options::OPT_momit_leaf_frame_pointer))
  2570. return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
  2571. if (Args.hasArg(options::OPT_pg))
  2572. return true;
  2573. if (Triple.isPS4CPU())
  2574. return false;
  2575. return shouldUseFramePointerForTarget(Args, Triple);
  2576. }
  2577. /// Add a CC1 option to specify the debug compilation directory.
  2578. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
  2579. SmallString<128> cwd;
  2580. if (!llvm::sys::fs::current_path(cwd)) {
  2581. CmdArgs.push_back("-fdebug-compilation-dir");
  2582. CmdArgs.push_back(Args.MakeArgString(cwd));
  2583. }
  2584. }
  2585. static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
  2586. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  2587. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  2588. SmallString<128> T(FinalOutput->getValue());
  2589. llvm::sys::path::replace_extension(T, "dwo");
  2590. return Args.MakeArgString(T);
  2591. } else {
  2592. // Use the compilation dir.
  2593. SmallString<128> T(
  2594. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  2595. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  2596. llvm::sys::path::replace_extension(F, "dwo");
  2597. T += F;
  2598. return Args.MakeArgString(F);
  2599. }
  2600. }
  2601. static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  2602. const JobAction &JA, const ArgList &Args,
  2603. const InputInfo &Output, const char *OutFile) {
  2604. ArgStringList ExtractArgs;
  2605. ExtractArgs.push_back("--extract-dwo");
  2606. ArgStringList StripArgs;
  2607. StripArgs.push_back("--strip-dwo");
  2608. // Grabbing the output of the earlier compile step.
  2609. StripArgs.push_back(Output.getFilename());
  2610. ExtractArgs.push_back(Output.getFilename());
  2611. ExtractArgs.push_back(OutFile);
  2612. const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
  2613. InputInfo II(Output.getFilename(), types::TY_Object, Output.getFilename());
  2614. // First extract the dwo sections.
  2615. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  2616. // Then remove them from the original .o file.
  2617. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
  2618. }
  2619. /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
  2620. /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
  2621. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  2622. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  2623. if (A->getOption().matches(options::OPT_O4) ||
  2624. A->getOption().matches(options::OPT_Ofast))
  2625. return true;
  2626. if (A->getOption().matches(options::OPT_O0))
  2627. return false;
  2628. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  2629. // Vectorize -Os.
  2630. StringRef S(A->getValue());
  2631. if (S == "s")
  2632. return true;
  2633. // Don't vectorize -Oz, unless it's the slp vectorizer.
  2634. if (S == "z")
  2635. return isSlpVec;
  2636. unsigned OptLevel = 0;
  2637. if (S.getAsInteger(10, OptLevel))
  2638. return false;
  2639. return OptLevel > 1;
  2640. }
  2641. return false;
  2642. }
  2643. /// Add -x lang to \p CmdArgs for \p Input.
  2644. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  2645. ArgStringList &CmdArgs) {
  2646. // When using -verify-pch, we don't want to provide the type
  2647. // 'precompiled-header' if it was inferred from the file extension
  2648. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  2649. return;
  2650. CmdArgs.push_back("-x");
  2651. if (Args.hasArg(options::OPT_rewrite_objc))
  2652. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  2653. else
  2654. CmdArgs.push_back(types::getTypeName(Input.getType()));
  2655. }
  2656. static VersionTuple getMSCompatibilityVersion(unsigned Version) {
  2657. if (Version < 100)
  2658. return VersionTuple(Version);
  2659. if (Version < 10000)
  2660. return VersionTuple(Version / 100, Version % 100);
  2661. unsigned Build = 0, Factor = 1;
  2662. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  2663. Build = Build + (Version % 10) * Factor;
  2664. return VersionTuple(Version / 100, Version % 100, Build);
  2665. }
  2666. // Claim options we don't want to warn if they are unused. We do this for
  2667. // options that build systems might add but are unused when assembling or only
  2668. // running the preprocessor for example.
  2669. static void claimNoWarnArgs(const ArgList &Args) {
  2670. // Don't warn about unused -f(no-)?lto. This can happen when we're
  2671. // preprocessing, precompiling or assembling.
  2672. Args.ClaimAllArgs(options::OPT_flto_EQ);
  2673. Args.ClaimAllArgs(options::OPT_flto);
  2674. Args.ClaimAllArgs(options::OPT_fno_lto);
  2675. }
  2676. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  2677. #ifdef LLVM_ON_UNIX
  2678. const char *Username = getenv("LOGNAME");
  2679. #else
  2680. const char *Username = getenv("USERNAME");
  2681. #endif
  2682. if (Username) {
  2683. // Validate that LoginName can be used in a path, and get its length.
  2684. size_t Len = 0;
  2685. for (const char *P = Username; *P; ++P, ++Len) {
  2686. if (!isAlphanumeric(*P) && *P != '_') {
  2687. Username = nullptr;
  2688. break;
  2689. }
  2690. }
  2691. if (Username && Len > 0) {
  2692. Result.append(Username, Username + Len);
  2693. return;
  2694. }
  2695. }
  2696. // Fallback to user id.
  2697. #ifdef LLVM_ON_UNIX
  2698. std::string UID = llvm::utostr(getuid());
  2699. #else
  2700. // FIXME: Windows seems to have an 'SID' that might work.
  2701. std::string UID = "9999";
  2702. #endif
  2703. Result.append(UID.begin(), UID.end());
  2704. }
  2705. VersionTuple visualstudio::getMSVCVersion(const Driver *D,
  2706. const llvm::Triple &Triple,
  2707. const llvm::opt::ArgList &Args,
  2708. bool IsWindowsMSVC) {
  2709. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  2710. IsWindowsMSVC) ||
  2711. Args.hasArg(options::OPT_fmsc_version) ||
  2712. Args.hasArg(options::OPT_fms_compatibility_version)) {
  2713. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  2714. const Arg *MSCompatibilityVersion =
  2715. Args.getLastArg(options::OPT_fms_compatibility_version);
  2716. if (MSCVersion && MSCompatibilityVersion) {
  2717. if (D)
  2718. D->Diag(diag::err_drv_argument_not_allowed_with)
  2719. << MSCVersion->getAsString(Args)
  2720. << MSCompatibilityVersion->getAsString(Args);
  2721. return VersionTuple();
  2722. }
  2723. if (MSCompatibilityVersion) {
  2724. VersionTuple MSVT;
  2725. if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
  2726. D->Diag(diag::err_drv_invalid_value)
  2727. << MSCompatibilityVersion->getAsString(Args)
  2728. << MSCompatibilityVersion->getValue();
  2729. return MSVT;
  2730. }
  2731. if (MSCVersion) {
  2732. unsigned Version = 0;
  2733. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
  2734. D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
  2735. << MSCVersion->getValue();
  2736. return getMSCompatibilityVersion(Version);
  2737. }
  2738. unsigned Major, Minor, Micro;
  2739. Triple.getEnvironmentVersion(Major, Minor, Micro);
  2740. if (Major || Minor || Micro)
  2741. return VersionTuple(Major, Minor, Micro);
  2742. return VersionTuple(18);
  2743. }
  2744. return VersionTuple();
  2745. }
  2746. static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
  2747. const InputInfo &Output, const ArgList &Args,
  2748. ArgStringList &CmdArgs) {
  2749. auto *ProfileGenerateArg = Args.getLastArg(
  2750. options::OPT_fprofile_instr_generate,
  2751. options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
  2752. options::OPT_fprofile_generate_EQ,
  2753. options::OPT_fno_profile_instr_generate);
  2754. if (ProfileGenerateArg &&
  2755. ProfileGenerateArg->getOption().matches(
  2756. options::OPT_fno_profile_instr_generate))
  2757. ProfileGenerateArg = nullptr;
  2758. auto *ProfileUseArg = Args.getLastArg(
  2759. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  2760. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  2761. options::OPT_fno_profile_instr_use);
  2762. if (ProfileUseArg &&
  2763. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  2764. ProfileUseArg = nullptr;
  2765. if (ProfileGenerateArg && ProfileUseArg)
  2766. D.Diag(diag::err_drv_argument_not_allowed_with)
  2767. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  2768. if (ProfileGenerateArg) {
  2769. if (ProfileGenerateArg->getOption().matches(
  2770. options::OPT_fprofile_instr_generate_EQ))
  2771. ProfileGenerateArg->render(Args, CmdArgs);
  2772. else if (ProfileGenerateArg->getOption().matches(
  2773. options::OPT_fprofile_generate_EQ)) {
  2774. SmallString<128> Path(ProfileGenerateArg->getValue());
  2775. llvm::sys::path::append(Path, "default.profraw");
  2776. CmdArgs.push_back(
  2777. Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
  2778. } else
  2779. Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
  2780. }
  2781. if (ProfileUseArg) {
  2782. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  2783. ProfileUseArg->render(Args, CmdArgs);
  2784. else if ((ProfileUseArg->getOption().matches(
  2785. options::OPT_fprofile_use_EQ) ||
  2786. ProfileUseArg->getOption().matches(
  2787. options::OPT_fprofile_instr_use))) {
  2788. SmallString<128> Path(
  2789. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  2790. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  2791. llvm::sys::path::append(Path, "default.profdata");
  2792. CmdArgs.push_back(
  2793. Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
  2794. }
  2795. }
  2796. if (Args.hasArg(options::OPT_ftest_coverage) ||
  2797. Args.hasArg(options::OPT_coverage))
  2798. CmdArgs.push_back("-femit-coverage-notes");
  2799. if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  2800. false) ||
  2801. Args.hasArg(options::OPT_coverage))
  2802. CmdArgs.push_back("-femit-coverage-data");
  2803. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  2804. options::OPT_fno_coverage_mapping, false) &&
  2805. !ProfileGenerateArg)
  2806. D.Diag(diag::err_drv_argument_only_allowed_with)
  2807. << "-fcoverage-mapping"
  2808. << "-fprofile-instr-generate";
  2809. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  2810. options::OPT_fno_coverage_mapping, false))
  2811. CmdArgs.push_back("-fcoverage-mapping");
  2812. if (C.getArgs().hasArg(options::OPT_c) ||
  2813. C.getArgs().hasArg(options::OPT_S)) {
  2814. if (Output.isFilename()) {
  2815. CmdArgs.push_back("-coverage-file");
  2816. SmallString<128> CoverageFilename;
  2817. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
  2818. CoverageFilename = FinalOutput->getValue();
  2819. } else {
  2820. CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
  2821. }
  2822. if (llvm::sys::path::is_relative(CoverageFilename)) {
  2823. SmallString<128> Pwd;
  2824. if (!llvm::sys::fs::current_path(Pwd)) {
  2825. llvm::sys::path::append(Pwd, CoverageFilename);
  2826. CoverageFilename.swap(Pwd);
  2827. }
  2828. }
  2829. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  2830. }
  2831. }
  2832. }
  2833. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  2834. /// smooshes them together with platform defaults, to decide whether
  2835. /// this compile should be using PIC mode or not. Returns a tuple of
  2836. /// (RelocationModel, PICLevel, IsPIE).
  2837. static std::tuple<llvm::Reloc::Model, unsigned, bool>
  2838. ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
  2839. const ArgList &Args) {
  2840. // FIXME: why does this code...and so much everywhere else, use both
  2841. // ToolChain.getTriple() and Triple?
  2842. bool PIE = ToolChain.isPIEDefault();
  2843. bool PIC = PIE || ToolChain.isPICDefault();
  2844. bool IsPICLevelTwo = PIC;
  2845. bool KernelOrKext =
  2846. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  2847. // Android-specific defaults for PIC/PIE
  2848. if (ToolChain.getTriple().isAndroid()) {
  2849. switch (ToolChain.getArch()) {
  2850. case llvm::Triple::arm:
  2851. case llvm::Triple::armeb:
  2852. case llvm::Triple::thumb:
  2853. case llvm::Triple::thumbeb:
  2854. case llvm::Triple::aarch64:
  2855. case llvm::Triple::mips:
  2856. case llvm::Triple::mipsel:
  2857. case llvm::Triple::mips64:
  2858. case llvm::Triple::mips64el:
  2859. PIC = true; // "-fpic"
  2860. break;
  2861. case llvm::Triple::x86:
  2862. case llvm::Triple::x86_64:
  2863. PIC = true; // "-fPIC"
  2864. IsPICLevelTwo = true;
  2865. break;
  2866. default:
  2867. break;
  2868. }
  2869. }
  2870. // OpenBSD-specific defaults for PIE
  2871. if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
  2872. switch (ToolChain.getArch()) {
  2873. case llvm::Triple::mips64:
  2874. case llvm::Triple::mips64el:
  2875. case llvm::Triple::sparcel:
  2876. case llvm::Triple::x86:
  2877. case llvm::Triple::x86_64:
  2878. IsPICLevelTwo = false; // "-fpie"
  2879. break;
  2880. case llvm::Triple::ppc:
  2881. case llvm::Triple::sparc:
  2882. case llvm::Triple::sparcv9:
  2883. IsPICLevelTwo = true; // "-fPIE"
  2884. break;
  2885. default:
  2886. break;
  2887. }
  2888. }
  2889. // The last argument relating to either PIC or PIE wins, and no
  2890. // other argument is used. If the last argument is any flavor of the
  2891. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  2892. // option implicitly enables PIC at the same level.
  2893. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  2894. options::OPT_fpic, options::OPT_fno_pic,
  2895. options::OPT_fPIE, options::OPT_fno_PIE,
  2896. options::OPT_fpie, options::OPT_fno_pie);
  2897. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  2898. // is forced, then neither PIC nor PIE flags will have no effect.
  2899. if (!ToolChain.isPICDefaultForced()) {
  2900. if (LastPICArg) {
  2901. Option O = LastPICArg->getOption();
  2902. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  2903. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  2904. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  2905. PIC =
  2906. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  2907. IsPICLevelTwo =
  2908. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  2909. } else {
  2910. PIE = PIC = false;
  2911. if (Triple.isPS4CPU()) {
  2912. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  2913. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  2914. if (Model != "kernel") {
  2915. PIC = true;
  2916. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  2917. << LastPICArg->getSpelling();
  2918. }
  2919. }
  2920. }
  2921. }
  2922. }
  2923. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  2924. // PIC level would've been set to level 1, force it back to level 2 PIC
  2925. // instead.
  2926. if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
  2927. IsPICLevelTwo |= ToolChain.isPICDefault();
  2928. // This kernel flags are a trump-card: they will disable PIC/PIE
  2929. // generation, independent of the argument order.
  2930. if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  2931. !Triple.isWatchOS()))
  2932. PIC = PIE = false;
  2933. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  2934. // This is a very special mode. It trumps the other modes, almost no one
  2935. // uses it, and it isn't even valid on any OS but Darwin.
  2936. if (!ToolChain.getTriple().isOSDarwin())
  2937. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  2938. << A->getSpelling() << ToolChain.getTriple().str();
  2939. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  2940. // Only a forced PIC mode can cause the actual compile to have PIC defines
  2941. // etc., no flags are sufficient. This behavior was selected to closely
  2942. // match that of llvm-gcc and Apple GCC before that.
  2943. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  2944. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
  2945. }
  2946. if (PIC)
  2947. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
  2948. return std::make_tuple(llvm::Reloc::Static, 0, false);
  2949. }
  2950. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  2951. switch (Model) {
  2952. case llvm::Reloc::Default:
  2953. return nullptr;
  2954. case llvm::Reloc::Static:
  2955. return "static";
  2956. case llvm::Reloc::PIC_:
  2957. return "pic";
  2958. case llvm::Reloc::DynamicNoPIC:
  2959. return "dynamic-no-pic";
  2960. }
  2961. llvm_unreachable("Unknown Reloc::Model kind");
  2962. }
  2963. static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  2964. ArgStringList &CmdArgs) {
  2965. llvm::Reloc::Model RelocationModel;
  2966. unsigned PICLevel;
  2967. bool IsPIE;
  2968. std::tie(RelocationModel, PICLevel, IsPIE) =
  2969. ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
  2970. if (RelocationModel != llvm::Reloc::Static)
  2971. CmdArgs.push_back("-KPIC");
  2972. }
  2973. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  2974. const InputInfo &Output, const InputInfoList &Inputs,
  2975. const ArgList &Args, const char *LinkingOutput) const {
  2976. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  2977. const llvm::Triple Triple(TripleStr);
  2978. bool KernelOrKext =
  2979. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  2980. const Driver &D = getToolChain().getDriver();
  2981. ArgStringList CmdArgs;
  2982. bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
  2983. bool IsWindowsCygnus =
  2984. getToolChain().getTriple().isWindowsCygwinEnvironment();
  2985. bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
  2986. bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
  2987. // Check number of inputs for sanity. We need at least one input.
  2988. assert(Inputs.size() >= 1 && "Must have at least one input.");
  2989. const InputInfo &Input = Inputs[0];
  2990. // CUDA compilation may have multiple inputs (source file + results of
  2991. // device-side compilations). All other jobs are expected to have exactly one
  2992. // input.
  2993. bool IsCuda = types::isCuda(Input.getType());
  2994. assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
  2995. // Invoke ourselves in -cc1 mode.
  2996. //
  2997. // FIXME: Implement custom jobs for internal actions.
  2998. CmdArgs.push_back("-cc1");
  2999. // Add the "effective" target triple.
  3000. CmdArgs.push_back("-triple");
  3001. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  3002. const ToolChain *AuxToolChain = nullptr;
  3003. if (IsCuda) {
  3004. // FIXME: We need a (better) way to pass information about
  3005. // particular compilation pass we're constructing here. For now we
  3006. // can check which toolchain we're using and pick the other one to
  3007. // extract the triple.
  3008. if (&getToolChain() == C.getCudaDeviceToolChain())
  3009. AuxToolChain = C.getCudaHostToolChain();
  3010. else if (&getToolChain() == C.getCudaHostToolChain())
  3011. AuxToolChain = C.getCudaDeviceToolChain();
  3012. else
  3013. llvm_unreachable("Can't figure out CUDA compilation mode.");
  3014. assert(AuxToolChain != nullptr && "No aux toolchain.");
  3015. CmdArgs.push_back("-aux-triple");
  3016. CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
  3017. CmdArgs.push_back("-fcuda-target-overloads");
  3018. CmdArgs.push_back("-fcuda-disable-target-call-checks");
  3019. }
  3020. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  3021. Triple.getArch() == llvm::Triple::thumb)) {
  3022. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  3023. unsigned Version;
  3024. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  3025. if (Version < 7)
  3026. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  3027. << TripleStr;
  3028. }
  3029. // Push all default warning arguments that are specific to
  3030. // the given target. These come before user provided warning options
  3031. // are provided.
  3032. getToolChain().addClangWarningOptions(CmdArgs);
  3033. // Select the appropriate action.
  3034. RewriteKind rewriteKind = RK_None;
  3035. if (isa<AnalyzeJobAction>(JA)) {
  3036. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  3037. CmdArgs.push_back("-analyze");
  3038. } else if (isa<MigrateJobAction>(JA)) {
  3039. CmdArgs.push_back("-migrate");
  3040. } else if (isa<PreprocessJobAction>(JA)) {
  3041. if (Output.getType() == types::TY_Dependencies)
  3042. CmdArgs.push_back("-Eonly");
  3043. else {
  3044. CmdArgs.push_back("-E");
  3045. if (Args.hasArg(options::OPT_rewrite_objc) &&
  3046. !Args.hasArg(options::OPT_g_Group))
  3047. CmdArgs.push_back("-P");
  3048. }
  3049. } else if (isa<AssembleJobAction>(JA)) {
  3050. CmdArgs.push_back("-emit-obj");
  3051. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  3052. // Also ignore explicit -force_cpusubtype_ALL option.
  3053. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  3054. } else if (isa<PrecompileJobAction>(JA)) {
  3055. // Use PCH if the user requested it.
  3056. bool UsePCH = D.CCCUsePCH;
  3057. if (JA.getType() == types::TY_Nothing)
  3058. CmdArgs.push_back("-fsyntax-only");
  3059. else if (UsePCH)
  3060. CmdArgs.push_back("-emit-pch");
  3061. else
  3062. CmdArgs.push_back("-emit-pth");
  3063. } else if (isa<VerifyPCHJobAction>(JA)) {
  3064. CmdArgs.push_back("-verify-pch");
  3065. } else {
  3066. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  3067. "Invalid action for clang tool.");
  3068. if (JA.getType() == types::TY_Nothing) {
  3069. CmdArgs.push_back("-fsyntax-only");
  3070. } else if (JA.getType() == types::TY_LLVM_IR ||
  3071. JA.getType() == types::TY_LTO_IR) {
  3072. CmdArgs.push_back("-emit-llvm");
  3073. } else if (JA.getType() == types::TY_LLVM_BC ||
  3074. JA.getType() == types::TY_LTO_BC) {
  3075. CmdArgs.push_back("-emit-llvm-bc");
  3076. } else if (JA.getType() == types::TY_PP_Asm) {
  3077. CmdArgs.push_back("-S");
  3078. } else if (JA.getType() == types::TY_AST) {
  3079. CmdArgs.push_back("-emit-pch");
  3080. } else if (JA.getType() == types::TY_ModuleFile) {
  3081. CmdArgs.push_back("-module-file-info");
  3082. } else if (JA.getType() == types::TY_RewrittenObjC) {
  3083. CmdArgs.push_back("-rewrite-objc");
  3084. rewriteKind = RK_NonFragile;
  3085. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  3086. CmdArgs.push_back("-rewrite-objc");
  3087. rewriteKind = RK_Fragile;
  3088. } else {
  3089. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  3090. }
  3091. // Preserve use-list order by default when emitting bitcode, so that
  3092. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  3093. // same result as running passes here. For LTO, we don't need to preserve
  3094. // the use-list order, since serialization to bitcode is part of the flow.
  3095. if (JA.getType() == types::TY_LLVM_BC)
  3096. CmdArgs.push_back("-emit-llvm-uselists");
  3097. if (D.isUsingLTO())
  3098. Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
  3099. }
  3100. if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
  3101. if (!types::isLLVMIR(Input.getType()))
  3102. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3103. << "-x ir";
  3104. Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
  3105. }
  3106. // We normally speed up the clang process a bit by skipping destructors at
  3107. // exit, but when we're generating diagnostics we can rely on some of the
  3108. // cleanup.
  3109. if (!C.isForDiagnostics())
  3110. CmdArgs.push_back("-disable-free");
  3111. // Disable the verification pass in -asserts builds.
  3112. #ifdef NDEBUG
  3113. CmdArgs.push_back("-disable-llvm-verifier");
  3114. #endif
  3115. // Set the main file name, so that debug info works even with
  3116. // -save-temps.
  3117. CmdArgs.push_back("-main-file-name");
  3118. CmdArgs.push_back(getBaseInputName(Args, Input));
  3119. // Some flags which affect the language (via preprocessor
  3120. // defines).
  3121. if (Args.hasArg(options::OPT_static))
  3122. CmdArgs.push_back("-static-define");
  3123. if (isa<AnalyzeJobAction>(JA)) {
  3124. // Enable region store model by default.
  3125. CmdArgs.push_back("-analyzer-store=region");
  3126. // Treat blocks as analysis entry points.
  3127. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  3128. CmdArgs.push_back("-analyzer-eagerly-assume");
  3129. // Add default argument set.
  3130. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  3131. CmdArgs.push_back("-analyzer-checker=core");
  3132. if (!IsWindowsMSVC)
  3133. CmdArgs.push_back("-analyzer-checker=unix");
  3134. if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
  3135. CmdArgs.push_back("-analyzer-checker=osx");
  3136. CmdArgs.push_back("-analyzer-checker=deadcode");
  3137. if (types::isCXX(Input.getType()))
  3138. CmdArgs.push_back("-analyzer-checker=cplusplus");
  3139. // Enable the following experimental checkers for testing.
  3140. CmdArgs.push_back(
  3141. "-analyzer-checker=security.insecureAPI.UncheckedReturn");
  3142. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  3143. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  3144. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  3145. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  3146. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  3147. // Default nullability checks.
  3148. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  3149. CmdArgs.push_back(
  3150. "-analyzer-checker=nullability.NullReturnedFromNonnull");
  3151. }
  3152. // Set the output format. The default is plist, for (lame) historical
  3153. // reasons.
  3154. CmdArgs.push_back("-analyzer-output");
  3155. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  3156. CmdArgs.push_back(A->getValue());
  3157. else
  3158. CmdArgs.push_back("plist");
  3159. // Disable the presentation of standard compiler warnings when
  3160. // using --analyze. We only want to show static analyzer diagnostics
  3161. // or frontend errors.
  3162. CmdArgs.push_back("-w");
  3163. // Add -Xanalyzer arguments when running as analyzer.
  3164. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  3165. }
  3166. CheckCodeGenerationOptions(D, Args);
  3167. llvm::Reloc::Model RelocationModel;
  3168. unsigned PICLevel;
  3169. bool IsPIE;
  3170. std::tie(RelocationModel, PICLevel, IsPIE) =
  3171. ParsePICArgs(getToolChain(), Triple, Args);
  3172. const char *RMName = RelocationModelName(RelocationModel);
  3173. if (RMName) {
  3174. CmdArgs.push_back("-mrelocation-model");
  3175. CmdArgs.push_back(RMName);
  3176. }
  3177. if (PICLevel > 0) {
  3178. CmdArgs.push_back("-pic-level");
  3179. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3180. if (IsPIE) {
  3181. CmdArgs.push_back("-pie-level");
  3182. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3183. }
  3184. }
  3185. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  3186. CmdArgs.push_back("-meabi");
  3187. CmdArgs.push_back(A->getValue());
  3188. }
  3189. CmdArgs.push_back("-mthread-model");
  3190. if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
  3191. CmdArgs.push_back(A->getValue());
  3192. else
  3193. CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
  3194. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3195. if (!Args.hasFlag(options::OPT_fmerge_all_constants,
  3196. options::OPT_fno_merge_all_constants))
  3197. CmdArgs.push_back("-fno-merge-all-constants");
  3198. // LLVM Code Generator Options.
  3199. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3200. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3201. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3202. options::OPT_frewrite_map_file_EQ)) {
  3203. CmdArgs.push_back("-frewrite-map-file");
  3204. CmdArgs.push_back(A->getValue());
  3205. A->claim();
  3206. }
  3207. }
  3208. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3209. StringRef v = A->getValue();
  3210. CmdArgs.push_back("-mllvm");
  3211. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3212. A->claim();
  3213. }
  3214. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3215. CmdArgs.push_back("-mregparm");
  3216. CmdArgs.push_back(A->getValue());
  3217. }
  3218. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3219. options::OPT_freg_struct_return)) {
  3220. if (getToolChain().getArch() != llvm::Triple::x86) {
  3221. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3222. << A->getSpelling() << getToolChain().getTriple().str();
  3223. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3224. CmdArgs.push_back("-fpcc-struct-return");
  3225. } else {
  3226. assert(A->getOption().matches(options::OPT_freg_struct_return));
  3227. CmdArgs.push_back("-freg-struct-return");
  3228. }
  3229. }
  3230. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  3231. CmdArgs.push_back("-mrtd");
  3232. if (shouldUseFramePointer(Args, getToolChain().getTriple()))
  3233. CmdArgs.push_back("-mdisable-fp-elim");
  3234. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  3235. options::OPT_fno_zero_initialized_in_bss))
  3236. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  3237. bool OFastEnabled = isOptimizationLevelFast(Args);
  3238. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  3239. // enabled. This alias option is being used to simplify the hasFlag logic.
  3240. OptSpecifier StrictAliasingAliasOption =
  3241. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  3242. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  3243. // doesn't do any TBAA.
  3244. bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
  3245. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  3246. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  3247. CmdArgs.push_back("-relaxed-aliasing");
  3248. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  3249. options::OPT_fno_struct_path_tbaa))
  3250. CmdArgs.push_back("-no-struct-path-tbaa");
  3251. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  3252. false))
  3253. CmdArgs.push_back("-fstrict-enums");
  3254. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  3255. options::OPT_fno_strict_vtable_pointers,
  3256. false))
  3257. CmdArgs.push_back("-fstrict-vtable-pointers");
  3258. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3259. options::OPT_fno_optimize_sibling_calls))
  3260. CmdArgs.push_back("-mdisable-tail-calls");
  3261. // Handle segmented stacks.
  3262. if (Args.hasArg(options::OPT_fsplit_stack))
  3263. CmdArgs.push_back("-split-stacks");
  3264. // If -Ofast is the optimization level, then -ffast-math should be enabled.
  3265. // This alias option is being used to simplify the getLastArg logic.
  3266. OptSpecifier FastMathAliasOption =
  3267. OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
  3268. // Handle various floating point optimization flags, mapping them to the
  3269. // appropriate LLVM code generation flags. The pattern for all of these is to
  3270. // default off the codegen optimizations, and if any flag enables them and no
  3271. // flag disables them after the flag enabling them, enable the codegen
  3272. // optimization. This is complicated by several "umbrella" flags.
  3273. if (Arg *A = Args.getLastArg(
  3274. options::OPT_ffast_math, FastMathAliasOption,
  3275. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3276. options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
  3277. options::OPT_fno_honor_infinities))
  3278. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3279. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3280. A->getOption().getID() != options::OPT_fhonor_infinities)
  3281. CmdArgs.push_back("-menable-no-infs");
  3282. if (Arg *A = Args.getLastArg(
  3283. options::OPT_ffast_math, FastMathAliasOption,
  3284. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3285. options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
  3286. options::OPT_fno_honor_nans))
  3287. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3288. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3289. A->getOption().getID() != options::OPT_fhonor_nans)
  3290. CmdArgs.push_back("-menable-no-nans");
  3291. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  3292. bool MathErrno = getToolChain().IsMathErrnoDefault();
  3293. if (Arg *A =
  3294. Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3295. options::OPT_fno_fast_math, options::OPT_fmath_errno,
  3296. options::OPT_fno_math_errno)) {
  3297. // Turning on -ffast_math (with either flag) removes the need for MathErrno.
  3298. // However, turning *off* -ffast_math merely restores the toolchain default
  3299. // (which may be false).
  3300. if (A->getOption().getID() == options::OPT_fno_math_errno ||
  3301. A->getOption().getID() == options::OPT_ffast_math ||
  3302. A->getOption().getID() == options::OPT_Ofast)
  3303. MathErrno = false;
  3304. else if (A->getOption().getID() == options::OPT_fmath_errno)
  3305. MathErrno = true;
  3306. }
  3307. if (MathErrno)
  3308. CmdArgs.push_back("-fmath-errno");
  3309. // There are several flags which require disabling very specific
  3310. // optimizations. Any of these being disabled forces us to turn off the
  3311. // entire set of LLVM optimizations, so collect them through all the flag
  3312. // madness.
  3313. bool AssociativeMath = false;
  3314. if (Arg *A = Args.getLastArg(
  3315. options::OPT_ffast_math, FastMathAliasOption,
  3316. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3317. options::OPT_fno_unsafe_math_optimizations,
  3318. options::OPT_fassociative_math, options::OPT_fno_associative_math))
  3319. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3320. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3321. A->getOption().getID() != options::OPT_fno_associative_math)
  3322. AssociativeMath = true;
  3323. bool ReciprocalMath = false;
  3324. if (Arg *A = Args.getLastArg(
  3325. options::OPT_ffast_math, FastMathAliasOption,
  3326. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3327. options::OPT_fno_unsafe_math_optimizations,
  3328. options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
  3329. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3330. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3331. A->getOption().getID() != options::OPT_fno_reciprocal_math)
  3332. ReciprocalMath = true;
  3333. bool SignedZeros = true;
  3334. if (Arg *A = Args.getLastArg(
  3335. options::OPT_ffast_math, FastMathAliasOption,
  3336. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3337. options::OPT_fno_unsafe_math_optimizations,
  3338. options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
  3339. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3340. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3341. A->getOption().getID() != options::OPT_fsigned_zeros)
  3342. SignedZeros = false;
  3343. bool TrappingMath = true;
  3344. if (Arg *A = Args.getLastArg(
  3345. options::OPT_ffast_math, FastMathAliasOption,
  3346. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3347. options::OPT_fno_unsafe_math_optimizations,
  3348. options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
  3349. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3350. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3351. A->getOption().getID() != options::OPT_ftrapping_math)
  3352. TrappingMath = false;
  3353. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  3354. !TrappingMath)
  3355. CmdArgs.push_back("-menable-unsafe-fp-math");
  3356. if (!SignedZeros)
  3357. CmdArgs.push_back("-fno-signed-zeros");
  3358. if (ReciprocalMath)
  3359. CmdArgs.push_back("-freciprocal-math");
  3360. // Validate and pass through -fp-contract option.
  3361. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3362. options::OPT_fno_fast_math,
  3363. options::OPT_ffp_contract)) {
  3364. if (A->getOption().getID() == options::OPT_ffp_contract) {
  3365. StringRef Val = A->getValue();
  3366. if (Val == "fast" || Val == "on" || Val == "off") {
  3367. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
  3368. } else {
  3369. D.Diag(diag::err_drv_unsupported_option_argument)
  3370. << A->getOption().getName() << Val;
  3371. }
  3372. } else if (A->getOption().matches(options::OPT_ffast_math) ||
  3373. (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
  3374. // If fast-math is set then set the fp-contract mode to fast.
  3375. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  3376. }
  3377. }
  3378. ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
  3379. // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
  3380. // and if we find them, tell the frontend to provide the appropriate
  3381. // preprocessor macros. This is distinct from enabling any optimizations as
  3382. // these options induce language changes which must survive serialization
  3383. // and deserialization, etc.
  3384. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3385. options::OPT_fno_fast_math))
  3386. if (!A->getOption().matches(options::OPT_fno_fast_math))
  3387. CmdArgs.push_back("-ffast-math");
  3388. if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
  3389. options::OPT_fno_fast_math))
  3390. if (A->getOption().matches(options::OPT_ffinite_math_only))
  3391. CmdArgs.push_back("-ffinite-math-only");
  3392. // Decide whether to use verbose asm. Verbose assembly is the default on
  3393. // toolchains which have the integrated assembler on by default.
  3394. bool IsIntegratedAssemblerDefault =
  3395. getToolChain().IsIntegratedAssemblerDefault();
  3396. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  3397. IsIntegratedAssemblerDefault) ||
  3398. Args.hasArg(options::OPT_dA))
  3399. CmdArgs.push_back("-masm-verbose");
  3400. if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
  3401. IsIntegratedAssemblerDefault))
  3402. CmdArgs.push_back("-no-integrated-as");
  3403. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  3404. CmdArgs.push_back("-mdebug-pass");
  3405. CmdArgs.push_back("Structure");
  3406. }
  3407. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  3408. CmdArgs.push_back("-mdebug-pass");
  3409. CmdArgs.push_back("Arguments");
  3410. }
  3411. // Enable -mconstructor-aliases except on darwin, where we have to
  3412. // work around a linker bug; see <rdar://problem/7651567>.
  3413. if (!getToolChain().getTriple().isOSDarwin())
  3414. CmdArgs.push_back("-mconstructor-aliases");
  3415. // Darwin's kernel doesn't support guard variables; just die if we
  3416. // try to use them.
  3417. if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
  3418. CmdArgs.push_back("-fforbid-guard-variables");
  3419. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  3420. false)) {
  3421. CmdArgs.push_back("-mms-bitfields");
  3422. }
  3423. // This is a coarse approximation of what llvm-gcc actually does, both
  3424. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  3425. // complicated ways.
  3426. bool AsynchronousUnwindTables =
  3427. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  3428. options::OPT_fno_asynchronous_unwind_tables,
  3429. (getToolChain().IsUnwindTablesDefault() ||
  3430. getToolChain().getSanitizerArgs().needsUnwindTables()) &&
  3431. !KernelOrKext);
  3432. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  3433. AsynchronousUnwindTables))
  3434. CmdArgs.push_back("-munwind-tables");
  3435. getToolChain().addClangTargetOptions(Args, CmdArgs);
  3436. if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  3437. CmdArgs.push_back("-mlimit-float-precision");
  3438. CmdArgs.push_back(A->getValue());
  3439. }
  3440. // FIXME: Handle -mtune=.
  3441. (void)Args.hasArg(options::OPT_mtune_EQ);
  3442. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  3443. CmdArgs.push_back("-mcode-model");
  3444. CmdArgs.push_back(A->getValue());
  3445. }
  3446. // Add the target cpu
  3447. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  3448. if (!CPU.empty()) {
  3449. CmdArgs.push_back("-target-cpu");
  3450. CmdArgs.push_back(Args.MakeArgString(CPU));
  3451. }
  3452. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  3453. CmdArgs.push_back("-mfpmath");
  3454. CmdArgs.push_back(A->getValue());
  3455. }
  3456. // Add the target features
  3457. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
  3458. // Add target specific flags.
  3459. switch (getToolChain().getArch()) {
  3460. default:
  3461. break;
  3462. case llvm::Triple::arm:
  3463. case llvm::Triple::armeb:
  3464. case llvm::Triple::thumb:
  3465. case llvm::Triple::thumbeb:
  3466. // Use the effective triple, which takes into account the deployment target.
  3467. AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
  3468. break;
  3469. case llvm::Triple::aarch64:
  3470. case llvm::Triple::aarch64_be:
  3471. AddAArch64TargetArgs(Args, CmdArgs);
  3472. break;
  3473. case llvm::Triple::mips:
  3474. case llvm::Triple::mipsel:
  3475. case llvm::Triple::mips64:
  3476. case llvm::Triple::mips64el:
  3477. AddMIPSTargetArgs(Args, CmdArgs);
  3478. break;
  3479. case llvm::Triple::ppc:
  3480. case llvm::Triple::ppc64:
  3481. case llvm::Triple::ppc64le:
  3482. AddPPCTargetArgs(Args, CmdArgs);
  3483. break;
  3484. case llvm::Triple::sparc:
  3485. case llvm::Triple::sparcel:
  3486. case llvm::Triple::sparcv9:
  3487. AddSparcTargetArgs(Args, CmdArgs);
  3488. break;
  3489. case llvm::Triple::x86:
  3490. case llvm::Triple::x86_64:
  3491. AddX86TargetArgs(Args, CmdArgs);
  3492. break;
  3493. case llvm::Triple::hexagon:
  3494. AddHexagonTargetArgs(Args, CmdArgs);
  3495. break;
  3496. }
  3497. // The 'g' groups options involve a somewhat intricate sequence of decisions
  3498. // about what to pass from the driver to the frontend, but by the time they
  3499. // reach cc1 they've been factored into two well-defined orthogonal choices:
  3500. // * what level of debug info to generate
  3501. // * what dwarf version to write
  3502. // This avoids having to monkey around further in cc1 other than to disable
  3503. // codeview if not running in a Windows environment. Perhaps even that
  3504. // decision should be made in the driver as well though.
  3505. enum CodeGenOptions::DebugInfoKind DebugInfoKind =
  3506. CodeGenOptions::NoDebugInfo;
  3507. // These two are potentially updated by AddClangCLArgs.
  3508. unsigned DwarfVersion = 0;
  3509. bool EmitCodeView = false;
  3510. // Add clang-cl arguments.
  3511. if (getToolChain().getDriver().IsCLMode())
  3512. AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
  3513. // Pass the linker version in use.
  3514. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  3515. CmdArgs.push_back("-target-linker-version");
  3516. CmdArgs.push_back(A->getValue());
  3517. }
  3518. if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
  3519. CmdArgs.push_back("-momit-leaf-frame-pointer");
  3520. // Explicitly error on some things we know we don't support and can't just
  3521. // ignore.
  3522. types::ID InputType = Input.getType();
  3523. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  3524. Arg *Unsupported;
  3525. if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
  3526. getToolChain().getArch() == llvm::Triple::x86) {
  3527. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  3528. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  3529. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  3530. << Unsupported->getOption().getName();
  3531. }
  3532. }
  3533. Args.AddAllArgs(CmdArgs, options::OPT_v);
  3534. Args.AddLastArg(CmdArgs, options::OPT_H);
  3535. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  3536. CmdArgs.push_back("-header-include-file");
  3537. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  3538. : "-");
  3539. }
  3540. Args.AddLastArg(CmdArgs, options::OPT_P);
  3541. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  3542. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  3543. CmdArgs.push_back("-diagnostic-log-file");
  3544. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  3545. : "-");
  3546. }
  3547. Args.ClaimAllArgs(options::OPT_g_Group);
  3548. Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
  3549. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  3550. // If you say "-gline-tables-only -gsplit-dwarf", split-dwarf wins,
  3551. // which mandates turning on "-g". But -split-dwarf is not a g_group option,
  3552. // hence it takes a nontrivial test to decide about line-tables-only.
  3553. if (A->getOption().matches(options::OPT_gline_tables_only) &&
  3554. (!SplitDwarfArg || A->getIndex() > SplitDwarfArg->getIndex())) {
  3555. DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
  3556. SplitDwarfArg = nullptr;
  3557. } else if (!A->getOption().matches(options::OPT_g0)) {
  3558. // Some 'g' group option other than one expressly disabling debug info
  3559. // must have been the final (winning) one. They're all equivalent.
  3560. DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
  3561. }
  3562. }
  3563. // If a -gdwarf argument appeared, use it, unless DebugInfoKind is None
  3564. // (because that would mean that "-g0" was the rightmost 'g' group option).
  3565. // FIXME: specifying "-gdwarf-<N>" "-g1" in that order works,
  3566. // but "-g1" "-gdwarf-<N>" does not. A deceptively simple (but wrong) "fix"
  3567. // exists of removing the gdwarf options from the g_group.
  3568. if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  3569. options::OPT_gdwarf_4))
  3570. DwarfVersion = DwarfVersionNum(A->getSpelling());
  3571. // Forward -gcodeview.
  3572. // 'EmitCodeView might have been set by CL-compatibility argument parsing.
  3573. if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
  3574. // DwarfVersion remains at 0 if no explicit choice was made.
  3575. CmdArgs.push_back("-gcodeview");
  3576. } else if (DwarfVersion == 0 &&
  3577. DebugInfoKind != CodeGenOptions::NoDebugInfo) {
  3578. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  3579. }
  3580. // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
  3581. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  3582. // PS4 defaults to no column info
  3583. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  3584. /*Default=*/ !IsPS4CPU))
  3585. CmdArgs.push_back("-dwarf-column-info");
  3586. // FIXME: Move backend command line options to the module.
  3587. if (Args.hasArg(options::OPT_gmodules)) {
  3588. DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
  3589. CmdArgs.push_back("-dwarf-ext-refs");
  3590. CmdArgs.push_back("-fmodule-format=obj");
  3591. }
  3592. // -gsplit-dwarf should turn on -g and enable the backend dwarf
  3593. // splitting and extraction.
  3594. // FIXME: Currently only works on Linux.
  3595. if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
  3596. DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
  3597. CmdArgs.push_back("-backend-option");
  3598. CmdArgs.push_back("-split-dwarf=Enable");
  3599. }
  3600. // After we've dealt with all combinations of things that could
  3601. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  3602. // figure out if we need to "upgrade" it to standalone debug info.
  3603. // We parse these two '-f' options whether or not they will be used,
  3604. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  3605. bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
  3606. options::OPT_fno_standalone_debug,
  3607. getToolChain().GetDefaultStandaloneDebug());
  3608. if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
  3609. DebugInfoKind = CodeGenOptions::FullDebugInfo;
  3610. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion);
  3611. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  3612. if (Args.hasArg(options::OPT_ggnu_pubnames)) {
  3613. CmdArgs.push_back("-backend-option");
  3614. CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
  3615. }
  3616. // -gdwarf-aranges turns on the emission of the aranges section in the
  3617. // backend.
  3618. // Always enabled on the PS4.
  3619. if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
  3620. CmdArgs.push_back("-backend-option");
  3621. CmdArgs.push_back("-generate-arange-section");
  3622. }
  3623. if (Args.hasFlag(options::OPT_fdebug_types_section,
  3624. options::OPT_fno_debug_types_section, false)) {
  3625. CmdArgs.push_back("-backend-option");
  3626. CmdArgs.push_back("-generate-type-units");
  3627. }
  3628. // CloudABI uses -ffunction-sections and -fdata-sections by default.
  3629. bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
  3630. if (Args.hasFlag(options::OPT_ffunction_sections,
  3631. options::OPT_fno_function_sections, UseSeparateSections)) {
  3632. CmdArgs.push_back("-ffunction-sections");
  3633. }
  3634. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  3635. UseSeparateSections)) {
  3636. CmdArgs.push_back("-fdata-sections");
  3637. }
  3638. if (!Args.hasFlag(options::OPT_funique_section_names,
  3639. options::OPT_fno_unique_section_names, true))
  3640. CmdArgs.push_back("-fno-unique-section-names");
  3641. Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
  3642. addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
  3643. // Pass options for controlling the default header search paths.
  3644. if (Args.hasArg(options::OPT_nostdinc)) {
  3645. CmdArgs.push_back("-nostdsysteminc");
  3646. CmdArgs.push_back("-nobuiltininc");
  3647. } else {
  3648. if (Args.hasArg(options::OPT_nostdlibinc))
  3649. CmdArgs.push_back("-nostdsysteminc");
  3650. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  3651. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  3652. }
  3653. // Pass the path to compiler resource files.
  3654. CmdArgs.push_back("-resource-dir");
  3655. CmdArgs.push_back(D.ResourceDir.c_str());
  3656. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  3657. bool ARCMTEnabled = false;
  3658. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  3659. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  3660. options::OPT_ccc_arcmt_modify,
  3661. options::OPT_ccc_arcmt_migrate)) {
  3662. ARCMTEnabled = true;
  3663. switch (A->getOption().getID()) {
  3664. default:
  3665. llvm_unreachable("missed a case");
  3666. case options::OPT_ccc_arcmt_check:
  3667. CmdArgs.push_back("-arcmt-check");
  3668. break;
  3669. case options::OPT_ccc_arcmt_modify:
  3670. CmdArgs.push_back("-arcmt-modify");
  3671. break;
  3672. case options::OPT_ccc_arcmt_migrate:
  3673. CmdArgs.push_back("-arcmt-migrate");
  3674. CmdArgs.push_back("-mt-migrate-directory");
  3675. CmdArgs.push_back(A->getValue());
  3676. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  3677. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  3678. break;
  3679. }
  3680. }
  3681. } else {
  3682. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  3683. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  3684. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  3685. }
  3686. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  3687. if (ARCMTEnabled) {
  3688. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  3689. << "-ccc-arcmt-migrate";
  3690. }
  3691. CmdArgs.push_back("-mt-migrate-directory");
  3692. CmdArgs.push_back(A->getValue());
  3693. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  3694. options::OPT_objcmt_migrate_subscripting,
  3695. options::OPT_objcmt_migrate_property)) {
  3696. // None specified, means enable them all.
  3697. CmdArgs.push_back("-objcmt-migrate-literals");
  3698. CmdArgs.push_back("-objcmt-migrate-subscripting");
  3699. CmdArgs.push_back("-objcmt-migrate-property");
  3700. } else {
  3701. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3702. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3703. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3704. }
  3705. } else {
  3706. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3707. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3708. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3709. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  3710. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  3711. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  3712. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  3713. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  3714. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  3715. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  3716. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  3717. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  3718. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  3719. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  3720. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  3721. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  3722. }
  3723. // Add preprocessing options like -I, -D, etc. if we are using the
  3724. // preprocessor.
  3725. //
  3726. // FIXME: Support -fpreprocessed
  3727. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  3728. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
  3729. AuxToolChain);
  3730. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  3731. // that "The compiler can only warn and ignore the option if not recognized".
  3732. // When building with ccache, it will pass -D options to clang even on
  3733. // preprocessed inputs and configure concludes that -fPIC is not supported.
  3734. Args.ClaimAllArgs(options::OPT_D);
  3735. // Manually translate -O4 to -O3; let clang reject others.
  3736. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  3737. if (A->getOption().matches(options::OPT_O4)) {
  3738. CmdArgs.push_back("-O3");
  3739. D.Diag(diag::warn_O4_is_O3);
  3740. } else {
  3741. A->render(Args, CmdArgs);
  3742. }
  3743. }
  3744. // Warn about ignored options to clang.
  3745. for (const Arg *A :
  3746. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  3747. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  3748. A->claim();
  3749. }
  3750. claimNoWarnArgs(Args);
  3751. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  3752. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  3753. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  3754. CmdArgs.push_back("-pedantic");
  3755. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  3756. Args.AddLastArg(CmdArgs, options::OPT_w);
  3757. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  3758. // (-ansi is equivalent to -std=c89 or -std=c++98).
  3759. //
  3760. // If a std is supplied, only add -trigraphs if it follows the
  3761. // option.
  3762. bool ImplyVCPPCXXVer = false;
  3763. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
  3764. if (Std->getOption().matches(options::OPT_ansi))
  3765. if (types::isCXX(InputType))
  3766. CmdArgs.push_back("-std=c++98");
  3767. else
  3768. CmdArgs.push_back("-std=c89");
  3769. else
  3770. Std->render(Args, CmdArgs);
  3771. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  3772. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  3773. options::OPT_ftrigraphs,
  3774. options::OPT_fno_trigraphs))
  3775. if (A != Std)
  3776. A->render(Args, CmdArgs);
  3777. } else {
  3778. // Honor -std-default.
  3779. //
  3780. // FIXME: Clang doesn't correctly handle -std= when the input language
  3781. // doesn't match. For the time being just ignore this for C++ inputs;
  3782. // eventually we want to do all the standard defaulting here instead of
  3783. // splitting it between the driver and clang -cc1.
  3784. if (!types::isCXX(InputType))
  3785. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  3786. /*Joined=*/true);
  3787. else if (IsWindowsMSVC)
  3788. ImplyVCPPCXXVer = true;
  3789. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  3790. options::OPT_fno_trigraphs);
  3791. }
  3792. // GCC's behavior for -Wwrite-strings is a bit strange:
  3793. // * In C, this "warning flag" changes the types of string literals from
  3794. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  3795. // for the discarded qualifier.
  3796. // * In C++, this is just a normal warning flag.
  3797. //
  3798. // Implementing this warning correctly in C is hard, so we follow GCC's
  3799. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  3800. // a non-const char* in C, rather than using this crude hack.
  3801. if (!types::isCXX(InputType)) {
  3802. // FIXME: This should behave just like a warning flag, and thus should also
  3803. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  3804. Arg *WriteStrings =
  3805. Args.getLastArg(options::OPT_Wwrite_strings,
  3806. options::OPT_Wno_write_strings, options::OPT_w);
  3807. if (WriteStrings &&
  3808. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  3809. CmdArgs.push_back("-fconst-strings");
  3810. }
  3811. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  3812. // during C++ compilation, which it is by default. GCC keeps this define even
  3813. // in the presence of '-w', match this behavior bug-for-bug.
  3814. if (types::isCXX(InputType) &&
  3815. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  3816. true)) {
  3817. CmdArgs.push_back("-fdeprecated-macro");
  3818. }
  3819. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  3820. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  3821. if (Asm->getOption().matches(options::OPT_fasm))
  3822. CmdArgs.push_back("-fgnu-keywords");
  3823. else
  3824. CmdArgs.push_back("-fno-gnu-keywords");
  3825. }
  3826. if (ShouldDisableDwarfDirectory(Args, getToolChain()))
  3827. CmdArgs.push_back("-fno-dwarf-directory-asm");
  3828. if (ShouldDisableAutolink(Args, getToolChain()))
  3829. CmdArgs.push_back("-fno-autolink");
  3830. // Add in -fdebug-compilation-dir if necessary.
  3831. addDebugCompDirArg(Args, CmdArgs);
  3832. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  3833. StringRef Map = A->getValue();
  3834. if (Map.find('=') == StringRef::npos)
  3835. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  3836. else
  3837. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  3838. A->claim();
  3839. }
  3840. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  3841. options::OPT_ftemplate_depth_EQ)) {
  3842. CmdArgs.push_back("-ftemplate-depth");
  3843. CmdArgs.push_back(A->getValue());
  3844. }
  3845. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  3846. CmdArgs.push_back("-foperator-arrow-depth");
  3847. CmdArgs.push_back(A->getValue());
  3848. }
  3849. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  3850. CmdArgs.push_back("-fconstexpr-depth");
  3851. CmdArgs.push_back(A->getValue());
  3852. }
  3853. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  3854. CmdArgs.push_back("-fconstexpr-steps");
  3855. CmdArgs.push_back(A->getValue());
  3856. }
  3857. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  3858. CmdArgs.push_back("-fbracket-depth");
  3859. CmdArgs.push_back(A->getValue());
  3860. }
  3861. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  3862. options::OPT_Wlarge_by_value_copy_def)) {
  3863. if (A->getNumValues()) {
  3864. StringRef bytes = A->getValue();
  3865. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  3866. } else
  3867. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  3868. }
  3869. if (Args.hasArg(options::OPT_relocatable_pch))
  3870. CmdArgs.push_back("-relocatable-pch");
  3871. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  3872. CmdArgs.push_back("-fconstant-string-class");
  3873. CmdArgs.push_back(A->getValue());
  3874. }
  3875. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  3876. CmdArgs.push_back("-ftabstop");
  3877. CmdArgs.push_back(A->getValue());
  3878. }
  3879. CmdArgs.push_back("-ferror-limit");
  3880. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  3881. CmdArgs.push_back(A->getValue());
  3882. else
  3883. CmdArgs.push_back("19");
  3884. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  3885. CmdArgs.push_back("-fmacro-backtrace-limit");
  3886. CmdArgs.push_back(A->getValue());
  3887. }
  3888. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  3889. CmdArgs.push_back("-ftemplate-backtrace-limit");
  3890. CmdArgs.push_back(A->getValue());
  3891. }
  3892. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  3893. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  3894. CmdArgs.push_back(A->getValue());
  3895. }
  3896. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  3897. CmdArgs.push_back("-fspell-checking-limit");
  3898. CmdArgs.push_back(A->getValue());
  3899. }
  3900. // Pass -fmessage-length=.
  3901. CmdArgs.push_back("-fmessage-length");
  3902. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  3903. CmdArgs.push_back(A->getValue());
  3904. } else {
  3905. // If -fmessage-length=N was not specified, determine whether this is a
  3906. // terminal and, if so, implicitly define -fmessage-length appropriately.
  3907. unsigned N = llvm::sys::Process::StandardErrColumns();
  3908. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  3909. }
  3910. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  3911. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  3912. options::OPT_fvisibility_ms_compat)) {
  3913. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  3914. CmdArgs.push_back("-fvisibility");
  3915. CmdArgs.push_back(A->getValue());
  3916. } else {
  3917. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  3918. CmdArgs.push_back("-fvisibility");
  3919. CmdArgs.push_back("hidden");
  3920. CmdArgs.push_back("-ftype-visibility");
  3921. CmdArgs.push_back("default");
  3922. }
  3923. }
  3924. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  3925. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  3926. // -fhosted is default.
  3927. if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  3928. KernelOrKext)
  3929. CmdArgs.push_back("-ffreestanding");
  3930. // Forward -f (flag) options which we can pass directly.
  3931. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  3932. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  3933. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  3934. // Emulated TLS is enabled by default on Android, and can be enabled manually
  3935. // with -femulated-tls.
  3936. bool EmulatedTLSDefault = Triple.isAndroid();
  3937. if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
  3938. EmulatedTLSDefault))
  3939. CmdArgs.push_back("-femulated-tls");
  3940. // AltiVec-like language extensions aren't relevant for assembling.
  3941. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
  3942. Args.AddLastArg(CmdArgs, options::OPT_faltivec);
  3943. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  3944. }
  3945. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  3946. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  3947. // Forward flags for OpenMP
  3948. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  3949. options::OPT_fno_openmp, false))
  3950. switch (getOpenMPRuntime(getToolChain(), Args)) {
  3951. case OMPRT_OMP:
  3952. case OMPRT_IOMP5:
  3953. // Clang can generate useful OpenMP code for these two runtime libraries.
  3954. CmdArgs.push_back("-fopenmp");
  3955. // If no option regarding the use of TLS in OpenMP codegeneration is
  3956. // given, decide a default based on the target. Otherwise rely on the
  3957. // options and pass the right information to the frontend.
  3958. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  3959. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  3960. CmdArgs.push_back("-fnoopenmp-use-tls");
  3961. break;
  3962. default:
  3963. // By default, if Clang doesn't know how to generate useful OpenMP code
  3964. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  3965. // down to the actual compilation.
  3966. // FIXME: It would be better to have a mode which *only* omits IR
  3967. // generation based on the OpenMP support so that we get consistent
  3968. // semantic analysis, etc.
  3969. break;
  3970. }
  3971. const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
  3972. Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
  3973. // Report an error for -faltivec on anything other than PowerPC.
  3974. if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
  3975. const llvm::Triple::ArchType Arch = getToolChain().getArch();
  3976. if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  3977. Arch == llvm::Triple::ppc64le))
  3978. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3979. << "ppc/ppc64/ppc64le";
  3980. }
  3981. // -fzvector is incompatible with -faltivec.
  3982. if (Arg *A = Args.getLastArg(options::OPT_fzvector))
  3983. if (Args.hasArg(options::OPT_faltivec))
  3984. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  3985. << "-faltivec";
  3986. if (getToolChain().SupportsProfiling())
  3987. Args.AddLastArg(CmdArgs, options::OPT_pg);
  3988. // -flax-vector-conversions is default.
  3989. if (!Args.hasFlag(options::OPT_flax_vector_conversions,
  3990. options::OPT_fno_lax_vector_conversions))
  3991. CmdArgs.push_back("-fno-lax-vector-conversions");
  3992. if (Args.getLastArg(options::OPT_fapple_kext) ||
  3993. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  3994. CmdArgs.push_back("-fapple-kext");
  3995. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  3996. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  3997. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  3998. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  3999. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  4000. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  4001. CmdArgs.push_back("-ftrapv-handler");
  4002. CmdArgs.push_back(A->getValue());
  4003. }
  4004. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  4005. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  4006. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  4007. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  4008. if (A->getOption().matches(options::OPT_fwrapv))
  4009. CmdArgs.push_back("-fwrapv");
  4010. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  4011. options::OPT_fno_strict_overflow)) {
  4012. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  4013. CmdArgs.push_back("-fwrapv");
  4014. }
  4015. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  4016. options::OPT_fno_reroll_loops))
  4017. if (A->getOption().matches(options::OPT_freroll_loops))
  4018. CmdArgs.push_back("-freroll-loops");
  4019. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  4020. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  4021. options::OPT_fno_unroll_loops);
  4022. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  4023. // -stack-protector=0 is default.
  4024. unsigned StackProtectorLevel = 0;
  4025. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  4026. Args.ClaimAllArgs(options::OPT_fno_stack_protector);
  4027. Args.ClaimAllArgs(options::OPT_fstack_protector_all);
  4028. Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
  4029. Args.ClaimAllArgs(options::OPT_fstack_protector);
  4030. } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  4031. options::OPT_fstack_protector_all,
  4032. options::OPT_fstack_protector_strong,
  4033. options::OPT_fstack_protector)) {
  4034. if (A->getOption().matches(options::OPT_fstack_protector)) {
  4035. StackProtectorLevel = std::max<unsigned>(
  4036. LangOptions::SSPOn,
  4037. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
  4038. } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  4039. StackProtectorLevel = LangOptions::SSPStrong;
  4040. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  4041. StackProtectorLevel = LangOptions::SSPReq;
  4042. } else {
  4043. StackProtectorLevel =
  4044. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
  4045. }
  4046. if (StackProtectorLevel) {
  4047. CmdArgs.push_back("-stack-protector");
  4048. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  4049. }
  4050. // --param ssp-buffer-size=
  4051. for (const Arg *A : Args.filtered(options::OPT__param)) {
  4052. StringRef Str(A->getValue());
  4053. if (Str.startswith("ssp-buffer-size=")) {
  4054. if (StackProtectorLevel) {
  4055. CmdArgs.push_back("-stack-protector-buffer-size");
  4056. // FIXME: Verify the argument is a valid integer.
  4057. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  4058. }
  4059. A->claim();
  4060. }
  4061. }
  4062. // Translate -mstackrealign
  4063. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  4064. false))
  4065. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  4066. if (Args.hasArg(options::OPT_mstack_alignment)) {
  4067. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  4068. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  4069. }
  4070. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  4071. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  4072. if (!Size.empty())
  4073. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  4074. else
  4075. CmdArgs.push_back("-mstack-probe-size=0");
  4076. }
  4077. switch (getToolChain().getArch()) {
  4078. case llvm::Triple::aarch64:
  4079. case llvm::Triple::aarch64_be:
  4080. case llvm::Triple::arm:
  4081. case llvm::Triple::armeb:
  4082. case llvm::Triple::thumb:
  4083. case llvm::Triple::thumbeb:
  4084. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  4085. break;
  4086. default:
  4087. break;
  4088. }
  4089. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  4090. options::OPT_mno_restrict_it)) {
  4091. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  4092. CmdArgs.push_back("-backend-option");
  4093. CmdArgs.push_back("-arm-restrict-it");
  4094. } else {
  4095. CmdArgs.push_back("-backend-option");
  4096. CmdArgs.push_back("-arm-no-restrict-it");
  4097. }
  4098. } else if (Triple.isOSWindows() &&
  4099. (Triple.getArch() == llvm::Triple::arm ||
  4100. Triple.getArch() == llvm::Triple::thumb)) {
  4101. // Windows on ARM expects restricted IT blocks
  4102. CmdArgs.push_back("-backend-option");
  4103. CmdArgs.push_back("-arm-restrict-it");
  4104. }
  4105. // Forward -f options with positive and negative forms; we translate
  4106. // these by hand.
  4107. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  4108. StringRef fname = A->getValue();
  4109. if (!llvm::sys::fs::exists(fname))
  4110. D.Diag(diag::err_drv_no_such_file) << fname;
  4111. else
  4112. A->render(Args, CmdArgs);
  4113. }
  4114. // -fbuiltin is default unless -mkernel is used
  4115. if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  4116. !Args.hasArg(options::OPT_mkernel)))
  4117. CmdArgs.push_back("-fno-builtin");
  4118. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4119. options::OPT_fno_assume_sane_operator_new))
  4120. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4121. // -fblocks=0 is default.
  4122. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  4123. getToolChain().IsBlocksDefault()) ||
  4124. (Args.hasArg(options::OPT_fgnu_runtime) &&
  4125. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  4126. !Args.hasArg(options::OPT_fno_blocks))) {
  4127. CmdArgs.push_back("-fblocks");
  4128. if (!Args.hasArg(options::OPT_fgnu_runtime) &&
  4129. !getToolChain().hasBlocksRuntime())
  4130. CmdArgs.push_back("-fblocks-runtime-optional");
  4131. }
  4132. // -fmodules enables the use of precompiled modules (off by default).
  4133. // Users can pass -fno-cxx-modules to turn off modules support for
  4134. // C++/Objective-C++ programs.
  4135. bool HaveModules = false;
  4136. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  4137. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  4138. options::OPT_fno_cxx_modules, true);
  4139. if (AllowedInCXX || !types::isCXX(InputType)) {
  4140. CmdArgs.push_back("-fmodules");
  4141. HaveModules = true;
  4142. }
  4143. }
  4144. // -fmodule-maps enables implicit reading of module map files. By default,
  4145. // this is enabled if we are using precompiled modules.
  4146. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  4147. options::OPT_fno_implicit_module_maps, HaveModules)) {
  4148. CmdArgs.push_back("-fimplicit-module-maps");
  4149. }
  4150. // -fmodules-decluse checks that modules used are declared so (off by
  4151. // default).
  4152. if (Args.hasFlag(options::OPT_fmodules_decluse,
  4153. options::OPT_fno_modules_decluse, false)) {
  4154. CmdArgs.push_back("-fmodules-decluse");
  4155. }
  4156. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  4157. // all #included headers are part of modules.
  4158. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  4159. options::OPT_fno_modules_strict_decluse, false)) {
  4160. CmdArgs.push_back("-fmodules-strict-decluse");
  4161. }
  4162. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  4163. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  4164. options::OPT_fno_implicit_modules)) {
  4165. CmdArgs.push_back("-fno-implicit-modules");
  4166. }
  4167. // -fmodule-name specifies the module that is currently being built (or
  4168. // used for header checking by -fmodule-maps).
  4169. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
  4170. // -fmodule-map-file can be used to specify files containing module
  4171. // definitions.
  4172. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  4173. // -fmodule-file can be used to specify files containing precompiled modules.
  4174. if (HaveModules)
  4175. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  4176. else
  4177. Args.ClaimAllArgs(options::OPT_fmodule_file);
  4178. // -fmodule-cache-path specifies where our implicitly-built module files
  4179. // should be written.
  4180. SmallString<128> Path;
  4181. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  4182. Path = A->getValue();
  4183. if (HaveModules) {
  4184. if (C.isForDiagnostics()) {
  4185. // When generating crash reports, we want to emit the modules along with
  4186. // the reproduction sources, so we ignore any provided module path.
  4187. Path = Output.getFilename();
  4188. llvm::sys::path::replace_extension(Path, ".cache");
  4189. llvm::sys::path::append(Path, "modules");
  4190. } else if (Path.empty()) {
  4191. // No module path was provided: use the default.
  4192. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
  4193. llvm::sys::path::append(Path, "org.llvm.clang.");
  4194. appendUserToPath(Path);
  4195. llvm::sys::path::append(Path, "ModuleCache");
  4196. }
  4197. const char Arg[] = "-fmodules-cache-path=";
  4198. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  4199. CmdArgs.push_back(Args.MakeArgString(Path));
  4200. }
  4201. // When building modules and generating crashdumps, we need to dump a module
  4202. // dependency VFS alongside the output.
  4203. if (HaveModules && C.isForDiagnostics()) {
  4204. SmallString<128> VFSDir(Output.getFilename());
  4205. llvm::sys::path::replace_extension(VFSDir, ".cache");
  4206. // Add the cache directory as a temp so the crash diagnostics pick it up.
  4207. C.addTempFile(Args.MakeArgString(VFSDir));
  4208. llvm::sys::path::append(VFSDir, "vfs");
  4209. CmdArgs.push_back("-module-dependency-dir");
  4210. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  4211. }
  4212. if (HaveModules)
  4213. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  4214. // Pass through all -fmodules-ignore-macro arguments.
  4215. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  4216. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  4217. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  4218. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  4219. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  4220. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  4221. D.Diag(diag::err_drv_argument_not_allowed_with)
  4222. << A->getAsString(Args) << "-fbuild-session-timestamp";
  4223. llvm::sys::fs::file_status Status;
  4224. if (llvm::sys::fs::status(A->getValue(), Status))
  4225. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  4226. CmdArgs.push_back(Args.MakeArgString(
  4227. "-fbuild-session-timestamp=" +
  4228. Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
  4229. }
  4230. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  4231. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  4232. options::OPT_fbuild_session_file))
  4233. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  4234. Args.AddLastArg(CmdArgs,
  4235. options::OPT_fmodules_validate_once_per_build_session);
  4236. }
  4237. Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
  4238. // -faccess-control is default.
  4239. if (Args.hasFlag(options::OPT_fno_access_control,
  4240. options::OPT_faccess_control, false))
  4241. CmdArgs.push_back("-fno-access-control");
  4242. // -felide-constructors is the default.
  4243. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  4244. options::OPT_felide_constructors, false))
  4245. CmdArgs.push_back("-fno-elide-constructors");
  4246. ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
  4247. if (KernelOrKext || (types::isCXX(InputType) &&
  4248. (RTTIMode == ToolChain::RM_DisabledExplicitly ||
  4249. RTTIMode == ToolChain::RM_DisabledImplicitly)))
  4250. CmdArgs.push_back("-fno-rtti");
  4251. // -fshort-enums=0 is default for all architectures except Hexagon.
  4252. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  4253. getToolChain().getArch() == llvm::Triple::hexagon))
  4254. CmdArgs.push_back("-fshort-enums");
  4255. // -fsigned-char is default.
  4256. if (Arg *A = Args.getLastArg(
  4257. options::OPT_fsigned_char, options::OPT_fno_signed_char,
  4258. options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
  4259. if (A->getOption().matches(options::OPT_funsigned_char) ||
  4260. A->getOption().matches(options::OPT_fno_signed_char)) {
  4261. CmdArgs.push_back("-fno-signed-char");
  4262. }
  4263. } else if (!isSignedCharDefault(getToolChain().getTriple())) {
  4264. CmdArgs.push_back("-fno-signed-char");
  4265. }
  4266. // -fuse-cxa-atexit is default.
  4267. if (!Args.hasFlag(
  4268. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  4269. !IsWindowsCygnus && !IsWindowsGNU &&
  4270. getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
  4271. getToolChain().getArch() != llvm::Triple::hexagon &&
  4272. getToolChain().getArch() != llvm::Triple::xcore &&
  4273. ((getToolChain().getTriple().getVendor() !=
  4274. llvm::Triple::MipsTechnologies) ||
  4275. getToolChain().getTriple().hasEnvironment())) ||
  4276. KernelOrKext)
  4277. CmdArgs.push_back("-fno-use-cxa-atexit");
  4278. // -fms-extensions=0 is default.
  4279. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  4280. IsWindowsMSVC))
  4281. CmdArgs.push_back("-fms-extensions");
  4282. // -fno-use-line-directives is default.
  4283. if (Args.hasFlag(options::OPT_fuse_line_directives,
  4284. options::OPT_fno_use_line_directives, false))
  4285. CmdArgs.push_back("-fuse-line-directives");
  4286. // -fms-compatibility=0 is default.
  4287. if (Args.hasFlag(options::OPT_fms_compatibility,
  4288. options::OPT_fno_ms_compatibility,
  4289. (IsWindowsMSVC &&
  4290. Args.hasFlag(options::OPT_fms_extensions,
  4291. options::OPT_fno_ms_extensions, true))))
  4292. CmdArgs.push_back("-fms-compatibility");
  4293. // -fms-compatibility-version=18.00 is default.
  4294. VersionTuple MSVT = visualstudio::getMSVCVersion(
  4295. &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
  4296. if (!MSVT.empty())
  4297. CmdArgs.push_back(
  4298. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  4299. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  4300. if (ImplyVCPPCXXVer) {
  4301. if (IsMSVC2015Compatible)
  4302. CmdArgs.push_back("-std=c++14");
  4303. else
  4304. CmdArgs.push_back("-std=c++11");
  4305. }
  4306. // -fno-borland-extensions is default.
  4307. if (Args.hasFlag(options::OPT_fborland_extensions,
  4308. options::OPT_fno_borland_extensions, false))
  4309. CmdArgs.push_back("-fborland-extensions");
  4310. // -fno-declspec is default, except for PS4.
  4311. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  4312. getToolChain().getTriple().isPS4()))
  4313. CmdArgs.push_back("-fdeclspec");
  4314. else if (Args.hasArg(options::OPT_fno_declspec))
  4315. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  4316. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  4317. // than 19.
  4318. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  4319. options::OPT_fno_threadsafe_statics,
  4320. !IsWindowsMSVC || IsMSVC2015Compatible))
  4321. CmdArgs.push_back("-fno-threadsafe-statics");
  4322. // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
  4323. // needs it.
  4324. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  4325. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  4326. CmdArgs.push_back("-fdelayed-template-parsing");
  4327. // -fgnu-keywords default varies depending on language; only pass if
  4328. // specified.
  4329. if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
  4330. options::OPT_fno_gnu_keywords))
  4331. A->render(Args, CmdArgs);
  4332. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  4333. false))
  4334. CmdArgs.push_back("-fgnu89-inline");
  4335. if (Args.hasArg(options::OPT_fno_inline))
  4336. CmdArgs.push_back("-fno-inline");
  4337. if (Args.hasArg(options::OPT_fno_inline_functions))
  4338. CmdArgs.push_back("-fno-inline-functions");
  4339. ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  4340. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
  4341. // legacy is the default. Except for deployment taget of 10.5,
  4342. // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
  4343. // gets ignored silently.
  4344. if (objcRuntime.isNonFragile()) {
  4345. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  4346. options::OPT_fno_objc_legacy_dispatch,
  4347. objcRuntime.isLegacyDispatchDefaultForArch(
  4348. getToolChain().getArch()))) {
  4349. if (getToolChain().UseObjCMixedDispatch())
  4350. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  4351. else
  4352. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  4353. }
  4354. }
  4355. // When ObjectiveC legacy runtime is in effect on MacOSX,
  4356. // turn on the option to do Array/Dictionary subscripting
  4357. // by default.
  4358. if (getToolChain().getArch() == llvm::Triple::x86 &&
  4359. getToolChain().getTriple().isMacOSX() &&
  4360. !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
  4361. objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
  4362. objcRuntime.isNeXTFamily())
  4363. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  4364. // -fencode-extended-block-signature=1 is default.
  4365. if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
  4366. CmdArgs.push_back("-fencode-extended-block-signature");
  4367. }
  4368. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  4369. // NOTE: This logic is duplicated in ToolChains.cpp.
  4370. bool ARC = isObjCAutoRefCount(Args);
  4371. if (ARC) {
  4372. getToolChain().CheckObjCARC();
  4373. CmdArgs.push_back("-fobjc-arc");
  4374. // FIXME: It seems like this entire block, and several around it should be
  4375. // wrapped in isObjC, but for now we just use it here as this is where it
  4376. // was being used previously.
  4377. if (types::isCXX(InputType) && types::isObjC(InputType)) {
  4378. if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  4379. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  4380. else
  4381. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  4382. }
  4383. // Allow the user to enable full exceptions code emission.
  4384. // We define off for Objective-CC, on for Objective-C++.
  4385. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  4386. options::OPT_fno_objc_arc_exceptions,
  4387. /*default*/ types::isCXX(InputType)))
  4388. CmdArgs.push_back("-fobjc-arc-exceptions");
  4389. }
  4390. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  4391. // rewriter.
  4392. if (rewriteKind != RK_None)
  4393. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  4394. // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
  4395. // takes precedence.
  4396. const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
  4397. if (!GCArg)
  4398. GCArg = Args.getLastArg(options::OPT_fobjc_gc);
  4399. if (GCArg) {
  4400. if (ARC) {
  4401. D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
  4402. } else if (getToolChain().SupportsObjCGC()) {
  4403. GCArg->render(Args, CmdArgs);
  4404. } else {
  4405. // FIXME: We should move this to a hard error.
  4406. D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
  4407. }
  4408. }
  4409. // Pass down -fobjc-weak or -fno-objc-weak if present.
  4410. if (types::isObjC(InputType)) {
  4411. auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
  4412. options::OPT_fno_objc_weak);
  4413. if (!WeakArg) {
  4414. // nothing to do
  4415. } else if (GCArg) {
  4416. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4417. D.Diag(diag::err_objc_weak_with_gc);
  4418. } else if (!objcRuntime.allowsWeak()) {
  4419. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4420. D.Diag(diag::err_objc_weak_unsupported);
  4421. } else {
  4422. WeakArg->render(Args, CmdArgs);
  4423. }
  4424. }
  4425. if (Args.hasFlag(options::OPT_fapplication_extension,
  4426. options::OPT_fno_application_extension, false))
  4427. CmdArgs.push_back("-fapplication-extension");
  4428. // Handle GCC-style exception args.
  4429. if (!C.getDriver().IsCLMode())
  4430. addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
  4431. CmdArgs);
  4432. if (getToolChain().UseSjLjExceptions(Args))
  4433. CmdArgs.push_back("-fsjlj-exceptions");
  4434. // C++ "sane" operator new.
  4435. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4436. options::OPT_fno_assume_sane_operator_new))
  4437. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4438. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  4439. // most platforms.
  4440. if (Args.hasFlag(options::OPT_fsized_deallocation,
  4441. options::OPT_fno_sized_deallocation, false))
  4442. CmdArgs.push_back("-fsized-deallocation");
  4443. // -fconstant-cfstrings is default, and may be subject to argument translation
  4444. // on Darwin.
  4445. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  4446. options::OPT_fno_constant_cfstrings) ||
  4447. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  4448. options::OPT_mno_constant_cfstrings))
  4449. CmdArgs.push_back("-fno-constant-cfstrings");
  4450. // -fshort-wchar default varies depending on platform; only
  4451. // pass if specified.
  4452. if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  4453. options::OPT_fno_short_wchar))
  4454. A->render(Args, CmdArgs);
  4455. // -fno-pascal-strings is default, only pass non-default.
  4456. if (Args.hasFlag(options::OPT_fpascal_strings,
  4457. options::OPT_fno_pascal_strings, false))
  4458. CmdArgs.push_back("-fpascal-strings");
  4459. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  4460. // -fno-pack-struct doesn't apply to -fpack-struct=.
  4461. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  4462. std::string PackStructStr = "-fpack-struct=";
  4463. PackStructStr += A->getValue();
  4464. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  4465. } else if (Args.hasFlag(options::OPT_fpack_struct,
  4466. options::OPT_fno_pack_struct, false)) {
  4467. CmdArgs.push_back("-fpack-struct=1");
  4468. }
  4469. // Handle -fmax-type-align=N and -fno-type-align
  4470. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  4471. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  4472. if (!SkipMaxTypeAlign) {
  4473. std::string MaxTypeAlignStr = "-fmax-type-align=";
  4474. MaxTypeAlignStr += A->getValue();
  4475. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4476. }
  4477. } else if (getToolChain().getTriple().isOSDarwin()) {
  4478. if (!SkipMaxTypeAlign) {
  4479. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  4480. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4481. }
  4482. }
  4483. // -fcommon is the default unless compiling kernel code or the target says so
  4484. bool NoCommonDefault =
  4485. KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
  4486. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  4487. !NoCommonDefault))
  4488. CmdArgs.push_back("-fno-common");
  4489. // -fsigned-bitfields is default, and clang doesn't yet support
  4490. // -funsigned-bitfields.
  4491. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  4492. options::OPT_funsigned_bitfields))
  4493. D.Diag(diag::warn_drv_clang_unsupported)
  4494. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  4495. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  4496. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  4497. D.Diag(diag::err_drv_clang_unsupported)
  4498. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  4499. // -finput_charset=UTF-8 is default. Reject others
  4500. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  4501. StringRef value = inputCharset->getValue();
  4502. if (value != "UTF-8")
  4503. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  4504. << value;
  4505. }
  4506. // -fexec_charset=UTF-8 is default. Reject others
  4507. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  4508. StringRef value = execCharset->getValue();
  4509. if (value != "UTF-8")
  4510. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  4511. << value;
  4512. }
  4513. // -fcaret-diagnostics is default.
  4514. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  4515. options::OPT_fno_caret_diagnostics, true))
  4516. CmdArgs.push_back("-fno-caret-diagnostics");
  4517. // -fdiagnostics-fixit-info is default, only pass non-default.
  4518. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  4519. options::OPT_fno_diagnostics_fixit_info))
  4520. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  4521. // Enable -fdiagnostics-show-option by default.
  4522. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  4523. options::OPT_fno_diagnostics_show_option))
  4524. CmdArgs.push_back("-fdiagnostics-show-option");
  4525. if (const Arg *A =
  4526. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  4527. CmdArgs.push_back("-fdiagnostics-show-category");
  4528. CmdArgs.push_back(A->getValue());
  4529. }
  4530. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  4531. CmdArgs.push_back("-fdiagnostics-format");
  4532. CmdArgs.push_back(A->getValue());
  4533. }
  4534. if (Arg *A = Args.getLastArg(
  4535. options::OPT_fdiagnostics_show_note_include_stack,
  4536. options::OPT_fno_diagnostics_show_note_include_stack)) {
  4537. if (A->getOption().matches(
  4538. options::OPT_fdiagnostics_show_note_include_stack))
  4539. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  4540. else
  4541. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  4542. }
  4543. // Color diagnostics are the default, unless the terminal doesn't support
  4544. // them.
  4545. // Support both clang's -f[no-]color-diagnostics and gcc's
  4546. // -f[no-]diagnostics-colors[=never|always|auto].
  4547. enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
  4548. for (const auto &Arg : Args) {
  4549. const Option &O = Arg->getOption();
  4550. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  4551. !O.matches(options::OPT_fdiagnostics_color) &&
  4552. !O.matches(options::OPT_fno_color_diagnostics) &&
  4553. !O.matches(options::OPT_fno_diagnostics_color) &&
  4554. !O.matches(options::OPT_fdiagnostics_color_EQ))
  4555. continue;
  4556. Arg->claim();
  4557. if (O.matches(options::OPT_fcolor_diagnostics) ||
  4558. O.matches(options::OPT_fdiagnostics_color)) {
  4559. ShowColors = Colors_On;
  4560. } else if (O.matches(options::OPT_fno_color_diagnostics) ||
  4561. O.matches(options::OPT_fno_diagnostics_color)) {
  4562. ShowColors = Colors_Off;
  4563. } else {
  4564. assert(O.matches(options::OPT_fdiagnostics_color_EQ));
  4565. StringRef value(Arg->getValue());
  4566. if (value == "always")
  4567. ShowColors = Colors_On;
  4568. else if (value == "never")
  4569. ShowColors = Colors_Off;
  4570. else if (value == "auto")
  4571. ShowColors = Colors_Auto;
  4572. else
  4573. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4574. << ("-fdiagnostics-color=" + value).str();
  4575. }
  4576. }
  4577. if (ShowColors == Colors_On ||
  4578. (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
  4579. CmdArgs.push_back("-fcolor-diagnostics");
  4580. if (Args.hasArg(options::OPT_fansi_escape_codes))
  4581. CmdArgs.push_back("-fansi-escape-codes");
  4582. if (!Args.hasFlag(options::OPT_fshow_source_location,
  4583. options::OPT_fno_show_source_location))
  4584. CmdArgs.push_back("-fno-show-source-location");
  4585. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  4586. true))
  4587. CmdArgs.push_back("-fno-show-column");
  4588. if (!Args.hasFlag(options::OPT_fspell_checking,
  4589. options::OPT_fno_spell_checking))
  4590. CmdArgs.push_back("-fno-spell-checking");
  4591. // -fno-asm-blocks is default.
  4592. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  4593. false))
  4594. CmdArgs.push_back("-fasm-blocks");
  4595. // -fgnu-inline-asm is default.
  4596. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  4597. options::OPT_fno_gnu_inline_asm, true))
  4598. CmdArgs.push_back("-fno-gnu-inline-asm");
  4599. // Enable vectorization per default according to the optimization level
  4600. // selected. For optimization levels that want vectorization we use the alias
  4601. // option to simplify the hasFlag logic.
  4602. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  4603. OptSpecifier VectorizeAliasOption =
  4604. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  4605. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  4606. options::OPT_fno_vectorize, EnableVec))
  4607. CmdArgs.push_back("-vectorize-loops");
  4608. // -fslp-vectorize is enabled based on the optimization level selected.
  4609. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  4610. OptSpecifier SLPVectAliasOption =
  4611. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  4612. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  4613. options::OPT_fno_slp_vectorize, EnableSLPVec))
  4614. CmdArgs.push_back("-vectorize-slp");
  4615. // -fno-slp-vectorize-aggressive is default.
  4616. if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
  4617. options::OPT_fno_slp_vectorize_aggressive, false))
  4618. CmdArgs.push_back("-vectorize-slp-aggressive");
  4619. if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
  4620. A->render(Args, CmdArgs);
  4621. // -fdollars-in-identifiers default varies depending on platform and
  4622. // language; only pass if specified.
  4623. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  4624. options::OPT_fno_dollars_in_identifiers)) {
  4625. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  4626. CmdArgs.push_back("-fdollars-in-identifiers");
  4627. else
  4628. CmdArgs.push_back("-fno-dollars-in-identifiers");
  4629. }
  4630. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  4631. // practical purposes.
  4632. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  4633. options::OPT_fno_unit_at_a_time)) {
  4634. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  4635. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  4636. }
  4637. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  4638. options::OPT_fno_apple_pragma_pack, false))
  4639. CmdArgs.push_back("-fapple-pragma-pack");
  4640. // le32-specific flags:
  4641. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  4642. // by default.
  4643. if (getToolChain().getArch() == llvm::Triple::le32) {
  4644. CmdArgs.push_back("-fno-math-builtin");
  4645. }
  4646. // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
  4647. //
  4648. // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
  4649. #if 0
  4650. if (getToolChain().getTriple().isOSDarwin() &&
  4651. (getToolChain().getArch() == llvm::Triple::arm ||
  4652. getToolChain().getArch() == llvm::Triple::thumb)) {
  4653. if (!Args.hasArg(options::OPT_fbuiltin_strcat))
  4654. CmdArgs.push_back("-fno-builtin-strcat");
  4655. if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
  4656. CmdArgs.push_back("-fno-builtin-strcpy");
  4657. }
  4658. #endif
  4659. // Enable rewrite includes if the user's asked for it or if we're generating
  4660. // diagnostics.
  4661. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  4662. // nice to enable this when doing a crashdump for modules as well.
  4663. if (Args.hasFlag(options::OPT_frewrite_includes,
  4664. options::OPT_fno_rewrite_includes, false) ||
  4665. (C.isForDiagnostics() && !HaveModules))
  4666. CmdArgs.push_back("-frewrite-includes");
  4667. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  4668. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  4669. options::OPT_traditional_cpp)) {
  4670. if (isa<PreprocessJobAction>(JA))
  4671. CmdArgs.push_back("-traditional-cpp");
  4672. else
  4673. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  4674. }
  4675. Args.AddLastArg(CmdArgs, options::OPT_dM);
  4676. Args.AddLastArg(CmdArgs, options::OPT_dD);
  4677. // Handle serialized diagnostics.
  4678. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  4679. CmdArgs.push_back("-serialize-diagnostic-file");
  4680. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  4681. }
  4682. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  4683. CmdArgs.push_back("-fretain-comments-from-system-headers");
  4684. // Forward -fcomment-block-commands to -cc1.
  4685. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  4686. // Forward -fparse-all-comments to -cc1.
  4687. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  4688. // Turn -fplugin=name.so into -load name.so
  4689. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  4690. CmdArgs.push_back("-load");
  4691. CmdArgs.push_back(A->getValue());
  4692. A->claim();
  4693. }
  4694. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  4695. // parser.
  4696. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  4697. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  4698. A->claim();
  4699. // We translate this by hand to the -cc1 argument, since nightly test uses
  4700. // it and developers have been trained to spell it with -mllvm.
  4701. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  4702. CmdArgs.push_back("-disable-llvm-optzns");
  4703. } else
  4704. A->render(Args, CmdArgs);
  4705. }
  4706. // With -save-temps, we want to save the unoptimized bitcode output from the
  4707. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  4708. // by the frontend.
  4709. if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
  4710. CmdArgs.push_back("-disable-llvm-passes");
  4711. if (Output.getType() == types::TY_Dependencies) {
  4712. // Handled with other dependency code.
  4713. } else if (Output.isFilename()) {
  4714. CmdArgs.push_back("-o");
  4715. CmdArgs.push_back(Output.getFilename());
  4716. } else {
  4717. assert(Output.isNothing() && "Invalid output.");
  4718. }
  4719. addDashXForInput(Args, Input, CmdArgs);
  4720. if (Input.isFilename())
  4721. CmdArgs.push_back(Input.getFilename());
  4722. else
  4723. Input.getInputArg().renderAsInput(Args, CmdArgs);
  4724. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  4725. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  4726. // Optionally embed the -cc1 level arguments into the debug info, for build
  4727. // analysis.
  4728. if (getToolChain().UseDwarfDebugFlags()) {
  4729. ArgStringList OriginalArgs;
  4730. for (const auto &Arg : Args)
  4731. Arg->render(Args, OriginalArgs);
  4732. SmallString<256> Flags;
  4733. Flags += Exec;
  4734. for (const char *OriginalArg : OriginalArgs) {
  4735. SmallString<128> EscapedArg;
  4736. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  4737. Flags += " ";
  4738. Flags += EscapedArg;
  4739. }
  4740. CmdArgs.push_back("-dwarf-debug-flags");
  4741. CmdArgs.push_back(Args.MakeArgString(Flags));
  4742. }
  4743. // Add the split debug info name to the command lines here so we
  4744. // can propagate it to the backend.
  4745. bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
  4746. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  4747. isa<BackendJobAction>(JA));
  4748. const char *SplitDwarfOut;
  4749. if (SplitDwarf) {
  4750. CmdArgs.push_back("-split-dwarf-file");
  4751. SplitDwarfOut = SplitDebugName(Args, Input);
  4752. CmdArgs.push_back(SplitDwarfOut);
  4753. }
  4754. // Host-side cuda compilation receives device-side outputs as Inputs[1...].
  4755. // Include them with -fcuda-include-gpubinary.
  4756. if (IsCuda && Inputs.size() > 1)
  4757. for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
  4758. CmdArgs.push_back("-fcuda-include-gpubinary");
  4759. CmdArgs.push_back(I->getFilename());
  4760. }
  4761. // Finally add the compile command to the compilation.
  4762. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  4763. Output.getType() == types::TY_Object &&
  4764. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  4765. auto CLCommand =
  4766. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  4767. C.addCommand(llvm::make_unique<FallbackCommand>(
  4768. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  4769. } else {
  4770. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  4771. }
  4772. // Handle the debug info splitting at object creation time if we're
  4773. // creating an object.
  4774. // TODO: Currently only works on linux with newer objcopy.
  4775. if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  4776. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
  4777. if (Arg *A = Args.getLastArg(options::OPT_pg))
  4778. if (Args.hasArg(options::OPT_fomit_frame_pointer))
  4779. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  4780. << A->getAsString(Args);
  4781. // Claim some arguments which clang supports automatically.
  4782. // -fpch-preprocess is used with gcc to add a special marker in the output to
  4783. // include the PCH file. Clang's PTH solution is completely transparent, so we
  4784. // do not need to deal with it at all.
  4785. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  4786. // Claim some arguments which clang doesn't support, but we don't
  4787. // care to warn the user about.
  4788. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  4789. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  4790. // Disable warnings for clang -E -emit-llvm foo.c
  4791. Args.ClaimAllArgs(options::OPT_emit_llvm);
  4792. }
  4793. /// Add options related to the Objective-C runtime/ABI.
  4794. ///
  4795. /// Returns true if the runtime is non-fragile.
  4796. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  4797. ArgStringList &cmdArgs,
  4798. RewriteKind rewriteKind) const {
  4799. // Look for the controlling runtime option.
  4800. Arg *runtimeArg =
  4801. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  4802. options::OPT_fobjc_runtime_EQ);
  4803. // Just forward -fobjc-runtime= to the frontend. This supercedes
  4804. // options about fragility.
  4805. if (runtimeArg &&
  4806. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  4807. ObjCRuntime runtime;
  4808. StringRef value = runtimeArg->getValue();
  4809. if (runtime.tryParse(value)) {
  4810. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  4811. << value;
  4812. }
  4813. runtimeArg->render(args, cmdArgs);
  4814. return runtime;
  4815. }
  4816. // Otherwise, we'll need the ABI "version". Version numbers are
  4817. // slightly confusing for historical reasons:
  4818. // 1 - Traditional "fragile" ABI
  4819. // 2 - Non-fragile ABI, version 1
  4820. // 3 - Non-fragile ABI, version 2
  4821. unsigned objcABIVersion = 1;
  4822. // If -fobjc-abi-version= is present, use that to set the version.
  4823. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  4824. StringRef value = abiArg->getValue();
  4825. if (value == "1")
  4826. objcABIVersion = 1;
  4827. else if (value == "2")
  4828. objcABIVersion = 2;
  4829. else if (value == "3")
  4830. objcABIVersion = 3;
  4831. else
  4832. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  4833. } else {
  4834. // Otherwise, determine if we are using the non-fragile ABI.
  4835. bool nonFragileABIIsDefault =
  4836. (rewriteKind == RK_NonFragile ||
  4837. (rewriteKind == RK_None &&
  4838. getToolChain().IsObjCNonFragileABIDefault()));
  4839. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  4840. options::OPT_fno_objc_nonfragile_abi,
  4841. nonFragileABIIsDefault)) {
  4842. // Determine the non-fragile ABI version to use.
  4843. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  4844. unsigned nonFragileABIVersion = 1;
  4845. #else
  4846. unsigned nonFragileABIVersion = 2;
  4847. #endif
  4848. if (Arg *abiArg =
  4849. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  4850. StringRef value = abiArg->getValue();
  4851. if (value == "1")
  4852. nonFragileABIVersion = 1;
  4853. else if (value == "2")
  4854. nonFragileABIVersion = 2;
  4855. else
  4856. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4857. << value;
  4858. }
  4859. objcABIVersion = 1 + nonFragileABIVersion;
  4860. } else {
  4861. objcABIVersion = 1;
  4862. }
  4863. }
  4864. // We don't actually care about the ABI version other than whether
  4865. // it's non-fragile.
  4866. bool isNonFragile = objcABIVersion != 1;
  4867. // If we have no runtime argument, ask the toolchain for its default runtime.
  4868. // However, the rewriter only really supports the Mac runtime, so assume that.
  4869. ObjCRuntime runtime;
  4870. if (!runtimeArg) {
  4871. switch (rewriteKind) {
  4872. case RK_None:
  4873. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  4874. break;
  4875. case RK_Fragile:
  4876. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  4877. break;
  4878. case RK_NonFragile:
  4879. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  4880. break;
  4881. }
  4882. // -fnext-runtime
  4883. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  4884. // On Darwin, make this use the default behavior for the toolchain.
  4885. if (getToolChain().getTriple().isOSDarwin()) {
  4886. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  4887. // Otherwise, build for a generic macosx port.
  4888. } else {
  4889. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  4890. }
  4891. // -fgnu-runtime
  4892. } else {
  4893. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  4894. // Legacy behaviour is to target the gnustep runtime if we are i
  4895. // non-fragile mode or the GCC runtime in fragile mode.
  4896. if (isNonFragile)
  4897. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
  4898. else
  4899. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  4900. }
  4901. cmdArgs.push_back(
  4902. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  4903. return runtime;
  4904. }
  4905. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  4906. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  4907. I += HaveDash;
  4908. return !HaveDash;
  4909. }
  4910. namespace {
  4911. struct EHFlags {
  4912. EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
  4913. bool Synch;
  4914. bool Asynch;
  4915. bool NoExceptC;
  4916. };
  4917. } // end anonymous namespace
  4918. /// /EH controls whether to run destructor cleanups when exceptions are
  4919. /// thrown. There are three modifiers:
  4920. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  4921. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  4922. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  4923. /// - c: Assume that extern "C" functions are implicitly noexcept. This
  4924. /// modifier is an optimization, so we ignore it for now.
  4925. /// The default is /EHs-c-, meaning cleanups are disabled.
  4926. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  4927. EHFlags EH;
  4928. std::vector<std::string> EHArgs =
  4929. Args.getAllArgValues(options::OPT__SLASH_EH);
  4930. for (auto EHVal : EHArgs) {
  4931. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  4932. switch (EHVal[I]) {
  4933. case 'a':
  4934. EH.Asynch = maybeConsumeDash(EHVal, I);
  4935. continue;
  4936. case 'c':
  4937. EH.NoExceptC = maybeConsumeDash(EHVal, I);
  4938. continue;
  4939. case 's':
  4940. EH.Synch = maybeConsumeDash(EHVal, I);
  4941. continue;
  4942. default:
  4943. break;
  4944. }
  4945. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  4946. break;
  4947. }
  4948. }
  4949. return EH;
  4950. }
  4951. void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
  4952. enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
  4953. bool *EmitCodeView) const {
  4954. unsigned RTOptionID = options::OPT__SLASH_MT;
  4955. if (Args.hasArg(options::OPT__SLASH_LDd))
  4956. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  4957. // but defining _DEBUG is sticky.
  4958. RTOptionID = options::OPT__SLASH_MTd;
  4959. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  4960. RTOptionID = A->getOption().getID();
  4961. StringRef FlagForCRT;
  4962. switch (RTOptionID) {
  4963. case options::OPT__SLASH_MD:
  4964. if (Args.hasArg(options::OPT__SLASH_LDd))
  4965. CmdArgs.push_back("-D_DEBUG");
  4966. CmdArgs.push_back("-D_MT");
  4967. CmdArgs.push_back("-D_DLL");
  4968. FlagForCRT = "--dependent-lib=msvcrt";
  4969. break;
  4970. case options::OPT__SLASH_MDd:
  4971. CmdArgs.push_back("-D_DEBUG");
  4972. CmdArgs.push_back("-D_MT");
  4973. CmdArgs.push_back("-D_DLL");
  4974. FlagForCRT = "--dependent-lib=msvcrtd";
  4975. break;
  4976. case options::OPT__SLASH_MT:
  4977. if (Args.hasArg(options::OPT__SLASH_LDd))
  4978. CmdArgs.push_back("-D_DEBUG");
  4979. CmdArgs.push_back("-D_MT");
  4980. FlagForCRT = "--dependent-lib=libcmt";
  4981. break;
  4982. case options::OPT__SLASH_MTd:
  4983. CmdArgs.push_back("-D_DEBUG");
  4984. CmdArgs.push_back("-D_MT");
  4985. FlagForCRT = "--dependent-lib=libcmtd";
  4986. break;
  4987. default:
  4988. llvm_unreachable("Unexpected option ID.");
  4989. }
  4990. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  4991. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  4992. } else {
  4993. CmdArgs.push_back(FlagForCRT.data());
  4994. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  4995. // users want. The /Za flag to cl.exe turns this off, but it's not
  4996. // implemented in clang.
  4997. CmdArgs.push_back("--dependent-lib=oldnames");
  4998. }
  4999. // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
  5000. // would produce interleaved output, so ignore /showIncludes in such cases.
  5001. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
  5002. if (Arg *A = Args.getLastArg(options::OPT_show_includes))
  5003. A->render(Args, CmdArgs);
  5004. // This controls whether or not we emit RTTI data for polymorphic types.
  5005. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  5006. /*default=*/false))
  5007. CmdArgs.push_back("-fno-rtti-data");
  5008. // Emit CodeView if -Z7 is present.
  5009. *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
  5010. bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
  5011. // If we are emitting CV but not DWARF, don't build information that LLVM
  5012. // can't yet process.
  5013. if (*EmitCodeView && !EmitDwarf)
  5014. *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
  5015. if (*EmitCodeView)
  5016. CmdArgs.push_back("-gcodeview");
  5017. const Driver &D = getToolChain().getDriver();
  5018. EHFlags EH = parseClangCLEHFlags(D, Args);
  5019. // FIXME: Do something with NoExceptC.
  5020. if (EH.Synch || EH.Asynch) {
  5021. CmdArgs.push_back("-fcxx-exceptions");
  5022. CmdArgs.push_back("-fexceptions");
  5023. }
  5024. // /EP should expand to -E -P.
  5025. if (Args.hasArg(options::OPT__SLASH_EP)) {
  5026. CmdArgs.push_back("-E");
  5027. CmdArgs.push_back("-P");
  5028. }
  5029. unsigned VolatileOptionID;
  5030. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  5031. getToolChain().getArch() == llvm::Triple::x86)
  5032. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  5033. else
  5034. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  5035. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  5036. VolatileOptionID = A->getOption().getID();
  5037. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  5038. CmdArgs.push_back("-fms-volatile");
  5039. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  5040. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  5041. if (MostGeneralArg && BestCaseArg)
  5042. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5043. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  5044. if (MostGeneralArg) {
  5045. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  5046. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  5047. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  5048. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  5049. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  5050. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  5051. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5052. << FirstConflict->getAsString(Args)
  5053. << SecondConflict->getAsString(Args);
  5054. if (SingleArg)
  5055. CmdArgs.push_back("-fms-memptr-rep=single");
  5056. else if (MultipleArg)
  5057. CmdArgs.push_back("-fms-memptr-rep=multiple");
  5058. else
  5059. CmdArgs.push_back("-fms-memptr-rep=virtual");
  5060. }
  5061. if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
  5062. A->render(Args, CmdArgs);
  5063. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  5064. CmdArgs.push_back("-fdiagnostics-format");
  5065. if (Args.hasArg(options::OPT__SLASH_fallback))
  5066. CmdArgs.push_back("msvc-fallback");
  5067. else
  5068. CmdArgs.push_back("msvc");
  5069. }
  5070. }
  5071. visualstudio::Compiler *Clang::getCLFallback() const {
  5072. if (!CLFallback)
  5073. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  5074. return CLFallback.get();
  5075. }
  5076. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  5077. ArgStringList &CmdArgs) const {
  5078. StringRef CPUName;
  5079. StringRef ABIName;
  5080. const llvm::Triple &Triple = getToolChain().getTriple();
  5081. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  5082. CmdArgs.push_back("-target-abi");
  5083. CmdArgs.push_back(ABIName.data());
  5084. }
  5085. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  5086. const InputInfo &Output, const InputInfoList &Inputs,
  5087. const ArgList &Args,
  5088. const char *LinkingOutput) const {
  5089. ArgStringList CmdArgs;
  5090. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5091. const InputInfo &Input = Inputs[0];
  5092. std::string TripleStr =
  5093. getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
  5094. const llvm::Triple Triple(TripleStr);
  5095. // Don't warn about "clang -w -c foo.s"
  5096. Args.ClaimAllArgs(options::OPT_w);
  5097. // and "clang -emit-llvm -c foo.s"
  5098. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5099. claimNoWarnArgs(Args);
  5100. // Invoke ourselves in -cc1as mode.
  5101. //
  5102. // FIXME: Implement custom jobs for internal actions.
  5103. CmdArgs.push_back("-cc1as");
  5104. // Add the "effective" target triple.
  5105. CmdArgs.push_back("-triple");
  5106. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  5107. // Set the output mode, we currently only expect to be used as a real
  5108. // assembler.
  5109. CmdArgs.push_back("-filetype");
  5110. CmdArgs.push_back("obj");
  5111. // Set the main file name, so that debug info works even with
  5112. // -save-temps or preprocessed assembly.
  5113. CmdArgs.push_back("-main-file-name");
  5114. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  5115. // Add the target cpu
  5116. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  5117. if (!CPU.empty()) {
  5118. CmdArgs.push_back("-target-cpu");
  5119. CmdArgs.push_back(Args.MakeArgString(CPU));
  5120. }
  5121. // Add the target features
  5122. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  5123. // Ignore explicit -force_cpusubtype_ALL option.
  5124. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  5125. // Pass along any -I options so we get proper .include search paths.
  5126. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  5127. // Determine the original source input.
  5128. const Action *SourceAction = &JA;
  5129. while (SourceAction->getKind() != Action::InputClass) {
  5130. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5131. SourceAction = SourceAction->getInputs()[0];
  5132. }
  5133. // Forward -g and handle debug info related flags, assuming we are dealing
  5134. // with an actual assembly file.
  5135. if (SourceAction->getType() == types::TY_Asm ||
  5136. SourceAction->getType() == types::TY_PP_Asm) {
  5137. bool WantDebug = false;
  5138. unsigned DwarfVersion = 0;
  5139. Args.ClaimAllArgs(options::OPT_g_Group);
  5140. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  5141. WantDebug = !A->getOption().matches(options::OPT_g0);
  5142. if (WantDebug)
  5143. DwarfVersion = DwarfVersionNum(A->getSpelling());
  5144. }
  5145. if (DwarfVersion == 0)
  5146. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  5147. RenderDebugEnablingArgs(Args, CmdArgs,
  5148. (WantDebug ? CodeGenOptions::LimitedDebugInfo
  5149. : CodeGenOptions::NoDebugInfo),
  5150. DwarfVersion);
  5151. // Add the -fdebug-compilation-dir flag if needed.
  5152. addDebugCompDirArg(Args, CmdArgs);
  5153. // Set the AT_producer to the clang version when using the integrated
  5154. // assembler on assembly source files.
  5155. CmdArgs.push_back("-dwarf-debug-producer");
  5156. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  5157. // And pass along -I options
  5158. Args.AddAllArgs(CmdArgs, options::OPT_I);
  5159. }
  5160. // Handle -fPIC et al -- the relocation-model affects the assembler
  5161. // for some targets.
  5162. llvm::Reloc::Model RelocationModel;
  5163. unsigned PICLevel;
  5164. bool IsPIE;
  5165. std::tie(RelocationModel, PICLevel, IsPIE) =
  5166. ParsePICArgs(getToolChain(), Triple, Args);
  5167. const char *RMName = RelocationModelName(RelocationModel);
  5168. if (RMName) {
  5169. CmdArgs.push_back("-mrelocation-model");
  5170. CmdArgs.push_back(RMName);
  5171. }
  5172. // Optionally embed the -cc1as level arguments into the debug info, for build
  5173. // analysis.
  5174. if (getToolChain().UseDwarfDebugFlags()) {
  5175. ArgStringList OriginalArgs;
  5176. for (const auto &Arg : Args)
  5177. Arg->render(Args, OriginalArgs);
  5178. SmallString<256> Flags;
  5179. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5180. Flags += Exec;
  5181. for (const char *OriginalArg : OriginalArgs) {
  5182. SmallString<128> EscapedArg;
  5183. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5184. Flags += " ";
  5185. Flags += EscapedArg;
  5186. }
  5187. CmdArgs.push_back("-dwarf-debug-flags");
  5188. CmdArgs.push_back(Args.MakeArgString(Flags));
  5189. }
  5190. // FIXME: Add -static support, once we have it.
  5191. // Add target specific flags.
  5192. switch (getToolChain().getArch()) {
  5193. default:
  5194. break;
  5195. case llvm::Triple::mips:
  5196. case llvm::Triple::mipsel:
  5197. case llvm::Triple::mips64:
  5198. case llvm::Triple::mips64el:
  5199. AddMIPSTargetArgs(Args, CmdArgs);
  5200. break;
  5201. }
  5202. // Consume all the warning flags. Usually this would be handled more
  5203. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  5204. // doesn't handle that so rather than warning about unused flags that are
  5205. // actually used, we'll lie by omission instead.
  5206. // FIXME: Stop lying and consume only the appropriate driver flags
  5207. for (const Arg *A : Args.filtered(options::OPT_W_Group))
  5208. A->claim();
  5209. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  5210. getToolChain().getDriver());
  5211. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  5212. assert(Output.isFilename() && "Unexpected lipo output.");
  5213. CmdArgs.push_back("-o");
  5214. CmdArgs.push_back(Output.getFilename());
  5215. assert(Input.isFilename() && "Invalid input.");
  5216. CmdArgs.push_back(Input.getFilename());
  5217. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5218. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5219. // Handle the debug info splitting at object creation time if we're
  5220. // creating an object.
  5221. // TODO: Currently only works on linux with newer objcopy.
  5222. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  5223. getToolChain().getTriple().isOSLinux())
  5224. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  5225. SplitDebugName(Args, Input));
  5226. }
  5227. void GnuTool::anchor() {}
  5228. void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  5229. const InputInfo &Output,
  5230. const InputInfoList &Inputs, const ArgList &Args,
  5231. const char *LinkingOutput) const {
  5232. const Driver &D = getToolChain().getDriver();
  5233. ArgStringList CmdArgs;
  5234. for (const auto &A : Args) {
  5235. if (forwardToGCC(A->getOption())) {
  5236. // Don't forward any -g arguments to assembly steps.
  5237. if (isa<AssembleJobAction>(JA) &&
  5238. A->getOption().matches(options::OPT_g_Group))
  5239. continue;
  5240. // Don't forward any -W arguments to assembly and link steps.
  5241. if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
  5242. A->getOption().matches(options::OPT_W_Group))
  5243. continue;
  5244. // It is unfortunate that we have to claim here, as this means
  5245. // we will basically never report anything interesting for
  5246. // platforms using a generic gcc, even if we are just using gcc
  5247. // to get to the assembler.
  5248. A->claim();
  5249. A->render(Args, CmdArgs);
  5250. }
  5251. }
  5252. RenderExtraToolArgs(JA, CmdArgs);
  5253. // If using a driver driver, force the arch.
  5254. if (getToolChain().getTriple().isOSDarwin()) {
  5255. CmdArgs.push_back("-arch");
  5256. CmdArgs.push_back(
  5257. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  5258. }
  5259. // Try to force gcc to match the tool chain we want, if we recognize
  5260. // the arch.
  5261. //
  5262. // FIXME: The triple class should directly provide the information we want
  5263. // here.
  5264. switch (getToolChain().getArch()) {
  5265. default:
  5266. break;
  5267. case llvm::Triple::x86:
  5268. case llvm::Triple::ppc:
  5269. CmdArgs.push_back("-m32");
  5270. break;
  5271. case llvm::Triple::x86_64:
  5272. case llvm::Triple::ppc64:
  5273. case llvm::Triple::ppc64le:
  5274. CmdArgs.push_back("-m64");
  5275. break;
  5276. case llvm::Triple::sparcel:
  5277. CmdArgs.push_back("-EL");
  5278. break;
  5279. }
  5280. if (Output.isFilename()) {
  5281. CmdArgs.push_back("-o");
  5282. CmdArgs.push_back(Output.getFilename());
  5283. } else {
  5284. assert(Output.isNothing() && "Unexpected output");
  5285. CmdArgs.push_back("-fsyntax-only");
  5286. }
  5287. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5288. // Only pass -x if gcc will understand it; otherwise hope gcc
  5289. // understands the suffix correctly. The main use case this would go
  5290. // wrong in is for linker inputs if they happened to have an odd
  5291. // suffix; really the only way to get this to happen is a command
  5292. // like '-x foobar a.c' which will treat a.c like a linker input.
  5293. //
  5294. // FIXME: For the linker case specifically, can we safely convert
  5295. // inputs into '-Wl,' options?
  5296. for (const auto &II : Inputs) {
  5297. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5298. if (types::isLLVMIR(II.getType()))
  5299. D.Diag(diag::err_drv_no_linker_llvm_support)
  5300. << getToolChain().getTripleString();
  5301. else if (II.getType() == types::TY_AST)
  5302. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  5303. else if (II.getType() == types::TY_ModuleFile)
  5304. D.Diag(diag::err_drv_no_module_support)
  5305. << getToolChain().getTripleString();
  5306. if (types::canTypeBeUserSpecified(II.getType())) {
  5307. CmdArgs.push_back("-x");
  5308. CmdArgs.push_back(types::getTypeName(II.getType()));
  5309. }
  5310. if (II.isFilename())
  5311. CmdArgs.push_back(II.getFilename());
  5312. else {
  5313. const Arg &A = II.getInputArg();
  5314. // Reverse translate some rewritten options.
  5315. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  5316. CmdArgs.push_back("-lstdc++");
  5317. continue;
  5318. }
  5319. // Don't render as input, we need gcc to do the translations.
  5320. A.render(Args, CmdArgs);
  5321. }
  5322. }
  5323. const std::string customGCCName = D.getCCCGenericGCCName();
  5324. const char *GCCName;
  5325. if (!customGCCName.empty())
  5326. GCCName = customGCCName.c_str();
  5327. else if (D.CCCIsCXX()) {
  5328. GCCName = "g++";
  5329. } else
  5330. GCCName = "gcc";
  5331. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  5332. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5333. }
  5334. void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
  5335. ArgStringList &CmdArgs) const {
  5336. CmdArgs.push_back("-E");
  5337. }
  5338. void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  5339. ArgStringList &CmdArgs) const {
  5340. const Driver &D = getToolChain().getDriver();
  5341. switch (JA.getType()) {
  5342. // If -flto, etc. are present then make sure not to force assembly output.
  5343. case types::TY_LLVM_IR:
  5344. case types::TY_LTO_IR:
  5345. case types::TY_LLVM_BC:
  5346. case types::TY_LTO_BC:
  5347. CmdArgs.push_back("-c");
  5348. break;
  5349. case types::TY_PP_Asm:
  5350. CmdArgs.push_back("-S");
  5351. break;
  5352. case types::TY_Nothing:
  5353. CmdArgs.push_back("-fsyntax-only");
  5354. break;
  5355. default:
  5356. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  5357. }
  5358. }
  5359. void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  5360. ArgStringList &CmdArgs) const {
  5361. // The types are (hopefully) good enough.
  5362. }
  5363. // Hexagon tools start.
  5364. void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
  5365. ArgStringList &CmdArgs) const {
  5366. }
  5367. void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5368. const InputInfo &Output,
  5369. const InputInfoList &Inputs,
  5370. const ArgList &Args,
  5371. const char *LinkingOutput) const {
  5372. claimNoWarnArgs(Args);
  5373. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  5374. const Driver &D = HTC.getDriver();
  5375. ArgStringList CmdArgs;
  5376. std::string MArchString = "-march=hexagon";
  5377. CmdArgs.push_back(Args.MakeArgString(MArchString));
  5378. RenderExtraToolArgs(JA, CmdArgs);
  5379. std::string AsName = "hexagon-llvm-mc";
  5380. std::string MCpuString = "-mcpu=hexagon" +
  5381. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5382. CmdArgs.push_back("-filetype=obj");
  5383. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5384. if (Output.isFilename()) {
  5385. CmdArgs.push_back("-o");
  5386. CmdArgs.push_back(Output.getFilename());
  5387. } else {
  5388. assert(Output.isNothing() && "Unexpected output");
  5389. CmdArgs.push_back("-fsyntax-only");
  5390. }
  5391. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5392. std::string N = llvm::utostr(G.getValue());
  5393. CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
  5394. }
  5395. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5396. // Only pass -x if gcc will understand it; otherwise hope gcc
  5397. // understands the suffix correctly. The main use case this would go
  5398. // wrong in is for linker inputs if they happened to have an odd
  5399. // suffix; really the only way to get this to happen is a command
  5400. // like '-x foobar a.c' which will treat a.c like a linker input.
  5401. //
  5402. // FIXME: For the linker case specifically, can we safely convert
  5403. // inputs into '-Wl,' options?
  5404. for (const auto &II : Inputs) {
  5405. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5406. if (types::isLLVMIR(II.getType()))
  5407. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  5408. << HTC.getTripleString();
  5409. else if (II.getType() == types::TY_AST)
  5410. D.Diag(clang::diag::err_drv_no_ast_support)
  5411. << HTC.getTripleString();
  5412. else if (II.getType() == types::TY_ModuleFile)
  5413. D.Diag(diag::err_drv_no_module_support)
  5414. << HTC.getTripleString();
  5415. if (II.isFilename())
  5416. CmdArgs.push_back(II.getFilename());
  5417. else
  5418. // Don't render as input, we need gcc to do the translations.
  5419. // FIXME: What is this?
  5420. II.getInputArg().render(Args, CmdArgs);
  5421. }
  5422. auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
  5423. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5424. }
  5425. void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
  5426. ArgStringList &CmdArgs) const {
  5427. }
  5428. static void
  5429. constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
  5430. const toolchains::HexagonToolChain &HTC,
  5431. const InputInfo &Output, const InputInfoList &Inputs,
  5432. const ArgList &Args, ArgStringList &CmdArgs,
  5433. const char *LinkingOutput) {
  5434. const Driver &D = HTC.getDriver();
  5435. //----------------------------------------------------------------------------
  5436. //
  5437. //----------------------------------------------------------------------------
  5438. bool IsStatic = Args.hasArg(options::OPT_static);
  5439. bool IsShared = Args.hasArg(options::OPT_shared);
  5440. bool IsPIE = Args.hasArg(options::OPT_pie);
  5441. bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
  5442. bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
  5443. bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
  5444. bool UseG0 = false;
  5445. bool UseShared = IsShared && !IsStatic;
  5446. //----------------------------------------------------------------------------
  5447. // Silence warnings for various options
  5448. //----------------------------------------------------------------------------
  5449. Args.ClaimAllArgs(options::OPT_g_Group);
  5450. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5451. Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
  5452. // handled somewhere else.
  5453. Args.ClaimAllArgs(options::OPT_static_libgcc);
  5454. //----------------------------------------------------------------------------
  5455. //
  5456. //----------------------------------------------------------------------------
  5457. if (Args.hasArg(options::OPT_s))
  5458. CmdArgs.push_back("-s");
  5459. if (Args.hasArg(options::OPT_r))
  5460. CmdArgs.push_back("-r");
  5461. for (const auto &Opt : HTC.ExtraOpts)
  5462. CmdArgs.push_back(Opt.c_str());
  5463. CmdArgs.push_back("-march=hexagon");
  5464. std::string CpuVer =
  5465. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5466. std::string MCpuString = "-mcpu=hexagon" + CpuVer;
  5467. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5468. if (IsShared) {
  5469. CmdArgs.push_back("-shared");
  5470. // The following should be the default, but doing as hexagon-gcc does.
  5471. CmdArgs.push_back("-call_shared");
  5472. }
  5473. if (IsStatic)
  5474. CmdArgs.push_back("-static");
  5475. if (IsPIE && !IsShared)
  5476. CmdArgs.push_back("-pie");
  5477. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5478. std::string N = llvm::utostr(G.getValue());
  5479. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
  5480. UseG0 = G.getValue() == 0;
  5481. }
  5482. //----------------------------------------------------------------------------
  5483. //
  5484. //----------------------------------------------------------------------------
  5485. CmdArgs.push_back("-o");
  5486. CmdArgs.push_back(Output.getFilename());
  5487. //----------------------------------------------------------------------------
  5488. // moslib
  5489. //----------------------------------------------------------------------------
  5490. std::vector<std::string> OsLibs;
  5491. bool HasStandalone = false;
  5492. for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
  5493. A->claim();
  5494. OsLibs.emplace_back(A->getValue());
  5495. HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
  5496. }
  5497. if (OsLibs.empty()) {
  5498. OsLibs.push_back("standalone");
  5499. HasStandalone = true;
  5500. }
  5501. //----------------------------------------------------------------------------
  5502. // Start Files
  5503. //----------------------------------------------------------------------------
  5504. const std::string MCpuSuffix = "/" + CpuVer;
  5505. const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
  5506. const std::string RootDir =
  5507. HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
  5508. const std::string StartSubDir =
  5509. "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
  5510. auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
  5511. const char *Name) -> std::string {
  5512. std::string RelName = SubDir + Name;
  5513. std::string P = HTC.GetFilePath(RelName.c_str());
  5514. if (llvm::sys::fs::exists(P))
  5515. return P;
  5516. return RootDir + RelName;
  5517. };
  5518. if (IncStdLib && IncStartFiles) {
  5519. if (!IsShared) {
  5520. if (HasStandalone) {
  5521. std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
  5522. CmdArgs.push_back(Args.MakeArgString(Crt0SA));
  5523. }
  5524. std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
  5525. CmdArgs.push_back(Args.MakeArgString(Crt0));
  5526. }
  5527. std::string Init = UseShared
  5528. ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
  5529. : Find(RootDir, StartSubDir, "/init.o");
  5530. CmdArgs.push_back(Args.MakeArgString(Init));
  5531. }
  5532. //----------------------------------------------------------------------------
  5533. // Library Search Paths
  5534. //----------------------------------------------------------------------------
  5535. const ToolChain::path_list &LibPaths = HTC.getFilePaths();
  5536. for (const auto &LibPath : LibPaths)
  5537. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  5538. //----------------------------------------------------------------------------
  5539. //
  5540. //----------------------------------------------------------------------------
  5541. Args.AddAllArgs(CmdArgs,
  5542. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  5543. options::OPT_t, options::OPT_u_Group});
  5544. AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
  5545. //----------------------------------------------------------------------------
  5546. // Libraries
  5547. //----------------------------------------------------------------------------
  5548. if (IncStdLib && IncDefLibs) {
  5549. if (D.CCCIsCXX()) {
  5550. HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
  5551. CmdArgs.push_back("-lm");
  5552. }
  5553. CmdArgs.push_back("--start-group");
  5554. if (!IsShared) {
  5555. for (const std::string &Lib : OsLibs)
  5556. CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
  5557. CmdArgs.push_back("-lc");
  5558. }
  5559. CmdArgs.push_back("-lgcc");
  5560. CmdArgs.push_back("--end-group");
  5561. }
  5562. //----------------------------------------------------------------------------
  5563. // End files
  5564. //----------------------------------------------------------------------------
  5565. if (IncStdLib && IncStartFiles) {
  5566. std::string Fini = UseShared
  5567. ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
  5568. : Find(RootDir, StartSubDir, "/fini.o");
  5569. CmdArgs.push_back(Args.MakeArgString(Fini));
  5570. }
  5571. }
  5572. void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5573. const InputInfo &Output,
  5574. const InputInfoList &Inputs,
  5575. const ArgList &Args,
  5576. const char *LinkingOutput) const {
  5577. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  5578. ArgStringList CmdArgs;
  5579. constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
  5580. LinkingOutput);
  5581. std::string Linker = HTC.GetProgramPath("hexagon-link");
  5582. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5583. CmdArgs, Inputs));
  5584. }
  5585. // Hexagon tools end.
  5586. void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5587. const InputInfo &Output,
  5588. const InputInfoList &Inputs,
  5589. const ArgList &Args,
  5590. const char *LinkingOutput) const {
  5591. std::string Linker = getToolChain().GetProgramPath(getShortName());
  5592. ArgStringList CmdArgs;
  5593. CmdArgs.push_back("-flavor");
  5594. CmdArgs.push_back("old-gnu");
  5595. CmdArgs.push_back("-target");
  5596. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  5597. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  5598. CmdArgs.push_back("-o");
  5599. CmdArgs.push_back(Output.getFilename());
  5600. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5601. CmdArgs, Inputs));
  5602. }
  5603. // AMDGPU tools end.
  5604. const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  5605. std::string MArch;
  5606. if (!Arch.empty())
  5607. MArch = Arch;
  5608. else
  5609. MArch = Triple.getArchName();
  5610. MArch = StringRef(MArch).split("+").first.lower();
  5611. // Handle -march=native.
  5612. if (MArch == "native") {
  5613. std::string CPU = llvm::sys::getHostCPUName();
  5614. if (CPU != "generic") {
  5615. // Translate the native cpu into the architecture suffix for that CPU.
  5616. StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  5617. // If there is no valid architecture suffix for this CPU we don't know how
  5618. // to handle it, so return no architecture.
  5619. if (Suffix.empty())
  5620. MArch = "";
  5621. else
  5622. MArch = std::string("arm") + Suffix.str();
  5623. }
  5624. }
  5625. return MArch;
  5626. }
  5627. /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
  5628. StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  5629. std::string MArch = getARMArch(Arch, Triple);
  5630. // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  5631. // here means an -march=native that we can't handle, so instead return no CPU.
  5632. if (MArch.empty())
  5633. return StringRef();
  5634. // We need to return an empty string here on invalid MArch values as the
  5635. // various places that call this function can't cope with a null result.
  5636. return Triple.getARMCPUForArch(MArch);
  5637. }
  5638. /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
  5639. std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
  5640. const llvm::Triple &Triple) {
  5641. // FIXME: Warn on inconsistent use of -mcpu and -march.
  5642. // If we have -mcpu=, use that.
  5643. if (!CPU.empty()) {
  5644. std::string MCPU = StringRef(CPU).split("+").first.lower();
  5645. // Handle -mcpu=native.
  5646. if (MCPU == "native")
  5647. return llvm::sys::getHostCPUName();
  5648. else
  5649. return MCPU;
  5650. }
  5651. return getARMCPUForMArch(Arch, Triple);
  5652. }
  5653. /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
  5654. /// CPU (or Arch, if CPU is generic).
  5655. // FIXME: This is redundant with -mcpu, why does LLVM use this.
  5656. StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
  5657. const llvm::Triple &Triple) {
  5658. unsigned ArchKind;
  5659. if (CPU == "generic") {
  5660. std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
  5661. ArchKind = llvm::ARM::parseArch(ARMArch);
  5662. if (ArchKind == llvm::ARM::AK_INVALID)
  5663. // In case of generic Arch, i.e. "arm",
  5664. // extract arch from default cpu of the Triple
  5665. ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  5666. } else {
  5667. // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
  5668. // armv7k triple if it's actually been specified via "-arch armv7k".
  5669. ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
  5670. ? (unsigned)llvm::ARM::AK_ARMV7K
  5671. : llvm::ARM::parseCPUArch(CPU);
  5672. }
  5673. if (ArchKind == llvm::ARM::AK_INVALID)
  5674. return "";
  5675. return llvm::ARM::getSubArch(ArchKind);
  5676. }
  5677. void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
  5678. const llvm::Triple &Triple) {
  5679. if (Args.hasArg(options::OPT_r))
  5680. return;
  5681. // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  5682. // to generate BE-8 executables.
  5683. if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
  5684. CmdArgs.push_back("--be8");
  5685. }
  5686. mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
  5687. // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
  5688. // was first introduced in Release 3. However, other compilers have
  5689. // traditionally allowed it for Release 2 so we should do the same.
  5690. return (NanEncoding)llvm::StringSwitch<int>(CPU)
  5691. .Case("mips1", NanLegacy)
  5692. .Case("mips2", NanLegacy)
  5693. .Case("mips3", NanLegacy)
  5694. .Case("mips4", NanLegacy)
  5695. .Case("mips5", NanLegacy)
  5696. .Case("mips32", NanLegacy)
  5697. .Case("mips32r2", NanLegacy | Nan2008)
  5698. .Case("mips32r3", NanLegacy | Nan2008)
  5699. .Case("mips32r5", NanLegacy | Nan2008)
  5700. .Case("mips32r6", Nan2008)
  5701. .Case("mips64", NanLegacy)
  5702. .Case("mips64r2", NanLegacy | Nan2008)
  5703. .Case("mips64r3", NanLegacy | Nan2008)
  5704. .Case("mips64r5", NanLegacy | Nan2008)
  5705. .Case("mips64r6", Nan2008)
  5706. .Default(NanLegacy);
  5707. }
  5708. bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
  5709. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  5710. return A && (A->getValue() == StringRef(Value));
  5711. }
  5712. bool mips::isUCLibc(const ArgList &Args) {
  5713. Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
  5714. return A && A->getOption().matches(options::OPT_muclibc);
  5715. }
  5716. bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
  5717. if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
  5718. return llvm::StringSwitch<bool>(NaNArg->getValue())
  5719. .Case("2008", true)
  5720. .Case("legacy", false)
  5721. .Default(false);
  5722. // NaN2008 is the default for MIPS32r6/MIPS64r6.
  5723. return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
  5724. .Cases("mips32r6", "mips64r6", true)
  5725. .Default(false);
  5726. return false;
  5727. }
  5728. bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
  5729. StringRef ABIName, mips::FloatABI FloatABI) {
  5730. if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
  5731. Triple.getVendor() != llvm::Triple::MipsTechnologies)
  5732. return false;
  5733. if (ABIName != "32")
  5734. return false;
  5735. // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
  5736. // present.
  5737. if (FloatABI == mips::FloatABI::Soft)
  5738. return false;
  5739. return llvm::StringSwitch<bool>(CPUName)
  5740. .Cases("mips2", "mips3", "mips4", "mips5", true)
  5741. .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
  5742. .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
  5743. .Default(false);
  5744. }
  5745. bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
  5746. StringRef CPUName, StringRef ABIName,
  5747. mips::FloatABI FloatABI) {
  5748. bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
  5749. // FPXX shouldn't be used if -msingle-float is present.
  5750. if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
  5751. options::OPT_mdouble_float))
  5752. if (A->getOption().matches(options::OPT_msingle_float))
  5753. UseFPXX = false;
  5754. return UseFPXX;
  5755. }
  5756. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  5757. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  5758. // archs which Darwin doesn't use.
  5759. // The matching this routine does is fairly pointless, since it is neither the
  5760. // complete architecture list, nor a reasonable subset. The problem is that
  5761. // historically the driver driver accepts this and also ties its -march=
  5762. // handling to the architecture name, so we need to be careful before removing
  5763. // support for it.
  5764. // This code must be kept in sync with Clang's Darwin specific argument
  5765. // translation.
  5766. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  5767. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  5768. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  5769. .Case("ppc64", llvm::Triple::ppc64)
  5770. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  5771. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  5772. llvm::Triple::x86)
  5773. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  5774. // This is derived from the driver driver.
  5775. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  5776. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  5777. .Cases("armv7s", "xscale", llvm::Triple::arm)
  5778. .Case("arm64", llvm::Triple::aarch64)
  5779. .Case("r600", llvm::Triple::r600)
  5780. .Case("amdgcn", llvm::Triple::amdgcn)
  5781. .Case("nvptx", llvm::Triple::nvptx)
  5782. .Case("nvptx64", llvm::Triple::nvptx64)
  5783. .Case("amdil", llvm::Triple::amdil)
  5784. .Case("spir", llvm::Triple::spir)
  5785. .Default(llvm::Triple::UnknownArch);
  5786. }
  5787. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  5788. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  5789. T.setArch(Arch);
  5790. if (Str == "x86_64h")
  5791. T.setArchName(Str);
  5792. else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
  5793. T.setOS(llvm::Triple::UnknownOS);
  5794. T.setObjectFormat(llvm::Triple::MachO);
  5795. }
  5796. }
  5797. const char *Clang::getBaseInputName(const ArgList &Args,
  5798. const InputInfo &Input) {
  5799. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  5800. }
  5801. const char *Clang::getBaseInputStem(const ArgList &Args,
  5802. const InputInfoList &Inputs) {
  5803. const char *Str = getBaseInputName(Args, Inputs[0]);
  5804. if (const char *End = strrchr(Str, '.'))
  5805. return Args.MakeArgString(std::string(Str, End));
  5806. return Str;
  5807. }
  5808. const char *Clang::getDependencyFileName(const ArgList &Args,
  5809. const InputInfoList &Inputs) {
  5810. // FIXME: Think about this more.
  5811. std::string Res;
  5812. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  5813. std::string Str(OutputOpt->getValue());
  5814. Res = Str.substr(0, Str.rfind('.'));
  5815. } else {
  5816. Res = getBaseInputStem(Args, Inputs);
  5817. }
  5818. return Args.MakeArgString(Res + ".d");
  5819. }
  5820. void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5821. const InputInfo &Output,
  5822. const InputInfoList &Inputs,
  5823. const ArgList &Args,
  5824. const char *LinkingOutput) const {
  5825. const ToolChain &ToolChain = getToolChain();
  5826. const Driver &D = ToolChain.getDriver();
  5827. ArgStringList CmdArgs;
  5828. // Silence warning for "clang -g foo.o -o foo"
  5829. Args.ClaimAllArgs(options::OPT_g_Group);
  5830. // and "clang -emit-llvm foo.o -o foo"
  5831. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5832. // and for "clang -w foo.o -o foo". Other warning options are already
  5833. // handled somewhere else.
  5834. Args.ClaimAllArgs(options::OPT_w);
  5835. if (!D.SysRoot.empty())
  5836. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  5837. // CloudABI only supports static linkage.
  5838. CmdArgs.push_back("-Bstatic");
  5839. CmdArgs.push_back("--eh-frame-hdr");
  5840. CmdArgs.push_back("--gc-sections");
  5841. if (Output.isFilename()) {
  5842. CmdArgs.push_back("-o");
  5843. CmdArgs.push_back(Output.getFilename());
  5844. } else {
  5845. assert(Output.isNothing() && "Invalid output.");
  5846. }
  5847. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  5848. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  5849. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
  5850. }
  5851. Args.AddAllArgs(CmdArgs, options::OPT_L);
  5852. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  5853. Args.AddAllArgs(CmdArgs,
  5854. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  5855. options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
  5856. if (D.isUsingLTO())
  5857. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  5858. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  5859. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  5860. if (D.CCCIsCXX())
  5861. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  5862. CmdArgs.push_back("-lc");
  5863. CmdArgs.push_back("-lcompiler_rt");
  5864. }
  5865. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  5866. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  5867. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  5868. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5869. }
  5870. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5871. const InputInfo &Output,
  5872. const InputInfoList &Inputs,
  5873. const ArgList &Args,
  5874. const char *LinkingOutput) const {
  5875. ArgStringList CmdArgs;
  5876. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5877. const InputInfo &Input = Inputs[0];
  5878. // Determine the original source input.
  5879. const Action *SourceAction = &JA;
  5880. while (SourceAction->getKind() != Action::InputClass) {
  5881. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5882. SourceAction = SourceAction->getInputs()[0];
  5883. }
  5884. // If -fno-integrated-as is used add -Q to the darwin assember driver to make
  5885. // sure it runs its system assembler not clang's integrated assembler.
  5886. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  5887. // FIXME: at run-time detect assembler capabilities or rely on version
  5888. // information forwarded by -target-assembler-version.
  5889. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  5890. const llvm::Triple &T(getToolChain().getTriple());
  5891. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  5892. CmdArgs.push_back("-Q");
  5893. }
  5894. // Forward -g, assuming we are dealing with an actual assembly file.
  5895. if (SourceAction->getType() == types::TY_Asm ||
  5896. SourceAction->getType() == types::TY_PP_Asm) {
  5897. if (Args.hasArg(options::OPT_gstabs))
  5898. CmdArgs.push_back("--gstabs");
  5899. else if (Args.hasArg(options::OPT_g_Group))
  5900. CmdArgs.push_back("-g");
  5901. }
  5902. // Derived from asm spec.
  5903. AddMachOArch(Args, CmdArgs);
  5904. // Use -force_cpusubtype_ALL on x86 by default.
  5905. if (getToolChain().getArch() == llvm::Triple::x86 ||
  5906. getToolChain().getArch() == llvm::Triple::x86_64 ||
  5907. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  5908. CmdArgs.push_back("-force_cpusubtype_ALL");
  5909. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  5910. (((Args.hasArg(options::OPT_mkernel) ||
  5911. Args.hasArg(options::OPT_fapple_kext)) &&
  5912. getMachOToolChain().isKernelStatic()) ||
  5913. Args.hasArg(options::OPT_static)))
  5914. CmdArgs.push_back("-static");
  5915. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5916. assert(Output.isFilename() && "Unexpected lipo output.");
  5917. CmdArgs.push_back("-o");
  5918. CmdArgs.push_back(Output.getFilename());
  5919. assert(Input.isFilename() && "Invalid input.");
  5920. CmdArgs.push_back(Input.getFilename());
  5921. // asm_final spec is empty.
  5922. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  5923. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5924. }
  5925. void darwin::MachOTool::anchor() {}
  5926. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  5927. ArgStringList &CmdArgs) const {
  5928. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  5929. // Derived from darwin_arch spec.
  5930. CmdArgs.push_back("-arch");
  5931. CmdArgs.push_back(Args.MakeArgString(ArchName));
  5932. // FIXME: Is this needed anymore?
  5933. if (ArchName == "arm")
  5934. CmdArgs.push_back("-force_cpusubtype_ALL");
  5935. }
  5936. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  5937. // We only need to generate a temp path for LTO if we aren't compiling object
  5938. // files. When compiling source files, we run 'dsymutil' after linking. We
  5939. // don't run 'dsymutil' when compiling object files.
  5940. for (const auto &Input : Inputs)
  5941. if (Input.getType() != types::TY_Object)
  5942. return true;
  5943. return false;
  5944. }
  5945. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  5946. ArgStringList &CmdArgs,
  5947. const InputInfoList &Inputs) const {
  5948. const Driver &D = getToolChain().getDriver();
  5949. const toolchains::MachO &MachOTC = getMachOToolChain();
  5950. unsigned Version[3] = {0, 0, 0};
  5951. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  5952. bool HadExtra;
  5953. if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
  5954. Version[2], HadExtra) ||
  5955. HadExtra)
  5956. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  5957. }
  5958. // Newer linkers support -demangle. Pass it if supported and not disabled by
  5959. // the user.
  5960. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  5961. CmdArgs.push_back("-demangle");
  5962. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  5963. CmdArgs.push_back("-export_dynamic");
  5964. // If we are using App Extension restrictions, pass a flag to the linker
  5965. // telling it that the compiled code has been audited.
  5966. if (Args.hasFlag(options::OPT_fapplication_extension,
  5967. options::OPT_fno_application_extension, false))
  5968. CmdArgs.push_back("-application_extension");
  5969. if (D.isUsingLTO()) {
  5970. // If we are using LTO, then automatically create a temporary file path for
  5971. // the linker to use, so that it's lifetime will extend past a possible
  5972. // dsymutil step.
  5973. if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
  5974. const char *TmpPath = C.getArgs().MakeArgString(
  5975. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
  5976. C.addTempFile(TmpPath);
  5977. CmdArgs.push_back("-object_path_lto");
  5978. CmdArgs.push_back(TmpPath);
  5979. }
  5980. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  5981. // it in clang installed libraries. If not found, the option is not used
  5982. // and 'ld' will use its default mechanism to search for libLTO.dylib.
  5983. if (Version[0] >= 133) {
  5984. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  5985. StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
  5986. SmallString<128> LibLTOPath(P);
  5987. llvm::sys::path::append(LibLTOPath, "lib");
  5988. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  5989. if (llvm::sys::fs::exists(LibLTOPath)) {
  5990. CmdArgs.push_back("-lto_library");
  5991. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  5992. } else {
  5993. D.Diag(diag::warn_drv_lto_libpath);
  5994. }
  5995. }
  5996. }
  5997. // Derived from the "link" spec.
  5998. Args.AddAllArgs(CmdArgs, options::OPT_static);
  5999. if (!Args.hasArg(options::OPT_static))
  6000. CmdArgs.push_back("-dynamic");
  6001. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  6002. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  6003. // here. How do we wish to handle such things?
  6004. }
  6005. if (!Args.hasArg(options::OPT_dynamiclib)) {
  6006. AddMachOArch(Args, CmdArgs);
  6007. // FIXME: Why do this only on this path?
  6008. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  6009. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  6010. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  6011. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  6012. Arg *A;
  6013. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  6014. (A = Args.getLastArg(options::OPT_current__version)) ||
  6015. (A = Args.getLastArg(options::OPT_install__name)))
  6016. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  6017. << "-dynamiclib";
  6018. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  6019. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  6020. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  6021. } else {
  6022. CmdArgs.push_back("-dylib");
  6023. Arg *A;
  6024. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  6025. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  6026. (A = Args.getLastArg(options::OPT_client__name)) ||
  6027. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  6028. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  6029. (A = Args.getLastArg(options::OPT_private__bundle)))
  6030. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  6031. << "-dynamiclib";
  6032. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  6033. "-dylib_compatibility_version");
  6034. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  6035. "-dylib_current_version");
  6036. AddMachOArch(Args, CmdArgs);
  6037. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  6038. "-dylib_install_name");
  6039. }
  6040. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  6041. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  6042. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  6043. if (MachOTC.isTargetIOSBased())
  6044. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  6045. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  6046. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  6047. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  6048. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  6049. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  6050. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  6051. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  6052. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  6053. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  6054. Args.AddAllArgs(CmdArgs, options::OPT_init);
  6055. // Add the deployment target.
  6056. MachOTC.addMinVersionArgs(Args, CmdArgs);
  6057. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  6058. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  6059. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  6060. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  6061. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  6062. if (const Arg *A =
  6063. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  6064. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  6065. if (A->getOption().matches(options::OPT_fpie) ||
  6066. A->getOption().matches(options::OPT_fPIE))
  6067. CmdArgs.push_back("-pie");
  6068. else
  6069. CmdArgs.push_back("-no_pie");
  6070. }
  6071. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  6072. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  6073. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  6074. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  6075. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  6076. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  6077. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  6078. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  6079. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  6080. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  6081. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  6082. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  6083. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  6084. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  6085. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  6086. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  6087. // Give --sysroot= preference, over the Apple specific behavior to also use
  6088. // --isysroot as the syslibroot.
  6089. StringRef sysroot = C.getSysRoot();
  6090. if (sysroot != "") {
  6091. CmdArgs.push_back("-syslibroot");
  6092. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  6093. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  6094. CmdArgs.push_back("-syslibroot");
  6095. CmdArgs.push_back(A->getValue());
  6096. }
  6097. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  6098. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  6099. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  6100. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  6101. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  6102. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  6103. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  6104. Args.AddAllArgs(CmdArgs, options::OPT_y);
  6105. Args.AddLastArg(CmdArgs, options::OPT_w);
  6106. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  6107. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  6108. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  6109. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  6110. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  6111. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  6112. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  6113. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  6114. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  6115. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  6116. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  6117. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  6118. }
  6119. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6120. const InputInfo &Output,
  6121. const InputInfoList &Inputs,
  6122. const ArgList &Args,
  6123. const char *LinkingOutput) const {
  6124. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  6125. // If the number of arguments surpasses the system limits, we will encode the
  6126. // input files in a separate file, shortening the command line. To this end,
  6127. // build a list of input file names that can be passed via a file with the
  6128. // -filelist linker option.
  6129. llvm::opt::ArgStringList InputFileList;
  6130. // The logic here is derived from gcc's behavior; most of which
  6131. // comes from specs (starting with link_command). Consult gcc for
  6132. // more information.
  6133. ArgStringList CmdArgs;
  6134. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  6135. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  6136. options::OPT_ccc_arcmt_migrate)) {
  6137. for (const auto &Arg : Args)
  6138. Arg->claim();
  6139. const char *Exec =
  6140. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  6141. CmdArgs.push_back(Output.getFilename());
  6142. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  6143. return;
  6144. }
  6145. // I'm not sure why this particular decomposition exists in gcc, but
  6146. // we follow suite for ease of comparison.
  6147. AddLinkArgs(C, Args, CmdArgs, Inputs);
  6148. // It seems that the 'e' option is completely ignored for dynamic executables
  6149. // (the default), and with static executables, the last one wins, as expected.
  6150. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  6151. options::OPT_Z_Flag, options::OPT_u_Group,
  6152. options::OPT_e, options::OPT_r});
  6153. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  6154. // members of static archive libraries which implement Objective-C classes or
  6155. // categories.
  6156. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  6157. CmdArgs.push_back("-ObjC");
  6158. CmdArgs.push_back("-o");
  6159. CmdArgs.push_back(Output.getFilename());
  6160. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6161. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  6162. // SafeStack requires its own runtime libraries
  6163. // These libraries should be linked first, to make sure the
  6164. // __safestack_init constructor executes before everything else
  6165. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  6166. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
  6167. "libclang_rt.safestack_osx.a",
  6168. /*AlwaysLink=*/true);
  6169. }
  6170. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6171. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6172. // Build the input file for -filelist (list of linker input files) in case we
  6173. // need it later
  6174. for (const auto &II : Inputs) {
  6175. if (!II.isFilename()) {
  6176. // This is a linker input argument.
  6177. // We cannot mix input arguments and file names in a -filelist input, thus
  6178. // we prematurely stop our list (remaining files shall be passed as
  6179. // arguments).
  6180. if (InputFileList.size() > 0)
  6181. break;
  6182. continue;
  6183. }
  6184. InputFileList.push_back(II.getFilename());
  6185. }
  6186. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  6187. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  6188. if (isObjCRuntimeLinked(Args) &&
  6189. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6190. // We use arclite library for both ARC and subscripting support.
  6191. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  6192. CmdArgs.push_back("-framework");
  6193. CmdArgs.push_back("Foundation");
  6194. // Link libobj.
  6195. CmdArgs.push_back("-lobjc");
  6196. }
  6197. if (LinkingOutput) {
  6198. CmdArgs.push_back("-arch_multiple");
  6199. CmdArgs.push_back("-final_output");
  6200. CmdArgs.push_back(LinkingOutput);
  6201. }
  6202. if (Args.hasArg(options::OPT_fnested_functions))
  6203. CmdArgs.push_back("-allow_stack_execute");
  6204. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  6205. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6206. if (getToolChain().getDriver().CCCIsCXX())
  6207. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6208. // link_ssp spec is empty.
  6209. // Let the tool chain choose which runtime library to link.
  6210. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  6211. }
  6212. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6213. // endfile_spec is empty.
  6214. }
  6215. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6216. Args.AddAllArgs(CmdArgs, options::OPT_F);
  6217. // -iframework should be forwarded as -F.
  6218. for (const Arg *A : Args.filtered(options::OPT_iframework))
  6219. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  6220. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6221. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  6222. if (A->getValue() == StringRef("Accelerate")) {
  6223. CmdArgs.push_back("-framework");
  6224. CmdArgs.push_back("Accelerate");
  6225. }
  6226. }
  6227. }
  6228. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6229. std::unique_ptr<Command> Cmd =
  6230. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  6231. Cmd->setInputFileList(std::move(InputFileList));
  6232. C.addCommand(std::move(Cmd));
  6233. }
  6234. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  6235. const InputInfo &Output,
  6236. const InputInfoList &Inputs,
  6237. const ArgList &Args,
  6238. const char *LinkingOutput) const {
  6239. ArgStringList CmdArgs;
  6240. CmdArgs.push_back("-create");
  6241. assert(Output.isFilename() && "Unexpected lipo output.");
  6242. CmdArgs.push_back("-output");
  6243. CmdArgs.push_back(Output.getFilename());
  6244. for (const auto &II : Inputs) {
  6245. assert(II.isFilename() && "Unexpected lipo input.");
  6246. CmdArgs.push_back(II.getFilename());
  6247. }
  6248. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  6249. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6250. }
  6251. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  6252. const InputInfo &Output,
  6253. const InputInfoList &Inputs,
  6254. const ArgList &Args,
  6255. const char *LinkingOutput) const {
  6256. ArgStringList CmdArgs;
  6257. CmdArgs.push_back("-o");
  6258. CmdArgs.push_back(Output.getFilename());
  6259. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6260. const InputInfo &Input = Inputs[0];
  6261. assert(Input.isFilename() && "Unexpected dsymutil input.");
  6262. CmdArgs.push_back(Input.getFilename());
  6263. const char *Exec =
  6264. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  6265. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6266. }
  6267. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  6268. const InputInfo &Output,
  6269. const InputInfoList &Inputs,
  6270. const ArgList &Args,
  6271. const char *LinkingOutput) const {
  6272. ArgStringList CmdArgs;
  6273. CmdArgs.push_back("--verify");
  6274. CmdArgs.push_back("--debug-info");
  6275. CmdArgs.push_back("--eh-frame");
  6276. CmdArgs.push_back("--quiet");
  6277. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6278. const InputInfo &Input = Inputs[0];
  6279. assert(Input.isFilename() && "Unexpected verify input");
  6280. // Grabbing the output of the earlier dsymutil run.
  6281. CmdArgs.push_back(Input.getFilename());
  6282. const char *Exec =
  6283. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  6284. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6285. }
  6286. void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6287. const InputInfo &Output,
  6288. const InputInfoList &Inputs,
  6289. const ArgList &Args,
  6290. const char *LinkingOutput) const {
  6291. claimNoWarnArgs(Args);
  6292. ArgStringList CmdArgs;
  6293. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6294. CmdArgs.push_back("-o");
  6295. CmdArgs.push_back(Output.getFilename());
  6296. for (const auto &II : Inputs)
  6297. CmdArgs.push_back(II.getFilename());
  6298. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6299. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6300. }
  6301. void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6302. const InputInfo &Output,
  6303. const InputInfoList &Inputs,
  6304. const ArgList &Args,
  6305. const char *LinkingOutput) const {
  6306. ArgStringList CmdArgs;
  6307. // Demangle C++ names in errors
  6308. CmdArgs.push_back("-C");
  6309. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6310. CmdArgs.push_back("-e");
  6311. CmdArgs.push_back("_start");
  6312. }
  6313. if (Args.hasArg(options::OPT_static)) {
  6314. CmdArgs.push_back("-Bstatic");
  6315. CmdArgs.push_back("-dn");
  6316. } else {
  6317. CmdArgs.push_back("-Bdynamic");
  6318. if (Args.hasArg(options::OPT_shared)) {
  6319. CmdArgs.push_back("-shared");
  6320. } else {
  6321. CmdArgs.push_back("--dynamic-linker");
  6322. CmdArgs.push_back(
  6323. Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
  6324. }
  6325. }
  6326. if (Output.isFilename()) {
  6327. CmdArgs.push_back("-o");
  6328. CmdArgs.push_back(Output.getFilename());
  6329. } else {
  6330. assert(Output.isNothing() && "Invalid output.");
  6331. }
  6332. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6333. if (!Args.hasArg(options::OPT_shared))
  6334. CmdArgs.push_back(
  6335. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  6336. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6337. CmdArgs.push_back(
  6338. Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
  6339. CmdArgs.push_back(
  6340. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6341. }
  6342. getToolChain().AddFilePathLibArgs(Args, CmdArgs);
  6343. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6344. options::OPT_e, options::OPT_r});
  6345. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6346. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6347. if (getToolChain().getDriver().CCCIsCXX())
  6348. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6349. CmdArgs.push_back("-lgcc_s");
  6350. CmdArgs.push_back("-lc");
  6351. if (!Args.hasArg(options::OPT_shared)) {
  6352. CmdArgs.push_back("-lgcc");
  6353. CmdArgs.push_back("-lm");
  6354. }
  6355. }
  6356. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6357. CmdArgs.push_back(
  6358. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6359. }
  6360. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  6361. getToolChain().addProfileRTLibs(Args, CmdArgs);
  6362. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6363. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6364. }
  6365. void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6366. const InputInfo &Output,
  6367. const InputInfoList &Inputs,
  6368. const ArgList &Args,
  6369. const char *LinkingOutput) const {
  6370. claimNoWarnArgs(Args);
  6371. ArgStringList CmdArgs;
  6372. switch (getToolChain().getArch()) {
  6373. case llvm::Triple::x86:
  6374. // When building 32-bit code on OpenBSD/amd64, we have to explicitly
  6375. // instruct as in the base system to assemble 32-bit code.
  6376. CmdArgs.push_back("--32");
  6377. break;
  6378. case llvm::Triple::ppc:
  6379. CmdArgs.push_back("-mppc");
  6380. CmdArgs.push_back("-many");
  6381. break;
  6382. case llvm::Triple::sparc:
  6383. case llvm::Triple::sparcel: {
  6384. CmdArgs.push_back("-32");
  6385. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6386. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6387. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6388. break;
  6389. }
  6390. case llvm::Triple::sparcv9: {
  6391. CmdArgs.push_back("-64");
  6392. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6393. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6394. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6395. break;
  6396. }
  6397. case llvm::Triple::mips64:
  6398. case llvm::Triple::mips64el: {
  6399. StringRef CPUName;
  6400. StringRef ABIName;
  6401. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6402. CmdArgs.push_back("-mabi");
  6403. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6404. if (getToolChain().getArch() == llvm::Triple::mips64)
  6405. CmdArgs.push_back("-EB");
  6406. else
  6407. CmdArgs.push_back("-EL");
  6408. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6409. break;
  6410. }
  6411. default:
  6412. break;
  6413. }
  6414. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6415. CmdArgs.push_back("-o");
  6416. CmdArgs.push_back(Output.getFilename());
  6417. for (const auto &II : Inputs)
  6418. CmdArgs.push_back(II.getFilename());
  6419. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6420. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6421. }
  6422. void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6423. const InputInfo &Output,
  6424. const InputInfoList &Inputs,
  6425. const ArgList &Args,
  6426. const char *LinkingOutput) const {
  6427. const Driver &D = getToolChain().getDriver();
  6428. ArgStringList CmdArgs;
  6429. // Silence warning for "clang -g foo.o -o foo"
  6430. Args.ClaimAllArgs(options::OPT_g_Group);
  6431. // and "clang -emit-llvm foo.o -o foo"
  6432. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6433. // and for "clang -w foo.o -o foo". Other warning options are already
  6434. // handled somewhere else.
  6435. Args.ClaimAllArgs(options::OPT_w);
  6436. if (getToolChain().getArch() == llvm::Triple::mips64)
  6437. CmdArgs.push_back("-EB");
  6438. else if (getToolChain().getArch() == llvm::Triple::mips64el)
  6439. CmdArgs.push_back("-EL");
  6440. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6441. CmdArgs.push_back("-e");
  6442. CmdArgs.push_back("__start");
  6443. }
  6444. if (Args.hasArg(options::OPT_static)) {
  6445. CmdArgs.push_back("-Bstatic");
  6446. } else {
  6447. if (Args.hasArg(options::OPT_rdynamic))
  6448. CmdArgs.push_back("-export-dynamic");
  6449. CmdArgs.push_back("--eh-frame-hdr");
  6450. CmdArgs.push_back("-Bdynamic");
  6451. if (Args.hasArg(options::OPT_shared)) {
  6452. CmdArgs.push_back("-shared");
  6453. } else {
  6454. CmdArgs.push_back("-dynamic-linker");
  6455. CmdArgs.push_back("/usr/libexec/ld.so");
  6456. }
  6457. }
  6458. if (Args.hasArg(options::OPT_nopie))
  6459. CmdArgs.push_back("-nopie");
  6460. if (Output.isFilename()) {
  6461. CmdArgs.push_back("-o");
  6462. CmdArgs.push_back(Output.getFilename());
  6463. } else {
  6464. assert(Output.isNothing() && "Invalid output.");
  6465. }
  6466. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6467. if (!Args.hasArg(options::OPT_shared)) {
  6468. if (Args.hasArg(options::OPT_pg))
  6469. CmdArgs.push_back(
  6470. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6471. else
  6472. CmdArgs.push_back(
  6473. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6474. CmdArgs.push_back(
  6475. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6476. } else {
  6477. CmdArgs.push_back(
  6478. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6479. }
  6480. }
  6481. std::string Triple = getToolChain().getTripleString();
  6482. if (Triple.substr(0, 6) == "x86_64")
  6483. Triple.replace(0, 6, "amd64");
  6484. CmdArgs.push_back(
  6485. Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
  6486. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6487. options::OPT_e, options::OPT_s, options::OPT_t,
  6488. options::OPT_Z_Flag, options::OPT_r});
  6489. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6490. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6491. if (D.CCCIsCXX()) {
  6492. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6493. if (Args.hasArg(options::OPT_pg))
  6494. CmdArgs.push_back("-lm_p");
  6495. else
  6496. CmdArgs.push_back("-lm");
  6497. }
  6498. // FIXME: For some reason GCC passes -lgcc before adding
  6499. // the default system libraries. Just mimic this for now.
  6500. CmdArgs.push_back("-lgcc");
  6501. if (Args.hasArg(options::OPT_pthread)) {
  6502. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6503. CmdArgs.push_back("-lpthread_p");
  6504. else
  6505. CmdArgs.push_back("-lpthread");
  6506. }
  6507. if (!Args.hasArg(options::OPT_shared)) {
  6508. if (Args.hasArg(options::OPT_pg))
  6509. CmdArgs.push_back("-lc_p");
  6510. else
  6511. CmdArgs.push_back("-lc");
  6512. }
  6513. CmdArgs.push_back("-lgcc");
  6514. }
  6515. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6516. if (!Args.hasArg(options::OPT_shared))
  6517. CmdArgs.push_back(
  6518. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6519. else
  6520. CmdArgs.push_back(
  6521. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6522. }
  6523. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6524. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6525. }
  6526. void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6527. const InputInfo &Output,
  6528. const InputInfoList &Inputs,
  6529. const ArgList &Args,
  6530. const char *LinkingOutput) const {
  6531. claimNoWarnArgs(Args);
  6532. ArgStringList CmdArgs;
  6533. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6534. CmdArgs.push_back("-o");
  6535. CmdArgs.push_back(Output.getFilename());
  6536. for (const auto &II : Inputs)
  6537. CmdArgs.push_back(II.getFilename());
  6538. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6539. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6540. }
  6541. void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6542. const InputInfo &Output,
  6543. const InputInfoList &Inputs,
  6544. const ArgList &Args,
  6545. const char *LinkingOutput) const {
  6546. const Driver &D = getToolChain().getDriver();
  6547. ArgStringList CmdArgs;
  6548. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6549. CmdArgs.push_back("-e");
  6550. CmdArgs.push_back("__start");
  6551. }
  6552. if (Args.hasArg(options::OPT_static)) {
  6553. CmdArgs.push_back("-Bstatic");
  6554. } else {
  6555. if (Args.hasArg(options::OPT_rdynamic))
  6556. CmdArgs.push_back("-export-dynamic");
  6557. CmdArgs.push_back("--eh-frame-hdr");
  6558. CmdArgs.push_back("-Bdynamic");
  6559. if (Args.hasArg(options::OPT_shared)) {
  6560. CmdArgs.push_back("-shared");
  6561. } else {
  6562. CmdArgs.push_back("-dynamic-linker");
  6563. CmdArgs.push_back("/usr/libexec/ld.so");
  6564. }
  6565. }
  6566. if (Output.isFilename()) {
  6567. CmdArgs.push_back("-o");
  6568. CmdArgs.push_back(Output.getFilename());
  6569. } else {
  6570. assert(Output.isNothing() && "Invalid output.");
  6571. }
  6572. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6573. if (!Args.hasArg(options::OPT_shared)) {
  6574. if (Args.hasArg(options::OPT_pg))
  6575. CmdArgs.push_back(
  6576. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6577. else
  6578. CmdArgs.push_back(
  6579. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6580. CmdArgs.push_back(
  6581. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6582. } else {
  6583. CmdArgs.push_back(
  6584. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6585. }
  6586. }
  6587. Args.AddAllArgs(CmdArgs,
  6588. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  6589. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6590. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6591. if (D.CCCIsCXX()) {
  6592. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6593. if (Args.hasArg(options::OPT_pg))
  6594. CmdArgs.push_back("-lm_p");
  6595. else
  6596. CmdArgs.push_back("-lm");
  6597. }
  6598. if (Args.hasArg(options::OPT_pthread)) {
  6599. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6600. CmdArgs.push_back("-lpthread_p");
  6601. else
  6602. CmdArgs.push_back("-lpthread");
  6603. }
  6604. if (!Args.hasArg(options::OPT_shared)) {
  6605. if (Args.hasArg(options::OPT_pg))
  6606. CmdArgs.push_back("-lc_p");
  6607. else
  6608. CmdArgs.push_back("-lc");
  6609. }
  6610. StringRef MyArch;
  6611. switch (getToolChain().getArch()) {
  6612. case llvm::Triple::arm:
  6613. MyArch = "arm";
  6614. break;
  6615. case llvm::Triple::x86:
  6616. MyArch = "i386";
  6617. break;
  6618. case llvm::Triple::x86_64:
  6619. MyArch = "amd64";
  6620. break;
  6621. default:
  6622. llvm_unreachable("Unsupported architecture");
  6623. }
  6624. CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
  6625. }
  6626. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6627. if (!Args.hasArg(options::OPT_shared))
  6628. CmdArgs.push_back(
  6629. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6630. else
  6631. CmdArgs.push_back(
  6632. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6633. }
  6634. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6635. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6636. }
  6637. void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6638. const InputInfo &Output,
  6639. const InputInfoList &Inputs,
  6640. const ArgList &Args,
  6641. const char *LinkingOutput) const {
  6642. claimNoWarnArgs(Args);
  6643. ArgStringList CmdArgs;
  6644. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  6645. // instruct as in the base system to assemble 32-bit code.
  6646. switch (getToolChain().getArch()) {
  6647. default:
  6648. break;
  6649. case llvm::Triple::x86:
  6650. CmdArgs.push_back("--32");
  6651. break;
  6652. case llvm::Triple::ppc:
  6653. CmdArgs.push_back("-a32");
  6654. break;
  6655. case llvm::Triple::mips:
  6656. case llvm::Triple::mipsel:
  6657. case llvm::Triple::mips64:
  6658. case llvm::Triple::mips64el: {
  6659. StringRef CPUName;
  6660. StringRef ABIName;
  6661. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6662. CmdArgs.push_back("-march");
  6663. CmdArgs.push_back(CPUName.data());
  6664. CmdArgs.push_back("-mabi");
  6665. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6666. if (getToolChain().getArch() == llvm::Triple::mips ||
  6667. getToolChain().getArch() == llvm::Triple::mips64)
  6668. CmdArgs.push_back("-EB");
  6669. else
  6670. CmdArgs.push_back("-EL");
  6671. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6672. break;
  6673. }
  6674. case llvm::Triple::arm:
  6675. case llvm::Triple::armeb:
  6676. case llvm::Triple::thumb:
  6677. case llvm::Triple::thumbeb: {
  6678. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  6679. if (ABI == arm::FloatABI::Hard)
  6680. CmdArgs.push_back("-mfpu=vfp");
  6681. else
  6682. CmdArgs.push_back("-mfpu=softvfp");
  6683. switch (getToolChain().getTriple().getEnvironment()) {
  6684. case llvm::Triple::GNUEABIHF:
  6685. case llvm::Triple::GNUEABI:
  6686. case llvm::Triple::EABI:
  6687. CmdArgs.push_back("-meabi=5");
  6688. break;
  6689. default:
  6690. CmdArgs.push_back("-matpcs");
  6691. }
  6692. break;
  6693. }
  6694. case llvm::Triple::sparc:
  6695. case llvm::Triple::sparcel:
  6696. case llvm::Triple::sparcv9: {
  6697. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6698. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6699. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6700. break;
  6701. }
  6702. }
  6703. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6704. CmdArgs.push_back("-o");
  6705. CmdArgs.push_back(Output.getFilename());
  6706. for (const auto &II : Inputs)
  6707. CmdArgs.push_back(II.getFilename());
  6708. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6709. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6710. }
  6711. void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6712. const InputInfo &Output,
  6713. const InputInfoList &Inputs,
  6714. const ArgList &Args,
  6715. const char *LinkingOutput) const {
  6716. const toolchains::FreeBSD &ToolChain =
  6717. static_cast<const toolchains::FreeBSD &>(getToolChain());
  6718. const Driver &D = ToolChain.getDriver();
  6719. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  6720. const bool IsPIE =
  6721. !Args.hasArg(options::OPT_shared) &&
  6722. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  6723. ArgStringList CmdArgs;
  6724. // Silence warning for "clang -g foo.o -o foo"
  6725. Args.ClaimAllArgs(options::OPT_g_Group);
  6726. // and "clang -emit-llvm foo.o -o foo"
  6727. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6728. // and for "clang -w foo.o -o foo". Other warning options are already
  6729. // handled somewhere else.
  6730. Args.ClaimAllArgs(options::OPT_w);
  6731. if (!D.SysRoot.empty())
  6732. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6733. if (IsPIE)
  6734. CmdArgs.push_back("-pie");
  6735. if (Args.hasArg(options::OPT_static)) {
  6736. CmdArgs.push_back("-Bstatic");
  6737. } else {
  6738. if (Args.hasArg(options::OPT_rdynamic))
  6739. CmdArgs.push_back("-export-dynamic");
  6740. CmdArgs.push_back("--eh-frame-hdr");
  6741. if (Args.hasArg(options::OPT_shared)) {
  6742. CmdArgs.push_back("-Bshareable");
  6743. } else {
  6744. CmdArgs.push_back("-dynamic-linker");
  6745. CmdArgs.push_back("/libexec/ld-elf.so.1");
  6746. }
  6747. if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
  6748. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
  6749. Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  6750. CmdArgs.push_back("--hash-style=both");
  6751. }
  6752. }
  6753. CmdArgs.push_back("--enable-new-dtags");
  6754. }
  6755. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  6756. // instruct ld in the base system to link 32-bit code.
  6757. if (Arch == llvm::Triple::x86) {
  6758. CmdArgs.push_back("-m");
  6759. CmdArgs.push_back("elf_i386_fbsd");
  6760. }
  6761. if (Arch == llvm::Triple::ppc) {
  6762. CmdArgs.push_back("-m");
  6763. CmdArgs.push_back("elf32ppc_fbsd");
  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. const char *crt1 = nullptr;
  6773. if (!Args.hasArg(options::OPT_shared)) {
  6774. if (Args.hasArg(options::OPT_pg))
  6775. crt1 = "gcrt1.o";
  6776. else if (IsPIE)
  6777. crt1 = "Scrt1.o";
  6778. else
  6779. crt1 = "crt1.o";
  6780. }
  6781. if (crt1)
  6782. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  6783. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  6784. const char *crtbegin = nullptr;
  6785. if (Args.hasArg(options::OPT_static))
  6786. crtbegin = "crtbeginT.o";
  6787. else if (Args.hasArg(options::OPT_shared) || IsPIE)
  6788. crtbegin = "crtbeginS.o";
  6789. else
  6790. crtbegin = "crtbegin.o";
  6791. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  6792. }
  6793. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6794. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6795. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6796. Args.AddAllArgs(CmdArgs, options::OPT_e);
  6797. Args.AddAllArgs(CmdArgs, options::OPT_s);
  6798. Args.AddAllArgs(CmdArgs, options::OPT_t);
  6799. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  6800. Args.AddAllArgs(CmdArgs, options::OPT_r);
  6801. if (D.isUsingLTO())
  6802. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  6803. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  6804. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6805. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6806. addOpenMPRuntime(CmdArgs, ToolChain, Args);
  6807. if (D.CCCIsCXX()) {
  6808. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6809. if (Args.hasArg(options::OPT_pg))
  6810. CmdArgs.push_back("-lm_p");
  6811. else
  6812. CmdArgs.push_back("-lm");
  6813. }
  6814. if (NeedsSanitizerDeps)
  6815. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  6816. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  6817. // the default system libraries. Just mimic this for now.
  6818. if (Args.hasArg(options::OPT_pg))
  6819. CmdArgs.push_back("-lgcc_p");
  6820. else
  6821. CmdArgs.push_back("-lgcc");
  6822. if (Args.hasArg(options::OPT_static)) {
  6823. CmdArgs.push_back("-lgcc_eh");
  6824. } else if (Args.hasArg(options::OPT_pg)) {
  6825. CmdArgs.push_back("-lgcc_eh_p");
  6826. } else {
  6827. CmdArgs.push_back("--as-needed");
  6828. CmdArgs.push_back("-lgcc_s");
  6829. CmdArgs.push_back("--no-as-needed");
  6830. }
  6831. if (Args.hasArg(options::OPT_pthread)) {
  6832. if (Args.hasArg(options::OPT_pg))
  6833. CmdArgs.push_back("-lpthread_p");
  6834. else
  6835. CmdArgs.push_back("-lpthread");
  6836. }
  6837. if (Args.hasArg(options::OPT_pg)) {
  6838. if (Args.hasArg(options::OPT_shared))
  6839. CmdArgs.push_back("-lc");
  6840. else
  6841. CmdArgs.push_back("-lc_p");
  6842. CmdArgs.push_back("-lgcc_p");
  6843. } else {
  6844. CmdArgs.push_back("-lc");
  6845. CmdArgs.push_back("-lgcc");
  6846. }
  6847. if (Args.hasArg(options::OPT_static)) {
  6848. CmdArgs.push_back("-lgcc_eh");
  6849. } else if (Args.hasArg(options::OPT_pg)) {
  6850. CmdArgs.push_back("-lgcc_eh_p");
  6851. } else {
  6852. CmdArgs.push_back("--as-needed");
  6853. CmdArgs.push_back("-lgcc_s");
  6854. CmdArgs.push_back("--no-as-needed");
  6855. }
  6856. }
  6857. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6858. if (Args.hasArg(options::OPT_shared) || IsPIE)
  6859. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  6860. else
  6861. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  6862. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  6863. }
  6864. ToolChain.addProfileRTLibs(Args, CmdArgs);
  6865. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6866. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6867. }
  6868. void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6869. const InputInfo &Output,
  6870. const InputInfoList &Inputs,
  6871. const ArgList &Args,
  6872. const char *LinkingOutput) const {
  6873. claimNoWarnArgs(Args);
  6874. ArgStringList CmdArgs;
  6875. // GNU as needs different flags for creating the correct output format
  6876. // on architectures with different ABIs or optional feature sets.
  6877. switch (getToolChain().getArch()) {
  6878. case llvm::Triple::x86:
  6879. CmdArgs.push_back("--32");
  6880. break;
  6881. case llvm::Triple::arm:
  6882. case llvm::Triple::armeb:
  6883. case llvm::Triple::thumb:
  6884. case llvm::Triple::thumbeb: {
  6885. StringRef MArch, MCPU;
  6886. getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
  6887. std::string Arch =
  6888. arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
  6889. CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
  6890. break;
  6891. }
  6892. case llvm::Triple::mips:
  6893. case llvm::Triple::mipsel:
  6894. case llvm::Triple::mips64:
  6895. case llvm::Triple::mips64el: {
  6896. StringRef CPUName;
  6897. StringRef ABIName;
  6898. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6899. CmdArgs.push_back("-march");
  6900. CmdArgs.push_back(CPUName.data());
  6901. CmdArgs.push_back("-mabi");
  6902. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6903. if (getToolChain().getArch() == llvm::Triple::mips ||
  6904. getToolChain().getArch() == llvm::Triple::mips64)
  6905. CmdArgs.push_back("-EB");
  6906. else
  6907. CmdArgs.push_back("-EL");
  6908. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6909. break;
  6910. }
  6911. case llvm::Triple::sparc:
  6912. case llvm::Triple::sparcel: {
  6913. CmdArgs.push_back("-32");
  6914. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6915. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6916. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6917. break;
  6918. }
  6919. case llvm::Triple::sparcv9: {
  6920. CmdArgs.push_back("-64");
  6921. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6922. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6923. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6924. break;
  6925. }
  6926. default:
  6927. break;
  6928. }
  6929. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6930. CmdArgs.push_back("-o");
  6931. CmdArgs.push_back(Output.getFilename());
  6932. for (const auto &II : Inputs)
  6933. CmdArgs.push_back(II.getFilename());
  6934. const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
  6935. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6936. }
  6937. void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6938. const InputInfo &Output,
  6939. const InputInfoList &Inputs,
  6940. const ArgList &Args,
  6941. const char *LinkingOutput) const {
  6942. const Driver &D = getToolChain().getDriver();
  6943. ArgStringList CmdArgs;
  6944. if (!D.SysRoot.empty())
  6945. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6946. CmdArgs.push_back("--eh-frame-hdr");
  6947. if (Args.hasArg(options::OPT_static)) {
  6948. CmdArgs.push_back("-Bstatic");
  6949. } else {
  6950. if (Args.hasArg(options::OPT_rdynamic))
  6951. CmdArgs.push_back("-export-dynamic");
  6952. if (Args.hasArg(options::OPT_shared)) {
  6953. CmdArgs.push_back("-Bshareable");
  6954. } else {
  6955. CmdArgs.push_back("-dynamic-linker");
  6956. CmdArgs.push_back("/libexec/ld.elf_so");
  6957. }
  6958. }
  6959. // Many NetBSD architectures support more than one ABI.
  6960. // Determine the correct emulation for ld.
  6961. switch (getToolChain().getArch()) {
  6962. case llvm::Triple::x86:
  6963. CmdArgs.push_back("-m");
  6964. CmdArgs.push_back("elf_i386");
  6965. break;
  6966. case llvm::Triple::arm:
  6967. case llvm::Triple::thumb:
  6968. CmdArgs.push_back("-m");
  6969. switch (getToolChain().getTriple().getEnvironment()) {
  6970. case llvm::Triple::EABI:
  6971. case llvm::Triple::GNUEABI:
  6972. CmdArgs.push_back("armelf_nbsd_eabi");
  6973. break;
  6974. case llvm::Triple::EABIHF:
  6975. case llvm::Triple::GNUEABIHF:
  6976. CmdArgs.push_back("armelf_nbsd_eabihf");
  6977. break;
  6978. default:
  6979. CmdArgs.push_back("armelf_nbsd");
  6980. break;
  6981. }
  6982. break;
  6983. case llvm::Triple::armeb:
  6984. case llvm::Triple::thumbeb:
  6985. arm::appendEBLinkFlags(
  6986. Args, CmdArgs,
  6987. llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
  6988. CmdArgs.push_back("-m");
  6989. switch (getToolChain().getTriple().getEnvironment()) {
  6990. case llvm::Triple::EABI:
  6991. case llvm::Triple::GNUEABI:
  6992. CmdArgs.push_back("armelfb_nbsd_eabi");
  6993. break;
  6994. case llvm::Triple::EABIHF:
  6995. case llvm::Triple::GNUEABIHF:
  6996. CmdArgs.push_back("armelfb_nbsd_eabihf");
  6997. break;
  6998. default:
  6999. CmdArgs.push_back("armelfb_nbsd");
  7000. break;
  7001. }
  7002. break;
  7003. case llvm::Triple::mips64:
  7004. case llvm::Triple::mips64el:
  7005. if (mips::hasMipsAbiArg(Args, "32")) {
  7006. CmdArgs.push_back("-m");
  7007. if (getToolChain().getArch() == llvm::Triple::mips64)
  7008. CmdArgs.push_back("elf32btsmip");
  7009. else
  7010. CmdArgs.push_back("elf32ltsmip");
  7011. } else if (mips::hasMipsAbiArg(Args, "64")) {
  7012. CmdArgs.push_back("-m");
  7013. if (getToolChain().getArch() == llvm::Triple::mips64)
  7014. CmdArgs.push_back("elf64btsmip");
  7015. else
  7016. CmdArgs.push_back("elf64ltsmip");
  7017. }
  7018. break;
  7019. case llvm::Triple::ppc:
  7020. CmdArgs.push_back("-m");
  7021. CmdArgs.push_back("elf32ppc_nbsd");
  7022. break;
  7023. case llvm::Triple::ppc64:
  7024. case llvm::Triple::ppc64le:
  7025. CmdArgs.push_back("-m");
  7026. CmdArgs.push_back("elf64ppc");
  7027. break;
  7028. case llvm::Triple::sparc:
  7029. CmdArgs.push_back("-m");
  7030. CmdArgs.push_back("elf32_sparc");
  7031. break;
  7032. case llvm::Triple::sparcv9:
  7033. CmdArgs.push_back("-m");
  7034. CmdArgs.push_back("elf64_sparc");
  7035. break;
  7036. default:
  7037. break;
  7038. }
  7039. if (Output.isFilename()) {
  7040. CmdArgs.push_back("-o");
  7041. CmdArgs.push_back(Output.getFilename());
  7042. } else {
  7043. assert(Output.isNothing() && "Invalid output.");
  7044. }
  7045. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7046. if (!Args.hasArg(options::OPT_shared)) {
  7047. CmdArgs.push_back(
  7048. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7049. CmdArgs.push_back(
  7050. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7051. CmdArgs.push_back(
  7052. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7053. } else {
  7054. CmdArgs.push_back(
  7055. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7056. CmdArgs.push_back(
  7057. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7058. }
  7059. }
  7060. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7061. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7062. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7063. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7064. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7065. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7066. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7067. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7068. unsigned Major, Minor, Micro;
  7069. getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
  7070. bool useLibgcc = true;
  7071. if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
  7072. switch (getToolChain().getArch()) {
  7073. case llvm::Triple::aarch64:
  7074. case llvm::Triple::arm:
  7075. case llvm::Triple::armeb:
  7076. case llvm::Triple::thumb:
  7077. case llvm::Triple::thumbeb:
  7078. case llvm::Triple::ppc:
  7079. case llvm::Triple::ppc64:
  7080. case llvm::Triple::ppc64le:
  7081. case llvm::Triple::x86:
  7082. case llvm::Triple::x86_64:
  7083. useLibgcc = false;
  7084. break;
  7085. default:
  7086. break;
  7087. }
  7088. }
  7089. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7090. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  7091. if (D.CCCIsCXX()) {
  7092. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7093. CmdArgs.push_back("-lm");
  7094. }
  7095. if (Args.hasArg(options::OPT_pthread))
  7096. CmdArgs.push_back("-lpthread");
  7097. CmdArgs.push_back("-lc");
  7098. if (useLibgcc) {
  7099. if (Args.hasArg(options::OPT_static)) {
  7100. // libgcc_eh depends on libc, so resolve as much as possible,
  7101. // pull in any new requirements from libc and then get the rest
  7102. // of libgcc.
  7103. CmdArgs.push_back("-lgcc_eh");
  7104. CmdArgs.push_back("-lc");
  7105. CmdArgs.push_back("-lgcc");
  7106. } else {
  7107. CmdArgs.push_back("-lgcc");
  7108. CmdArgs.push_back("--as-needed");
  7109. CmdArgs.push_back("-lgcc_s");
  7110. CmdArgs.push_back("--no-as-needed");
  7111. }
  7112. }
  7113. }
  7114. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7115. if (!Args.hasArg(options::OPT_shared))
  7116. CmdArgs.push_back(
  7117. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7118. else
  7119. CmdArgs.push_back(
  7120. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7121. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7122. }
  7123. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7124. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7125. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7126. }
  7127. void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7128. const InputInfo &Output,
  7129. const InputInfoList &Inputs,
  7130. const ArgList &Args,
  7131. const char *LinkingOutput) const {
  7132. claimNoWarnArgs(Args);
  7133. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7134. llvm::Triple Triple = llvm::Triple(TripleStr);
  7135. ArgStringList CmdArgs;
  7136. llvm::Reloc::Model RelocationModel;
  7137. unsigned PICLevel;
  7138. bool IsPIE;
  7139. std::tie(RelocationModel, PICLevel, IsPIE) =
  7140. ParsePICArgs(getToolChain(), Triple, Args);
  7141. switch (getToolChain().getArch()) {
  7142. default:
  7143. break;
  7144. // Add --32/--64 to make sure we get the format we want.
  7145. // This is incomplete
  7146. case llvm::Triple::x86:
  7147. CmdArgs.push_back("--32");
  7148. break;
  7149. case llvm::Triple::x86_64:
  7150. if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7151. CmdArgs.push_back("--x32");
  7152. else
  7153. CmdArgs.push_back("--64");
  7154. break;
  7155. case llvm::Triple::ppc:
  7156. CmdArgs.push_back("-a32");
  7157. CmdArgs.push_back("-mppc");
  7158. CmdArgs.push_back("-many");
  7159. break;
  7160. case llvm::Triple::ppc64:
  7161. CmdArgs.push_back("-a64");
  7162. CmdArgs.push_back("-mppc64");
  7163. CmdArgs.push_back("-many");
  7164. break;
  7165. case llvm::Triple::ppc64le:
  7166. CmdArgs.push_back("-a64");
  7167. CmdArgs.push_back("-mppc64");
  7168. CmdArgs.push_back("-many");
  7169. CmdArgs.push_back("-mlittle-endian");
  7170. break;
  7171. case llvm::Triple::sparc:
  7172. case llvm::Triple::sparcel: {
  7173. CmdArgs.push_back("-32");
  7174. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7175. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7176. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7177. break;
  7178. }
  7179. case llvm::Triple::sparcv9: {
  7180. CmdArgs.push_back("-64");
  7181. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7182. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7183. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7184. break;
  7185. }
  7186. case llvm::Triple::arm:
  7187. case llvm::Triple::armeb:
  7188. case llvm::Triple::thumb:
  7189. case llvm::Triple::thumbeb: {
  7190. const llvm::Triple &Triple2 = getToolChain().getTriple();
  7191. switch (Triple2.getSubArch()) {
  7192. case llvm::Triple::ARMSubArch_v7:
  7193. CmdArgs.push_back("-mfpu=neon");
  7194. break;
  7195. case llvm::Triple::ARMSubArch_v8:
  7196. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  7197. break;
  7198. default:
  7199. break;
  7200. }
  7201. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  7202. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  7203. case arm::FloatABI::Soft:
  7204. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  7205. break;
  7206. case arm::FloatABI::SoftFP:
  7207. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  7208. break;
  7209. case arm::FloatABI::Hard:
  7210. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  7211. break;
  7212. }
  7213. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  7214. // FIXME: remove krait check when GNU tools support krait cpu
  7215. // for now replace it with -march=armv7-a to avoid a lower
  7216. // march from being picked in the absence of a cpu flag.
  7217. Arg *A;
  7218. if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
  7219. StringRef(A->getValue()).lower() == "krait")
  7220. CmdArgs.push_back("-march=armv7-a");
  7221. else
  7222. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  7223. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  7224. break;
  7225. }
  7226. case llvm::Triple::mips:
  7227. case llvm::Triple::mipsel:
  7228. case llvm::Triple::mips64:
  7229. case llvm::Triple::mips64el: {
  7230. StringRef CPUName;
  7231. StringRef ABIName;
  7232. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7233. ABIName = getGnuCompatibleMipsABIName(ABIName);
  7234. CmdArgs.push_back("-march");
  7235. CmdArgs.push_back(CPUName.data());
  7236. CmdArgs.push_back("-mabi");
  7237. CmdArgs.push_back(ABIName.data());
  7238. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  7239. // or -mshared (not implemented) is in effect.
  7240. if (RelocationModel == llvm::Reloc::Static)
  7241. CmdArgs.push_back("-mno-shared");
  7242. // LLVM doesn't support -mplt yet and acts as if it is always given.
  7243. // However, -mplt has no effect with the N64 ABI.
  7244. CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
  7245. if (getToolChain().getArch() == llvm::Triple::mips ||
  7246. getToolChain().getArch() == llvm::Triple::mips64)
  7247. CmdArgs.push_back("-EB");
  7248. else
  7249. CmdArgs.push_back("-EL");
  7250. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  7251. if (StringRef(A->getValue()) == "2008")
  7252. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  7253. }
  7254. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  7255. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  7256. options::OPT_mfp64)) {
  7257. A->claim();
  7258. A->render(Args, CmdArgs);
  7259. } else if (mips::shouldUseFPXX(
  7260. Args, getToolChain().getTriple(), CPUName, ABIName,
  7261. getMipsFloatABI(getToolChain().getDriver(), Args)))
  7262. CmdArgs.push_back("-mfpxx");
  7263. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  7264. // -mno-mips16 is actually -no-mips16.
  7265. if (Arg *A =
  7266. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  7267. if (A->getOption().matches(options::OPT_mips16)) {
  7268. A->claim();
  7269. A->render(Args, CmdArgs);
  7270. } else {
  7271. A->claim();
  7272. CmdArgs.push_back("-no-mips16");
  7273. }
  7274. }
  7275. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  7276. options::OPT_mno_micromips);
  7277. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  7278. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  7279. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  7280. // Do not use AddLastArg because not all versions of MIPS assembler
  7281. // support -mmsa / -mno-msa options.
  7282. if (A->getOption().matches(options::OPT_mmsa))
  7283. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  7284. }
  7285. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  7286. options::OPT_msoft_float);
  7287. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  7288. options::OPT_msingle_float);
  7289. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  7290. options::OPT_mno_odd_spreg);
  7291. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7292. break;
  7293. }
  7294. case llvm::Triple::systemz: {
  7295. // Always pass an -march option, since our default of z10 is later
  7296. // than the GNU assembler's default.
  7297. StringRef CPUName = getSystemZTargetCPU(Args);
  7298. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  7299. break;
  7300. }
  7301. }
  7302. Args.AddAllArgs(CmdArgs, options::OPT_I);
  7303. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7304. CmdArgs.push_back("-o");
  7305. CmdArgs.push_back(Output.getFilename());
  7306. for (const auto &II : Inputs)
  7307. CmdArgs.push_back(II.getFilename());
  7308. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7309. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7310. // Handle the debug info splitting at object creation time if we're
  7311. // creating an object.
  7312. // TODO: Currently only works on linux with newer objcopy.
  7313. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  7314. getToolChain().getTriple().isOSLinux())
  7315. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  7316. SplitDebugName(Args, Inputs[0]));
  7317. }
  7318. static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
  7319. ArgStringList &CmdArgs, const ArgList &Args) {
  7320. bool isAndroid = Triple.isAndroid();
  7321. bool isCygMing = Triple.isOSCygMing();
  7322. bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
  7323. Args.hasArg(options::OPT_static);
  7324. if (!D.CCCIsCXX())
  7325. CmdArgs.push_back("-lgcc");
  7326. if (StaticLibgcc || isAndroid) {
  7327. if (D.CCCIsCXX())
  7328. CmdArgs.push_back("-lgcc");
  7329. } else {
  7330. if (!D.CCCIsCXX() && !isCygMing)
  7331. CmdArgs.push_back("--as-needed");
  7332. CmdArgs.push_back("-lgcc_s");
  7333. if (!D.CCCIsCXX() && !isCygMing)
  7334. CmdArgs.push_back("--no-as-needed");
  7335. }
  7336. if (StaticLibgcc && !isAndroid)
  7337. CmdArgs.push_back("-lgcc_eh");
  7338. else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
  7339. CmdArgs.push_back("-lgcc");
  7340. // According to Android ABI, we have to link with libdl if we are
  7341. // linking with non-static libgcc.
  7342. //
  7343. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  7344. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  7345. if (isAndroid && !StaticLibgcc)
  7346. CmdArgs.push_back("-ldl");
  7347. }
  7348. static std::string getLinuxDynamicLinker(const ArgList &Args,
  7349. const toolchains::Linux &ToolChain) {
  7350. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7351. if (ToolChain.getTriple().isAndroid()) {
  7352. if (ToolChain.getTriple().isArch64Bit())
  7353. return "/system/bin/linker64";
  7354. else
  7355. return "/system/bin/linker";
  7356. } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
  7357. Arch == llvm::Triple::sparcel)
  7358. return "/lib/ld-linux.so.2";
  7359. else if (Arch == llvm::Triple::aarch64)
  7360. return "/lib/ld-linux-aarch64.so.1";
  7361. else if (Arch == llvm::Triple::aarch64_be)
  7362. return "/lib/ld-linux-aarch64_be.so.1";
  7363. else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
  7364. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7365. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7366. return "/lib/ld-linux-armhf.so.3";
  7367. else
  7368. return "/lib/ld-linux.so.3";
  7369. } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
  7370. // TODO: check which dynamic linker name.
  7371. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7372. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7373. return "/lib/ld-linux-armhf.so.3";
  7374. else
  7375. return "/lib/ld-linux.so.3";
  7376. } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
  7377. Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
  7378. std::string LibDir =
  7379. "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
  7380. StringRef LibName;
  7381. bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
  7382. if (mips::isUCLibc(Args))
  7383. LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
  7384. else if (!ToolChain.getTriple().hasEnvironment()) {
  7385. bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
  7386. (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
  7387. LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
  7388. } else
  7389. LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
  7390. return (LibDir + "/" + LibName).str();
  7391. } else if (Arch == llvm::Triple::ppc)
  7392. return "/lib/ld.so.1";
  7393. else if (Arch == llvm::Triple::ppc64) {
  7394. if (ppc::hasPPCAbiArg(Args, "elfv2"))
  7395. return "/lib64/ld64.so.2";
  7396. return "/lib64/ld64.so.1";
  7397. } else if (Arch == llvm::Triple::ppc64le) {
  7398. if (ppc::hasPPCAbiArg(Args, "elfv1"))
  7399. return "/lib64/ld64.so.1";
  7400. return "/lib64/ld64.so.2";
  7401. } else if (Arch == llvm::Triple::systemz)
  7402. return "/lib/ld64.so.1";
  7403. else if (Arch == llvm::Triple::sparcv9)
  7404. return "/lib64/ld-linux.so.2";
  7405. else if (Arch == llvm::Triple::x86_64 &&
  7406. ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7407. return "/libx32/ld-linux-x32.so.2";
  7408. else
  7409. return "/lib64/ld-linux-x86-64.so.2";
  7410. }
  7411. static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  7412. ArgStringList &CmdArgs, const ArgList &Args) {
  7413. // Make use of compiler-rt if --rtlib option is used
  7414. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  7415. switch (RLT) {
  7416. case ToolChain::RLT_CompilerRT:
  7417. switch (TC.getTriple().getOS()) {
  7418. default:
  7419. llvm_unreachable("unsupported OS");
  7420. case llvm::Triple::Win32:
  7421. case llvm::Triple::Linux:
  7422. addClangRT(TC, Args, CmdArgs);
  7423. break;
  7424. }
  7425. break;
  7426. case ToolChain::RLT_Libgcc:
  7427. AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
  7428. break;
  7429. }
  7430. }
  7431. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  7432. switch (T.getArch()) {
  7433. case llvm::Triple::x86:
  7434. return "elf_i386";
  7435. case llvm::Triple::aarch64:
  7436. return "aarch64linux";
  7437. case llvm::Triple::aarch64_be:
  7438. return "aarch64_be_linux";
  7439. case llvm::Triple::arm:
  7440. case llvm::Triple::thumb:
  7441. return "armelf_linux_eabi";
  7442. case llvm::Triple::armeb:
  7443. case llvm::Triple::thumbeb:
  7444. return "armebelf_linux_eabi"; /* TODO: check which NAME. */
  7445. case llvm::Triple::ppc:
  7446. return "elf32ppclinux";
  7447. case llvm::Triple::ppc64:
  7448. return "elf64ppc";
  7449. case llvm::Triple::ppc64le:
  7450. return "elf64lppc";
  7451. case llvm::Triple::sparc:
  7452. case llvm::Triple::sparcel:
  7453. return "elf32_sparc";
  7454. case llvm::Triple::sparcv9:
  7455. return "elf64_sparc";
  7456. case llvm::Triple::mips:
  7457. return "elf32btsmip";
  7458. case llvm::Triple::mipsel:
  7459. return "elf32ltsmip";
  7460. case llvm::Triple::mips64:
  7461. if (mips::hasMipsAbiArg(Args, "n32"))
  7462. return "elf32btsmipn32";
  7463. return "elf64btsmip";
  7464. case llvm::Triple::mips64el:
  7465. if (mips::hasMipsAbiArg(Args, "n32"))
  7466. return "elf32ltsmipn32";
  7467. return "elf64ltsmip";
  7468. case llvm::Triple::systemz:
  7469. return "elf64_s390";
  7470. case llvm::Triple::x86_64:
  7471. if (T.getEnvironment() == llvm::Triple::GNUX32)
  7472. return "elf32_x86_64";
  7473. return "elf_x86_64";
  7474. default:
  7475. llvm_unreachable("Unexpected arch");
  7476. }
  7477. }
  7478. void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7479. const InputInfo &Output,
  7480. const InputInfoList &Inputs,
  7481. const ArgList &Args,
  7482. const char *LinkingOutput) const {
  7483. const toolchains::Linux &ToolChain =
  7484. static_cast<const toolchains::Linux &>(getToolChain());
  7485. const Driver &D = ToolChain.getDriver();
  7486. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7487. llvm::Triple Triple = llvm::Triple(TripleStr);
  7488. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7489. const bool isAndroid = ToolChain.getTriple().isAndroid();
  7490. const bool IsPIE =
  7491. !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
  7492. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7493. const bool HasCRTBeginEndFiles =
  7494. ToolChain.getTriple().hasEnvironment() ||
  7495. (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
  7496. ArgStringList CmdArgs;
  7497. // Silence warning for "clang -g foo.o -o foo"
  7498. Args.ClaimAllArgs(options::OPT_g_Group);
  7499. // and "clang -emit-llvm foo.o -o foo"
  7500. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7501. // and for "clang -w foo.o -o foo". Other warning options are already
  7502. // handled somewhere else.
  7503. Args.ClaimAllArgs(options::OPT_w);
  7504. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  7505. if (llvm::sys::path::filename(Exec) == "lld") {
  7506. CmdArgs.push_back("-flavor");
  7507. CmdArgs.push_back("old-gnu");
  7508. CmdArgs.push_back("-target");
  7509. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  7510. }
  7511. if (!D.SysRoot.empty())
  7512. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7513. if (IsPIE)
  7514. CmdArgs.push_back("-pie");
  7515. if (Args.hasArg(options::OPT_rdynamic))
  7516. CmdArgs.push_back("-export-dynamic");
  7517. if (Args.hasArg(options::OPT_s))
  7518. CmdArgs.push_back("-s");
  7519. if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
  7520. arm::appendEBLinkFlags(Args, CmdArgs, Triple);
  7521. for (const auto &Opt : ToolChain.ExtraOpts)
  7522. CmdArgs.push_back(Opt.c_str());
  7523. if (!Args.hasArg(options::OPT_static)) {
  7524. CmdArgs.push_back("--eh-frame-hdr");
  7525. }
  7526. CmdArgs.push_back("-m");
  7527. CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
  7528. if (Args.hasArg(options::OPT_static)) {
  7529. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7530. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
  7531. CmdArgs.push_back("-Bstatic");
  7532. else
  7533. CmdArgs.push_back("-static");
  7534. } else if (Args.hasArg(options::OPT_shared)) {
  7535. CmdArgs.push_back("-shared");
  7536. }
  7537. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7538. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
  7539. (!Args.hasArg(options::OPT_static) &&
  7540. !Args.hasArg(options::OPT_shared))) {
  7541. CmdArgs.push_back("-dynamic-linker");
  7542. CmdArgs.push_back(Args.MakeArgString(
  7543. D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
  7544. }
  7545. CmdArgs.push_back("-o");
  7546. CmdArgs.push_back(Output.getFilename());
  7547. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7548. if (!isAndroid) {
  7549. const char *crt1 = nullptr;
  7550. if (!Args.hasArg(options::OPT_shared)) {
  7551. if (Args.hasArg(options::OPT_pg))
  7552. crt1 = "gcrt1.o";
  7553. else if (IsPIE)
  7554. crt1 = "Scrt1.o";
  7555. else
  7556. crt1 = "crt1.o";
  7557. }
  7558. if (crt1)
  7559. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  7560. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7561. }
  7562. const char *crtbegin;
  7563. if (Args.hasArg(options::OPT_static))
  7564. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  7565. else if (Args.hasArg(options::OPT_shared))
  7566. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  7567. else if (IsPIE)
  7568. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  7569. else
  7570. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  7571. if (HasCRTBeginEndFiles)
  7572. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7573. // Add crtfastmath.o if available and fast math is enabled.
  7574. ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  7575. }
  7576. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7577. Args.AddAllArgs(CmdArgs, options::OPT_u);
  7578. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7579. if (D.isUsingLTO())
  7580. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  7581. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  7582. CmdArgs.push_back("--no-demangle");
  7583. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  7584. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7585. // The profile runtime also needs access to system libraries.
  7586. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7587. if (D.CCCIsCXX() &&
  7588. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7589. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  7590. !Args.hasArg(options::OPT_static);
  7591. if (OnlyLibstdcxxStatic)
  7592. CmdArgs.push_back("-Bstatic");
  7593. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7594. if (OnlyLibstdcxxStatic)
  7595. CmdArgs.push_back("-Bdynamic");
  7596. CmdArgs.push_back("-lm");
  7597. }
  7598. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  7599. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  7600. if (!Args.hasArg(options::OPT_nostdlib)) {
  7601. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  7602. if (Args.hasArg(options::OPT_static))
  7603. CmdArgs.push_back("--start-group");
  7604. if (NeedsSanitizerDeps)
  7605. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  7606. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  7607. Args.hasArg(options::OPT_pthreads);
  7608. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  7609. options::OPT_fno_openmp, false)) {
  7610. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  7611. // FIXME: Does this really make sense for all GNU toolchains?
  7612. WantPthread = true;
  7613. // Also link the particular OpenMP runtimes.
  7614. switch (getOpenMPRuntime(ToolChain, Args)) {
  7615. case OMPRT_OMP:
  7616. CmdArgs.push_back("-lomp");
  7617. break;
  7618. case OMPRT_GOMP:
  7619. CmdArgs.push_back("-lgomp");
  7620. // FIXME: Exclude this for platforms with libgomp that don't require
  7621. // librt. Most modern Linux platforms require it, but some may not.
  7622. CmdArgs.push_back("-lrt");
  7623. break;
  7624. case OMPRT_IOMP5:
  7625. CmdArgs.push_back("-liomp5");
  7626. break;
  7627. case OMPRT_Unknown:
  7628. // Already diagnosed.
  7629. break;
  7630. }
  7631. }
  7632. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  7633. if (WantPthread && !isAndroid)
  7634. CmdArgs.push_back("-lpthread");
  7635. CmdArgs.push_back("-lc");
  7636. if (Args.hasArg(options::OPT_static))
  7637. CmdArgs.push_back("--end-group");
  7638. else
  7639. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  7640. }
  7641. if (!Args.hasArg(options::OPT_nostartfiles)) {
  7642. const char *crtend;
  7643. if (Args.hasArg(options::OPT_shared))
  7644. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  7645. else if (IsPIE)
  7646. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  7647. else
  7648. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  7649. if (HasCRTBeginEndFiles)
  7650. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  7651. if (!isAndroid)
  7652. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7653. }
  7654. }
  7655. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7656. }
  7657. // NaCl ARM assembly (inline or standalone) can be written with a set of macros
  7658. // for the various SFI requirements like register masking. The assembly tool
  7659. // inserts the file containing the macros as an input into all the assembly
  7660. // jobs.
  7661. void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
  7662. const InputInfo &Output,
  7663. const InputInfoList &Inputs,
  7664. const ArgList &Args,
  7665. const char *LinkingOutput) const {
  7666. const toolchains::NaClToolChain &ToolChain =
  7667. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  7668. InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
  7669. "nacl-arm-macros.s");
  7670. InputInfoList NewInputs;
  7671. NewInputs.push_back(NaClMacros);
  7672. NewInputs.append(Inputs.begin(), Inputs.end());
  7673. gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
  7674. LinkingOutput);
  7675. }
  7676. // This is quite similar to gnutools::Linker::ConstructJob with changes that
  7677. // we use static by default, do not yet support sanitizers or LTO, and a few
  7678. // others. Eventually we can support more of that and hopefully migrate back
  7679. // to gnutools::Linker.
  7680. void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7681. const InputInfo &Output,
  7682. const InputInfoList &Inputs,
  7683. const ArgList &Args,
  7684. const char *LinkingOutput) const {
  7685. const toolchains::NaClToolChain &ToolChain =
  7686. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  7687. const Driver &D = ToolChain.getDriver();
  7688. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7689. const bool IsStatic =
  7690. !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
  7691. ArgStringList CmdArgs;
  7692. // Silence warning for "clang -g foo.o -o foo"
  7693. Args.ClaimAllArgs(options::OPT_g_Group);
  7694. // and "clang -emit-llvm foo.o -o foo"
  7695. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7696. // and for "clang -w foo.o -o foo". Other warning options are already
  7697. // handled somewhere else.
  7698. Args.ClaimAllArgs(options::OPT_w);
  7699. if (!D.SysRoot.empty())
  7700. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7701. if (Args.hasArg(options::OPT_rdynamic))
  7702. CmdArgs.push_back("-export-dynamic");
  7703. if (Args.hasArg(options::OPT_s))
  7704. CmdArgs.push_back("-s");
  7705. // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
  7706. // from there is --build-id, which we do want.
  7707. CmdArgs.push_back("--build-id");
  7708. if (!IsStatic)
  7709. CmdArgs.push_back("--eh-frame-hdr");
  7710. CmdArgs.push_back("-m");
  7711. if (Arch == llvm::Triple::x86)
  7712. CmdArgs.push_back("elf_i386_nacl");
  7713. else if (Arch == llvm::Triple::arm)
  7714. CmdArgs.push_back("armelf_nacl");
  7715. else if (Arch == llvm::Triple::x86_64)
  7716. CmdArgs.push_back("elf_x86_64_nacl");
  7717. else if (Arch == llvm::Triple::mipsel)
  7718. CmdArgs.push_back("mipselelf_nacl");
  7719. else
  7720. D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
  7721. << "Native Client";
  7722. if (IsStatic)
  7723. CmdArgs.push_back("-static");
  7724. else if (Args.hasArg(options::OPT_shared))
  7725. CmdArgs.push_back("-shared");
  7726. CmdArgs.push_back("-o");
  7727. CmdArgs.push_back(Output.getFilename());
  7728. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7729. if (!Args.hasArg(options::OPT_shared))
  7730. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  7731. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7732. const char *crtbegin;
  7733. if (IsStatic)
  7734. crtbegin = "crtbeginT.o";
  7735. else if (Args.hasArg(options::OPT_shared))
  7736. crtbegin = "crtbeginS.o";
  7737. else
  7738. crtbegin = "crtbegin.o";
  7739. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7740. }
  7741. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7742. Args.AddAllArgs(CmdArgs, options::OPT_u);
  7743. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7744. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  7745. CmdArgs.push_back("--no-demangle");
  7746. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7747. if (D.CCCIsCXX() &&
  7748. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7749. bool OnlyLibstdcxxStatic =
  7750. Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
  7751. if (OnlyLibstdcxxStatic)
  7752. CmdArgs.push_back("-Bstatic");
  7753. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7754. if (OnlyLibstdcxxStatic)
  7755. CmdArgs.push_back("-Bdynamic");
  7756. CmdArgs.push_back("-lm");
  7757. }
  7758. if (!Args.hasArg(options::OPT_nostdlib)) {
  7759. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  7760. // Always use groups, since it has no effect on dynamic libraries.
  7761. CmdArgs.push_back("--start-group");
  7762. CmdArgs.push_back("-lc");
  7763. // NaCl's libc++ currently requires libpthread, so just always include it
  7764. // in the group for C++.
  7765. if (Args.hasArg(options::OPT_pthread) ||
  7766. Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
  7767. // Gold, used by Mips, handles nested groups differently than ld, and
  7768. // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
  7769. // which is not a desired behaviour here.
  7770. // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
  7771. if (getToolChain().getArch() == llvm::Triple::mipsel)
  7772. CmdArgs.push_back("-lnacl");
  7773. CmdArgs.push_back("-lpthread");
  7774. }
  7775. CmdArgs.push_back("-lgcc");
  7776. CmdArgs.push_back("--as-needed");
  7777. if (IsStatic)
  7778. CmdArgs.push_back("-lgcc_eh");
  7779. else
  7780. CmdArgs.push_back("-lgcc_s");
  7781. CmdArgs.push_back("--no-as-needed");
  7782. // Mips needs to create and use pnacl_legacy library that contains
  7783. // definitions from bitcode/pnaclmm.c and definitions for
  7784. // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
  7785. if (getToolChain().getArch() == llvm::Triple::mipsel)
  7786. CmdArgs.push_back("-lpnacl_legacy");
  7787. CmdArgs.push_back("--end-group");
  7788. }
  7789. if (!Args.hasArg(options::OPT_nostartfiles)) {
  7790. const char *crtend;
  7791. if (Args.hasArg(options::OPT_shared))
  7792. crtend = "crtendS.o";
  7793. else
  7794. crtend = "crtend.o";
  7795. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  7796. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7797. }
  7798. }
  7799. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  7800. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7801. }
  7802. void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7803. const InputInfo &Output,
  7804. const InputInfoList &Inputs,
  7805. const ArgList &Args,
  7806. const char *LinkingOutput) const {
  7807. claimNoWarnArgs(Args);
  7808. ArgStringList CmdArgs;
  7809. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7810. CmdArgs.push_back("-o");
  7811. CmdArgs.push_back(Output.getFilename());
  7812. for (const auto &II : Inputs)
  7813. CmdArgs.push_back(II.getFilename());
  7814. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7815. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7816. }
  7817. void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7818. const InputInfo &Output,
  7819. const InputInfoList &Inputs,
  7820. const ArgList &Args,
  7821. const char *LinkingOutput) const {
  7822. const Driver &D = getToolChain().getDriver();
  7823. ArgStringList CmdArgs;
  7824. if (Output.isFilename()) {
  7825. CmdArgs.push_back("-o");
  7826. CmdArgs.push_back(Output.getFilename());
  7827. } else {
  7828. assert(Output.isNothing() && "Invalid output.");
  7829. }
  7830. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7831. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  7832. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7833. CmdArgs.push_back(
  7834. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7835. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7836. }
  7837. Args.AddAllArgs(CmdArgs,
  7838. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7839. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7840. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7841. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7842. if (D.CCCIsCXX()) {
  7843. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7844. CmdArgs.push_back("-lm");
  7845. }
  7846. }
  7847. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7848. if (Args.hasArg(options::OPT_pthread))
  7849. CmdArgs.push_back("-lpthread");
  7850. CmdArgs.push_back("-lc");
  7851. CmdArgs.push_back("-lCompilerRT-Generic");
  7852. CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
  7853. CmdArgs.push_back(
  7854. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7855. }
  7856. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7857. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7858. }
  7859. /// DragonFly Tools
  7860. // For now, DragonFly Assemble does just about the same as for
  7861. // FreeBSD, but this may change soon.
  7862. void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7863. const InputInfo &Output,
  7864. const InputInfoList &Inputs,
  7865. const ArgList &Args,
  7866. const char *LinkingOutput) const {
  7867. claimNoWarnArgs(Args);
  7868. ArgStringList CmdArgs;
  7869. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  7870. // instruct as in the base system to assemble 32-bit code.
  7871. if (getToolChain().getArch() == llvm::Triple::x86)
  7872. CmdArgs.push_back("--32");
  7873. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7874. CmdArgs.push_back("-o");
  7875. CmdArgs.push_back(Output.getFilename());
  7876. for (const auto &II : Inputs)
  7877. CmdArgs.push_back(II.getFilename());
  7878. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7879. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7880. }
  7881. void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7882. const InputInfo &Output,
  7883. const InputInfoList &Inputs,
  7884. const ArgList &Args,
  7885. const char *LinkingOutput) const {
  7886. const Driver &D = getToolChain().getDriver();
  7887. ArgStringList CmdArgs;
  7888. bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
  7889. if (!D.SysRoot.empty())
  7890. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7891. CmdArgs.push_back("--eh-frame-hdr");
  7892. if (Args.hasArg(options::OPT_static)) {
  7893. CmdArgs.push_back("-Bstatic");
  7894. } else {
  7895. if (Args.hasArg(options::OPT_rdynamic))
  7896. CmdArgs.push_back("-export-dynamic");
  7897. if (Args.hasArg(options::OPT_shared))
  7898. CmdArgs.push_back("-Bshareable");
  7899. else {
  7900. CmdArgs.push_back("-dynamic-linker");
  7901. CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
  7902. }
  7903. CmdArgs.push_back("--hash-style=both");
  7904. }
  7905. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  7906. // instruct ld in the base system to link 32-bit code.
  7907. if (getToolChain().getArch() == llvm::Triple::x86) {
  7908. CmdArgs.push_back("-m");
  7909. CmdArgs.push_back("elf_i386");
  7910. }
  7911. if (Output.isFilename()) {
  7912. CmdArgs.push_back("-o");
  7913. CmdArgs.push_back(Output.getFilename());
  7914. } else {
  7915. assert(Output.isNothing() && "Invalid output.");
  7916. }
  7917. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7918. if (!Args.hasArg(options::OPT_shared)) {
  7919. if (Args.hasArg(options::OPT_pg))
  7920. CmdArgs.push_back(
  7921. Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
  7922. else {
  7923. if (Args.hasArg(options::OPT_pie))
  7924. CmdArgs.push_back(
  7925. Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
  7926. else
  7927. CmdArgs.push_back(
  7928. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  7929. }
  7930. }
  7931. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7932. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  7933. CmdArgs.push_back(
  7934. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7935. else
  7936. CmdArgs.push_back(
  7937. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7938. }
  7939. Args.AddAllArgs(CmdArgs,
  7940. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7941. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7942. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7943. // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
  7944. // rpaths
  7945. if (UseGCC47)
  7946. CmdArgs.push_back("-L/usr/lib/gcc47");
  7947. else
  7948. CmdArgs.push_back("-L/usr/lib/gcc44");
  7949. if (!Args.hasArg(options::OPT_static)) {
  7950. if (UseGCC47) {
  7951. CmdArgs.push_back("-rpath");
  7952. CmdArgs.push_back("/usr/lib/gcc47");
  7953. } else {
  7954. CmdArgs.push_back("-rpath");
  7955. CmdArgs.push_back("/usr/lib/gcc44");
  7956. }
  7957. }
  7958. if (D.CCCIsCXX()) {
  7959. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7960. CmdArgs.push_back("-lm");
  7961. }
  7962. if (Args.hasArg(options::OPT_pthread))
  7963. CmdArgs.push_back("-lpthread");
  7964. if (!Args.hasArg(options::OPT_nolibc)) {
  7965. CmdArgs.push_back("-lc");
  7966. }
  7967. if (UseGCC47) {
  7968. if (Args.hasArg(options::OPT_static) ||
  7969. Args.hasArg(options::OPT_static_libgcc)) {
  7970. CmdArgs.push_back("-lgcc");
  7971. CmdArgs.push_back("-lgcc_eh");
  7972. } else {
  7973. if (Args.hasArg(options::OPT_shared_libgcc)) {
  7974. CmdArgs.push_back("-lgcc_pic");
  7975. if (!Args.hasArg(options::OPT_shared))
  7976. CmdArgs.push_back("-lgcc");
  7977. } else {
  7978. CmdArgs.push_back("-lgcc");
  7979. CmdArgs.push_back("--as-needed");
  7980. CmdArgs.push_back("-lgcc_pic");
  7981. CmdArgs.push_back("--no-as-needed");
  7982. }
  7983. }
  7984. } else {
  7985. if (Args.hasArg(options::OPT_shared)) {
  7986. CmdArgs.push_back("-lgcc_pic");
  7987. } else {
  7988. CmdArgs.push_back("-lgcc");
  7989. }
  7990. }
  7991. }
  7992. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7993. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  7994. CmdArgs.push_back(
  7995. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7996. else
  7997. CmdArgs.push_back(
  7998. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7999. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8000. }
  8001. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8002. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8003. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8004. }
  8005. // Try to find Exe from a Visual Studio distribution. This first tries to find
  8006. // an installed copy of Visual Studio and, failing that, looks in the PATH,
  8007. // making sure that whatever executable that's found is not a same-named exe
  8008. // from clang itself to prevent clang from falling back to itself.
  8009. static std::string FindVisualStudioExecutable(const ToolChain &TC,
  8010. const char *Exe,
  8011. const char *ClangProgramPath) {
  8012. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8013. std::string visualStudioBinDir;
  8014. if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
  8015. visualStudioBinDir)) {
  8016. SmallString<128> FilePath(visualStudioBinDir);
  8017. llvm::sys::path::append(FilePath, Exe);
  8018. if (llvm::sys::fs::can_execute(FilePath.c_str()))
  8019. return FilePath.str();
  8020. }
  8021. return Exe;
  8022. }
  8023. void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8024. const InputInfo &Output,
  8025. const InputInfoList &Inputs,
  8026. const ArgList &Args,
  8027. const char *LinkingOutput) const {
  8028. ArgStringList CmdArgs;
  8029. const ToolChain &TC = getToolChain();
  8030. assert((Output.isFilename() || Output.isNothing()) && "invalid output");
  8031. if (Output.isFilename())
  8032. CmdArgs.push_back(
  8033. Args.MakeArgString(std::string("-out:") + Output.getFilename()));
  8034. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
  8035. !C.getDriver().IsCLMode())
  8036. CmdArgs.push_back("-defaultlib:libcmt");
  8037. if (!llvm::sys::Process::GetEnv("LIB")) {
  8038. // If the VC environment hasn't been configured (perhaps because the user
  8039. // did not run vcvarsall), try to build a consistent link environment. If
  8040. // the environment variable is set however, assume the user knows what
  8041. // they're doing.
  8042. std::string VisualStudioDir;
  8043. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8044. if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
  8045. SmallString<128> LibDir(VisualStudioDir);
  8046. llvm::sys::path::append(LibDir, "VC", "lib");
  8047. switch (MSVC.getArch()) {
  8048. case llvm::Triple::x86:
  8049. // x86 just puts the libraries directly in lib
  8050. break;
  8051. case llvm::Triple::x86_64:
  8052. llvm::sys::path::append(LibDir, "amd64");
  8053. break;
  8054. case llvm::Triple::arm:
  8055. llvm::sys::path::append(LibDir, "arm");
  8056. break;
  8057. default:
  8058. break;
  8059. }
  8060. CmdArgs.push_back(
  8061. Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
  8062. if (MSVC.useUniversalCRT(VisualStudioDir)) {
  8063. std::string UniversalCRTLibPath;
  8064. if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
  8065. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8066. UniversalCRTLibPath.c_str()));
  8067. }
  8068. }
  8069. std::string WindowsSdkLibPath;
  8070. if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
  8071. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8072. WindowsSdkLibPath.c_str()));
  8073. }
  8074. CmdArgs.push_back("-nologo");
  8075. if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
  8076. CmdArgs.push_back("-debug");
  8077. bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
  8078. options::OPT_shared);
  8079. if (DLL) {
  8080. CmdArgs.push_back(Args.MakeArgString("-dll"));
  8081. SmallString<128> ImplibName(Output.getFilename());
  8082. llvm::sys::path::replace_extension(ImplibName, "lib");
  8083. CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
  8084. }
  8085. if (TC.getSanitizerArgs().needsAsanRt()) {
  8086. CmdArgs.push_back(Args.MakeArgString("-debug"));
  8087. CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
  8088. if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
  8089. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  8090. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8091. // Make sure the dynamic runtime thunk is not optimized out at link time
  8092. // to ensure proper SEH handling.
  8093. CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
  8094. } else if (DLL) {
  8095. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  8096. } else {
  8097. for (const auto &Lib : {"asan", "asan_cxx"})
  8098. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8099. }
  8100. }
  8101. Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
  8102. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8103. options::OPT_fno_openmp, false)) {
  8104. CmdArgs.push_back("-nodefaultlib:vcomp.lib");
  8105. CmdArgs.push_back("-nodefaultlib:vcompd.lib");
  8106. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8107. TC.getDriver().Dir + "/../lib"));
  8108. switch (getOpenMPRuntime(getToolChain(), Args)) {
  8109. case OMPRT_OMP:
  8110. CmdArgs.push_back("-defaultlib:libomp.lib");
  8111. break;
  8112. case OMPRT_IOMP5:
  8113. CmdArgs.push_back("-defaultlib:libiomp5md.lib");
  8114. break;
  8115. case OMPRT_GOMP:
  8116. break;
  8117. case OMPRT_Unknown:
  8118. // Already diagnosed.
  8119. break;
  8120. }
  8121. }
  8122. // Add filenames, libraries, and other linker inputs.
  8123. for (const auto &Input : Inputs) {
  8124. if (Input.isFilename()) {
  8125. CmdArgs.push_back(Input.getFilename());
  8126. continue;
  8127. }
  8128. const Arg &A = Input.getInputArg();
  8129. // Render -l options differently for the MSVC linker.
  8130. if (A.getOption().matches(options::OPT_l)) {
  8131. StringRef Lib = A.getValue();
  8132. const char *LinkLibArg;
  8133. if (Lib.endswith(".lib"))
  8134. LinkLibArg = Args.MakeArgString(Lib);
  8135. else
  8136. LinkLibArg = Args.MakeArgString(Lib + ".lib");
  8137. CmdArgs.push_back(LinkLibArg);
  8138. continue;
  8139. }
  8140. // Otherwise, this is some other kind of linker input option like -Wl, -z,
  8141. // or -L. Render it, even if MSVC doesn't understand it.
  8142. A.renderAsInput(Args, CmdArgs);
  8143. }
  8144. // We need to special case some linker paths. In the case of lld, we need to
  8145. // translate 'lld' into 'lld-link', and in the case of the regular msvc
  8146. // linker, we need to use a special search algorithm.
  8147. llvm::SmallString<128> linkPath;
  8148. StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
  8149. if (Linker.equals_lower("lld"))
  8150. Linker = "lld-link";
  8151. if (Linker.equals_lower("link")) {
  8152. // If we're using the MSVC linker, it's not sufficient to just use link
  8153. // from the program PATH, because other environments like GnuWin32 install
  8154. // their own link.exe which may come first.
  8155. linkPath = FindVisualStudioExecutable(TC, "link.exe",
  8156. C.getDriver().getClangProgramPath());
  8157. } else {
  8158. linkPath = Linker;
  8159. llvm::sys::path::replace_extension(linkPath, "exe");
  8160. linkPath = TC.GetProgramPath(linkPath.c_str());
  8161. }
  8162. const char *Exec = Args.MakeArgString(linkPath);
  8163. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8164. }
  8165. void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8166. const InputInfo &Output,
  8167. const InputInfoList &Inputs,
  8168. const ArgList &Args,
  8169. const char *LinkingOutput) const {
  8170. C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
  8171. }
  8172. std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
  8173. Compilation &C, const JobAction &JA, const InputInfo &Output,
  8174. const InputInfoList &Inputs, const ArgList &Args,
  8175. const char *LinkingOutput) const {
  8176. ArgStringList CmdArgs;
  8177. CmdArgs.push_back("/nologo");
  8178. CmdArgs.push_back("/c"); // Compile only.
  8179. CmdArgs.push_back("/W0"); // No warnings.
  8180. // The goal is to be able to invoke this tool correctly based on
  8181. // any flag accepted by clang-cl.
  8182. // These are spelled the same way in clang and cl.exe,.
  8183. Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
  8184. // Optimization level.
  8185. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
  8186. CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
  8187. : "/Oi-");
  8188. if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
  8189. if (A->getOption().getID() == options::OPT_O0) {
  8190. CmdArgs.push_back("/Od");
  8191. } else {
  8192. CmdArgs.push_back("/Og");
  8193. StringRef OptLevel = A->getValue();
  8194. if (OptLevel == "s" || OptLevel == "z")
  8195. CmdArgs.push_back("/Os");
  8196. else
  8197. CmdArgs.push_back("/Ot");
  8198. CmdArgs.push_back("/Ob2");
  8199. }
  8200. }
  8201. if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  8202. options::OPT_fno_omit_frame_pointer))
  8203. CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
  8204. ? "/Oy"
  8205. : "/Oy-");
  8206. if (!Args.hasArg(options::OPT_fwritable_strings))
  8207. CmdArgs.push_back("/GF");
  8208. // Flags for which clang-cl has an alias.
  8209. // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
  8210. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  8211. /*default=*/false))
  8212. CmdArgs.push_back("/GR-");
  8213. if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
  8214. options::OPT_fno_function_sections))
  8215. CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
  8216. ? "/Gy"
  8217. : "/Gy-");
  8218. if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
  8219. options::OPT_fno_data_sections))
  8220. CmdArgs.push_back(
  8221. A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
  8222. if (Args.hasArg(options::OPT_fsyntax_only))
  8223. CmdArgs.push_back("/Zs");
  8224. if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
  8225. options::OPT__SLASH_Z7))
  8226. CmdArgs.push_back("/Z7");
  8227. std::vector<std::string> Includes =
  8228. Args.getAllArgValues(options::OPT_include);
  8229. for (const auto &Include : Includes)
  8230. CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
  8231. // Flags that can simply be passed through.
  8232. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
  8233. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
  8234. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
  8235. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
  8236. // The order of these flags is relevant, so pick the last one.
  8237. if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
  8238. options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
  8239. A->render(Args, CmdArgs);
  8240. // Input filename.
  8241. assert(Inputs.size() == 1);
  8242. const InputInfo &II = Inputs[0];
  8243. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  8244. CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
  8245. if (II.isFilename())
  8246. CmdArgs.push_back(II.getFilename());
  8247. else
  8248. II.getInputArg().renderAsInput(Args, CmdArgs);
  8249. // Output filename.
  8250. assert(Output.getType() == types::TY_Object);
  8251. const char *Fo =
  8252. Args.MakeArgString(std::string("/Fo") + Output.getFilename());
  8253. CmdArgs.push_back(Fo);
  8254. const Driver &D = getToolChain().getDriver();
  8255. std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
  8256. D.getClangProgramPath());
  8257. return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8258. CmdArgs, Inputs);
  8259. }
  8260. /// MinGW Tools
  8261. void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8262. const InputInfo &Output,
  8263. const InputInfoList &Inputs,
  8264. const ArgList &Args,
  8265. const char *LinkingOutput) const {
  8266. claimNoWarnArgs(Args);
  8267. ArgStringList CmdArgs;
  8268. if (getToolChain().getArch() == llvm::Triple::x86) {
  8269. CmdArgs.push_back("--32");
  8270. } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
  8271. CmdArgs.push_back("--64");
  8272. }
  8273. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8274. CmdArgs.push_back("-o");
  8275. CmdArgs.push_back(Output.getFilename());
  8276. for (const auto &II : Inputs)
  8277. CmdArgs.push_back(II.getFilename());
  8278. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8279. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8280. if (Args.hasArg(options::OPT_gsplit_dwarf))
  8281. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  8282. SplitDebugName(Args, Inputs[0]));
  8283. }
  8284. void MinGW::Linker::AddLibGCC(const ArgList &Args,
  8285. ArgStringList &CmdArgs) const {
  8286. if (Args.hasArg(options::OPT_mthreads))
  8287. CmdArgs.push_back("-lmingwthrd");
  8288. CmdArgs.push_back("-lmingw32");
  8289. // Make use of compiler-rt if --rtlib option is used
  8290. ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
  8291. if (RLT == ToolChain::RLT_Libgcc) {
  8292. bool Static = Args.hasArg(options::OPT_static_libgcc) ||
  8293. Args.hasArg(options::OPT_static);
  8294. bool Shared = Args.hasArg(options::OPT_shared);
  8295. bool CXX = getToolChain().getDriver().CCCIsCXX();
  8296. if (Static || (!CXX && !Shared)) {
  8297. CmdArgs.push_back("-lgcc");
  8298. CmdArgs.push_back("-lgcc_eh");
  8299. } else {
  8300. CmdArgs.push_back("-lgcc_s");
  8301. CmdArgs.push_back("-lgcc");
  8302. }
  8303. } else {
  8304. AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
  8305. }
  8306. CmdArgs.push_back("-lmoldname");
  8307. CmdArgs.push_back("-lmingwex");
  8308. CmdArgs.push_back("-lmsvcrt");
  8309. }
  8310. void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8311. const InputInfo &Output,
  8312. const InputInfoList &Inputs,
  8313. const ArgList &Args,
  8314. const char *LinkingOutput) const {
  8315. const ToolChain &TC = getToolChain();
  8316. const Driver &D = TC.getDriver();
  8317. // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  8318. ArgStringList CmdArgs;
  8319. // Silence warning for "clang -g foo.o -o foo"
  8320. Args.ClaimAllArgs(options::OPT_g_Group);
  8321. // and "clang -emit-llvm foo.o -o foo"
  8322. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8323. // and for "clang -w foo.o -o foo". Other warning options are already
  8324. // handled somewhere else.
  8325. Args.ClaimAllArgs(options::OPT_w);
  8326. StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
  8327. if (LinkerName.equals_lower("lld")) {
  8328. CmdArgs.push_back("-flavor");
  8329. CmdArgs.push_back("gnu");
  8330. } else if (!LinkerName.equals_lower("ld")) {
  8331. D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
  8332. }
  8333. if (!D.SysRoot.empty())
  8334. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8335. if (Args.hasArg(options::OPT_s))
  8336. CmdArgs.push_back("-s");
  8337. CmdArgs.push_back("-m");
  8338. if (TC.getArch() == llvm::Triple::x86)
  8339. CmdArgs.push_back("i386pe");
  8340. if (TC.getArch() == llvm::Triple::x86_64)
  8341. CmdArgs.push_back("i386pep");
  8342. if (TC.getArch() == llvm::Triple::arm)
  8343. CmdArgs.push_back("thumb2pe");
  8344. if (Args.hasArg(options::OPT_mwindows)) {
  8345. CmdArgs.push_back("--subsystem");
  8346. CmdArgs.push_back("windows");
  8347. } else if (Args.hasArg(options::OPT_mconsole)) {
  8348. CmdArgs.push_back("--subsystem");
  8349. CmdArgs.push_back("console");
  8350. }
  8351. if (Args.hasArg(options::OPT_static))
  8352. CmdArgs.push_back("-Bstatic");
  8353. else {
  8354. if (Args.hasArg(options::OPT_mdll))
  8355. CmdArgs.push_back("--dll");
  8356. else if (Args.hasArg(options::OPT_shared))
  8357. CmdArgs.push_back("--shared");
  8358. CmdArgs.push_back("-Bdynamic");
  8359. if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
  8360. CmdArgs.push_back("-e");
  8361. if (TC.getArch() == llvm::Triple::x86)
  8362. CmdArgs.push_back("_DllMainCRTStartup@12");
  8363. else
  8364. CmdArgs.push_back("DllMainCRTStartup");
  8365. CmdArgs.push_back("--enable-auto-image-base");
  8366. }
  8367. }
  8368. CmdArgs.push_back("-o");
  8369. CmdArgs.push_back(Output.getFilename());
  8370. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8371. // FIXME: add -N, -n flags
  8372. Args.AddLastArg(CmdArgs, options::OPT_r);
  8373. Args.AddLastArg(CmdArgs, options::OPT_s);
  8374. Args.AddLastArg(CmdArgs, options::OPT_t);
  8375. Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
  8376. Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
  8377. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8378. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
  8379. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
  8380. } else {
  8381. if (Args.hasArg(options::OPT_municode))
  8382. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
  8383. else
  8384. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
  8385. }
  8386. if (Args.hasArg(options::OPT_pg))
  8387. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
  8388. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8389. }
  8390. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8391. TC.AddFilePathLibArgs(Args, CmdArgs);
  8392. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8393. // TODO: Add ASan stuff here
  8394. // TODO: Add profile stuff here
  8395. if (D.CCCIsCXX() &&
  8396. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8397. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8398. !Args.hasArg(options::OPT_static);
  8399. if (OnlyLibstdcxxStatic)
  8400. CmdArgs.push_back("-Bstatic");
  8401. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8402. if (OnlyLibstdcxxStatic)
  8403. CmdArgs.push_back("-Bdynamic");
  8404. }
  8405. if (!Args.hasArg(options::OPT_nostdlib)) {
  8406. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8407. if (Args.hasArg(options::OPT_static))
  8408. CmdArgs.push_back("--start-group");
  8409. if (Args.hasArg(options::OPT_fstack_protector) ||
  8410. Args.hasArg(options::OPT_fstack_protector_strong) ||
  8411. Args.hasArg(options::OPT_fstack_protector_all)) {
  8412. CmdArgs.push_back("-lssp_nonshared");
  8413. CmdArgs.push_back("-lssp");
  8414. }
  8415. if (Args.hasArg(options::OPT_fopenmp))
  8416. CmdArgs.push_back("-lgomp");
  8417. AddLibGCC(Args, CmdArgs);
  8418. if (Args.hasArg(options::OPT_pg))
  8419. CmdArgs.push_back("-lgmon");
  8420. if (Args.hasArg(options::OPT_pthread))
  8421. CmdArgs.push_back("-lpthread");
  8422. // add system libraries
  8423. if (Args.hasArg(options::OPT_mwindows)) {
  8424. CmdArgs.push_back("-lgdi32");
  8425. CmdArgs.push_back("-lcomdlg32");
  8426. }
  8427. CmdArgs.push_back("-ladvapi32");
  8428. CmdArgs.push_back("-lshell32");
  8429. CmdArgs.push_back("-luser32");
  8430. CmdArgs.push_back("-lkernel32");
  8431. if (Args.hasArg(options::OPT_static))
  8432. CmdArgs.push_back("--end-group");
  8433. else if (!LinkerName.equals_lower("lld"))
  8434. AddLibGCC(Args, CmdArgs);
  8435. }
  8436. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8437. // Add crtfastmath.o if available and fast math is enabled.
  8438. TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8439. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8440. }
  8441. }
  8442. const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
  8443. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8444. }
  8445. /// XCore Tools
  8446. // We pass assemble and link construction to the xcc tool.
  8447. void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8448. const InputInfo &Output,
  8449. const InputInfoList &Inputs,
  8450. const ArgList &Args,
  8451. const char *LinkingOutput) const {
  8452. claimNoWarnArgs(Args);
  8453. ArgStringList CmdArgs;
  8454. CmdArgs.push_back("-o");
  8455. CmdArgs.push_back(Output.getFilename());
  8456. CmdArgs.push_back("-c");
  8457. if (Args.hasArg(options::OPT_v))
  8458. CmdArgs.push_back("-v");
  8459. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  8460. if (!A->getOption().matches(options::OPT_g0))
  8461. CmdArgs.push_back("-g");
  8462. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  8463. false))
  8464. CmdArgs.push_back("-fverbose-asm");
  8465. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8466. for (const auto &II : Inputs)
  8467. CmdArgs.push_back(II.getFilename());
  8468. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8469. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8470. }
  8471. void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8472. const InputInfo &Output,
  8473. const InputInfoList &Inputs,
  8474. const ArgList &Args,
  8475. const char *LinkingOutput) const {
  8476. ArgStringList CmdArgs;
  8477. if (Output.isFilename()) {
  8478. CmdArgs.push_back("-o");
  8479. CmdArgs.push_back(Output.getFilename());
  8480. } else {
  8481. assert(Output.isNothing() && "Invalid output.");
  8482. }
  8483. if (Args.hasArg(options::OPT_v))
  8484. CmdArgs.push_back("-v");
  8485. // Pass -fexceptions through to the linker if it was present.
  8486. if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  8487. false))
  8488. CmdArgs.push_back("-fexceptions");
  8489. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8490. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8491. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8492. }
  8493. void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8494. const InputInfo &Output,
  8495. const InputInfoList &Inputs,
  8496. const ArgList &Args,
  8497. const char *LinkingOutput) const {
  8498. claimNoWarnArgs(Args);
  8499. const auto &TC =
  8500. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8501. ArgStringList CmdArgs;
  8502. const char *Exec;
  8503. switch (TC.getArch()) {
  8504. default:
  8505. llvm_unreachable("unsupported architecture");
  8506. case llvm::Triple::arm:
  8507. case llvm::Triple::thumb:
  8508. break;
  8509. case llvm::Triple::x86:
  8510. CmdArgs.push_back("--32");
  8511. break;
  8512. case llvm::Triple::x86_64:
  8513. CmdArgs.push_back("--64");
  8514. break;
  8515. }
  8516. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8517. CmdArgs.push_back("-o");
  8518. CmdArgs.push_back(Output.getFilename());
  8519. for (const auto &Input : Inputs)
  8520. CmdArgs.push_back(Input.getFilename());
  8521. const std::string Assembler = TC.GetProgramPath("as");
  8522. Exec = Args.MakeArgString(Assembler);
  8523. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8524. }
  8525. void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8526. const InputInfo &Output,
  8527. const InputInfoList &Inputs,
  8528. const ArgList &Args,
  8529. const char *LinkingOutput) const {
  8530. const auto &TC =
  8531. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8532. const llvm::Triple &T = TC.getTriple();
  8533. const Driver &D = TC.getDriver();
  8534. SmallString<128> EntryPoint;
  8535. ArgStringList CmdArgs;
  8536. const char *Exec;
  8537. // Silence warning for "clang -g foo.o -o foo"
  8538. Args.ClaimAllArgs(options::OPT_g_Group);
  8539. // and "clang -emit-llvm foo.o -o foo"
  8540. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8541. // and for "clang -w foo.o -o foo"
  8542. Args.ClaimAllArgs(options::OPT_w);
  8543. // Other warning options are already handled somewhere else.
  8544. if (!D.SysRoot.empty())
  8545. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8546. if (Args.hasArg(options::OPT_pie))
  8547. CmdArgs.push_back("-pie");
  8548. if (Args.hasArg(options::OPT_rdynamic))
  8549. CmdArgs.push_back("-export-dynamic");
  8550. if (Args.hasArg(options::OPT_s))
  8551. CmdArgs.push_back("--strip-all");
  8552. CmdArgs.push_back("-m");
  8553. switch (TC.getArch()) {
  8554. default:
  8555. llvm_unreachable("unsupported architecture");
  8556. case llvm::Triple::arm:
  8557. case llvm::Triple::thumb:
  8558. // FIXME: this is incorrect for WinCE
  8559. CmdArgs.push_back("thumb2pe");
  8560. break;
  8561. case llvm::Triple::x86:
  8562. CmdArgs.push_back("i386pe");
  8563. EntryPoint.append("_");
  8564. break;
  8565. case llvm::Triple::x86_64:
  8566. CmdArgs.push_back("i386pep");
  8567. break;
  8568. }
  8569. if (Args.hasArg(options::OPT_shared)) {
  8570. switch (T.getArch()) {
  8571. default:
  8572. llvm_unreachable("unsupported architecture");
  8573. case llvm::Triple::arm:
  8574. case llvm::Triple::thumb:
  8575. case llvm::Triple::x86_64:
  8576. EntryPoint.append("_DllMainCRTStartup");
  8577. break;
  8578. case llvm::Triple::x86:
  8579. EntryPoint.append("_DllMainCRTStartup@12");
  8580. break;
  8581. }
  8582. CmdArgs.push_back("-shared");
  8583. CmdArgs.push_back("-Bdynamic");
  8584. CmdArgs.push_back("--enable-auto-image-base");
  8585. CmdArgs.push_back("--entry");
  8586. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  8587. } else {
  8588. EntryPoint.append("mainCRTStartup");
  8589. CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
  8590. : "-Bdynamic");
  8591. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8592. CmdArgs.push_back("--entry");
  8593. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  8594. }
  8595. // FIXME: handle subsystem
  8596. }
  8597. // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
  8598. CmdArgs.push_back("--allow-multiple-definition");
  8599. CmdArgs.push_back("-o");
  8600. CmdArgs.push_back(Output.getFilename());
  8601. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
  8602. SmallString<261> ImpLib(Output.getFilename());
  8603. llvm::sys::path::replace_extension(ImpLib, ".lib");
  8604. CmdArgs.push_back("--out-implib");
  8605. CmdArgs.push_back(Args.MakeArgString(ImpLib));
  8606. }
  8607. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8608. const std::string CRTPath(D.SysRoot + "/usr/lib/");
  8609. const char *CRTBegin;
  8610. CRTBegin =
  8611. Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
  8612. CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
  8613. }
  8614. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8615. TC.AddFilePathLibArgs(Args, CmdArgs);
  8616. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8617. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  8618. !Args.hasArg(options::OPT_nodefaultlibs)) {
  8619. bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
  8620. !Args.hasArg(options::OPT_static);
  8621. if (StaticCXX)
  8622. CmdArgs.push_back("-Bstatic");
  8623. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8624. if (StaticCXX)
  8625. CmdArgs.push_back("-Bdynamic");
  8626. }
  8627. if (!Args.hasArg(options::OPT_nostdlib)) {
  8628. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8629. // TODO handle /MT[d] /MD[d]
  8630. CmdArgs.push_back("-lmsvcrt");
  8631. AddRunTimeLibs(TC, D, CmdArgs, Args);
  8632. }
  8633. }
  8634. if (TC.getSanitizerArgs().needsAsanRt()) {
  8635. // TODO handle /MT[d] /MD[d]
  8636. if (Args.hasArg(options::OPT_shared)) {
  8637. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  8638. } else {
  8639. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  8640. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8641. // Make sure the dynamic runtime thunk is not optimized out at link time
  8642. // to ensure proper SEH handling.
  8643. CmdArgs.push_back(Args.MakeArgString("--undefined"));
  8644. CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
  8645. ? "___asan_seh_interceptor"
  8646. : "__asan_seh_interceptor"));
  8647. }
  8648. }
  8649. Exec = Args.MakeArgString(TC.GetLinkerPath());
  8650. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8651. }
  8652. void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8653. const InputInfo &Output,
  8654. const InputInfoList &Inputs,
  8655. const ArgList &Args,
  8656. const char *LinkingOutput) const {
  8657. ArgStringList CmdArgs;
  8658. assert(Inputs.size() == 1);
  8659. const InputInfo &II = Inputs[0];
  8660. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
  8661. II.getType() == types::TY_PP_CXX);
  8662. if (JA.getKind() == Action::PreprocessJobClass) {
  8663. Args.ClaimAllArgs();
  8664. CmdArgs.push_back("-E");
  8665. } else {
  8666. assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
  8667. CmdArgs.push_back("-S");
  8668. CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
  8669. }
  8670. CmdArgs.push_back("-mcpu=myriad2");
  8671. CmdArgs.push_back("-DMYRIAD2");
  8672. // Append all -I, -iquote, -isystem paths, defines/undefines,
  8673. // 'f' flags, optimize flags, and warning options.
  8674. // These are spelled the same way in clang and moviCompile.
  8675. Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
  8676. options::OPT_std_EQ, options::OPT_D, options::OPT_U,
  8677. options::OPT_f_Group, options::OPT_f_clang_Group,
  8678. options::OPT_g_Group, options::OPT_M_Group,
  8679. options::OPT_O_Group, options::OPT_W_Group});
  8680. // If we're producing a dependency file, and assembly is the final action,
  8681. // then the name of the target in the dependency file should be the '.o'
  8682. // file, not the '.s' file produced by this step. For example, instead of
  8683. // /tmp/mumble.s: mumble.c .../someheader.h
  8684. // the filename on the lefthand side should be "mumble.o"
  8685. if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
  8686. C.getActions().size() == 1 &&
  8687. C.getActions()[0]->getKind() == Action::AssembleJobClass) {
  8688. Arg *A = Args.getLastArg(options::OPT_o);
  8689. if (A) {
  8690. CmdArgs.push_back("-MT");
  8691. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  8692. }
  8693. }
  8694. CmdArgs.push_back(II.getFilename());
  8695. CmdArgs.push_back("-o");
  8696. CmdArgs.push_back(Output.getFilename());
  8697. std::string Exec =
  8698. Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
  8699. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8700. CmdArgs, Inputs));
  8701. }
  8702. void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8703. const InputInfo &Output,
  8704. const InputInfoList &Inputs,
  8705. const ArgList &Args,
  8706. const char *LinkingOutput) const {
  8707. ArgStringList CmdArgs;
  8708. assert(Inputs.size() == 1);
  8709. const InputInfo &II = Inputs[0];
  8710. assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
  8711. assert(Output.getType() == types::TY_Object);
  8712. CmdArgs.push_back("-no6thSlotCompression");
  8713. CmdArgs.push_back("-cv:myriad2"); // Chip Version
  8714. CmdArgs.push_back("-noSPrefixing");
  8715. CmdArgs.push_back("-a"); // Mystery option.
  8716. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8717. for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
  8718. A->claim();
  8719. CmdArgs.push_back(
  8720. Args.MakeArgString(std::string("-i:") + A->getValue(0)));
  8721. }
  8722. CmdArgs.push_back("-elf"); // Output format.
  8723. CmdArgs.push_back(II.getFilename());
  8724. CmdArgs.push_back(
  8725. Args.MakeArgString(std::string("-o:") + Output.getFilename()));
  8726. std::string Exec =
  8727. Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
  8728. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8729. CmdArgs, Inputs));
  8730. }
  8731. void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8732. const InputInfo &Output,
  8733. const InputInfoList &Inputs,
  8734. const ArgList &Args,
  8735. const char *LinkingOutput) const {
  8736. const auto &TC =
  8737. static_cast<const toolchains::MyriadToolChain &>(getToolChain());
  8738. const llvm::Triple &T = TC.getTriple();
  8739. ArgStringList CmdArgs;
  8740. bool UseStartfiles =
  8741. !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
  8742. bool UseDefaultLibs =
  8743. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
  8744. if (T.getArch() == llvm::Triple::sparc)
  8745. CmdArgs.push_back("-EB");
  8746. else // SHAVE assumes little-endian, and sparcel is expressly so.
  8747. CmdArgs.push_back("-EL");
  8748. // The remaining logic is mostly like gnutools::Linker::ConstructJob,
  8749. // but we never pass through a --sysroot option and various other bits.
  8750. // For example, there are no sanitizers (yet) nor gold linker.
  8751. // Eat some arguments that may be present but have no effect.
  8752. Args.ClaimAllArgs(options::OPT_g_Group);
  8753. Args.ClaimAllArgs(options::OPT_w);
  8754. Args.ClaimAllArgs(options::OPT_static_libgcc);
  8755. if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
  8756. CmdArgs.push_back("-s");
  8757. CmdArgs.push_back("-o");
  8758. CmdArgs.push_back(Output.getFilename());
  8759. if (UseStartfiles) {
  8760. // If you want startfiles, it means you want the builtin crti and crtbegin,
  8761. // but not crt0. Myriad link commands provide their own crt0.o as needed.
  8762. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
  8763. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8764. }
  8765. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  8766. options::OPT_e, options::OPT_s, options::OPT_t,
  8767. options::OPT_Z_Flag, options::OPT_r});
  8768. TC.AddFilePathLibArgs(Args, CmdArgs);
  8769. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8770. if (UseDefaultLibs) {
  8771. if (C.getDriver().CCCIsCXX())
  8772. CmdArgs.push_back("-lstdc++");
  8773. if (T.getOS() == llvm::Triple::RTEMS) {
  8774. CmdArgs.push_back("--start-group");
  8775. CmdArgs.push_back("-lc");
  8776. // You must provide your own "-L" option to enable finding these.
  8777. CmdArgs.push_back("-lrtemscpu");
  8778. CmdArgs.push_back("-lrtemsbsp");
  8779. CmdArgs.push_back("--end-group");
  8780. } else {
  8781. CmdArgs.push_back("-lc");
  8782. }
  8783. CmdArgs.push_back("-lgcc");
  8784. }
  8785. if (UseStartfiles) {
  8786. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8787. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
  8788. }
  8789. std::string Exec =
  8790. Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
  8791. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8792. CmdArgs, Inputs));
  8793. }
  8794. void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
  8795. const InputInfo &Output,
  8796. const InputInfoList &Inputs,
  8797. const ArgList &Args,
  8798. const char *LinkingOutput) const {
  8799. claimNoWarnArgs(Args);
  8800. ArgStringList CmdArgs;
  8801. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8802. CmdArgs.push_back("-o");
  8803. CmdArgs.push_back(Output.getFilename());
  8804. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  8805. const InputInfo &Input = Inputs[0];
  8806. assert(Input.isFilename() && "Invalid input.");
  8807. CmdArgs.push_back(Input.getFilename());
  8808. const char *Exec =
  8809. Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
  8810. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8811. }
  8812. static void AddPS4ProfileRT(const ToolChain &TC, const ArgList &Args,
  8813. ArgStringList &CmdArgs) {
  8814. if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  8815. false) ||
  8816. Args.hasArg(options::OPT_fprofile_generate) ||
  8817. Args.hasArg(options::OPT_fprofile_instr_generate) ||
  8818. Args.hasArg(options::OPT_fcreate_profile) ||
  8819. Args.hasArg(options::OPT_coverage)))
  8820. return;
  8821. assert(TC.getTriple().isPS4CPU() &&
  8822. "Profiling libraries are only implemented for the PS4 CPU");
  8823. CmdArgs.push_back("-lclang_rt.profile-x86_64");
  8824. }
  8825. static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
  8826. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  8827. if (SanArgs.needsUbsanRt()) {
  8828. CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
  8829. }
  8830. if (SanArgs.needsAsanRt()) {
  8831. CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
  8832. }
  8833. }
  8834. static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
  8835. const JobAction &JA, const InputInfo &Output,
  8836. const InputInfoList &Inputs,
  8837. const ArgList &Args,
  8838. const char *LinkingOutput) {
  8839. const toolchains::FreeBSD &ToolChain =
  8840. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  8841. const Driver &D = ToolChain.getDriver();
  8842. ArgStringList CmdArgs;
  8843. // Silence warning for "clang -g foo.o -o foo"
  8844. Args.ClaimAllArgs(options::OPT_g_Group);
  8845. // and "clang -emit-llvm foo.o -o foo"
  8846. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8847. // and for "clang -w foo.o -o foo". Other warning options are already
  8848. // handled somewhere else.
  8849. Args.ClaimAllArgs(options::OPT_w);
  8850. if (!D.SysRoot.empty())
  8851. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8852. if (Args.hasArg(options::OPT_pie))
  8853. CmdArgs.push_back("-pie");
  8854. if (Args.hasArg(options::OPT_rdynamic))
  8855. CmdArgs.push_back("-export-dynamic");
  8856. if (Args.hasArg(options::OPT_shared))
  8857. CmdArgs.push_back("--oformat=so");
  8858. if (Output.isFilename()) {
  8859. CmdArgs.push_back("-o");
  8860. CmdArgs.push_back(Output.getFilename());
  8861. } else {
  8862. assert(Output.isNothing() && "Invalid output.");
  8863. }
  8864. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  8865. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8866. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  8867. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8868. Args.AddAllArgs(CmdArgs, options::OPT_s);
  8869. Args.AddAllArgs(CmdArgs, options::OPT_t);
  8870. Args.AddAllArgs(CmdArgs, options::OPT_r);
  8871. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8872. CmdArgs.push_back("--no-demangle");
  8873. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8874. if (Args.hasArg(options::OPT_pthread)) {
  8875. CmdArgs.push_back("-lpthread");
  8876. }
  8877. AddPS4ProfileRT(ToolChain, Args, CmdArgs);
  8878. const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  8879. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  8880. }
  8881. static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
  8882. const JobAction &JA, const InputInfo &Output,
  8883. const InputInfoList &Inputs,
  8884. const ArgList &Args,
  8885. const char *LinkingOutput) {
  8886. const toolchains::FreeBSD &ToolChain =
  8887. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  8888. const Driver &D = ToolChain.getDriver();
  8889. ArgStringList CmdArgs;
  8890. // Silence warning for "clang -g foo.o -o foo"
  8891. Args.ClaimAllArgs(options::OPT_g_Group);
  8892. // and "clang -emit-llvm foo.o -o foo"
  8893. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8894. // and for "clang -w foo.o -o foo". Other warning options are already
  8895. // handled somewhere else.
  8896. Args.ClaimAllArgs(options::OPT_w);
  8897. if (!D.SysRoot.empty())
  8898. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8899. if (Args.hasArg(options::OPT_pie))
  8900. CmdArgs.push_back("-pie");
  8901. if (Args.hasArg(options::OPT_static)) {
  8902. CmdArgs.push_back("-Bstatic");
  8903. } else {
  8904. if (Args.hasArg(options::OPT_rdynamic))
  8905. CmdArgs.push_back("-export-dynamic");
  8906. CmdArgs.push_back("--eh-frame-hdr");
  8907. if (Args.hasArg(options::OPT_shared)) {
  8908. CmdArgs.push_back("-Bshareable");
  8909. } else {
  8910. CmdArgs.push_back("-dynamic-linker");
  8911. CmdArgs.push_back("/libexec/ld-elf.so.1");
  8912. }
  8913. CmdArgs.push_back("--enable-new-dtags");
  8914. }
  8915. if (Output.isFilename()) {
  8916. CmdArgs.push_back("-o");
  8917. CmdArgs.push_back(Output.getFilename());
  8918. } else {
  8919. assert(Output.isNothing() && "Invalid output.");
  8920. }
  8921. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  8922. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8923. const char *crt1 = nullptr;
  8924. if (!Args.hasArg(options::OPT_shared)) {
  8925. if (Args.hasArg(options::OPT_pg))
  8926. crt1 = "gcrt1.o";
  8927. else if (Args.hasArg(options::OPT_pie))
  8928. crt1 = "Scrt1.o";
  8929. else
  8930. crt1 = "crt1.o";
  8931. }
  8932. if (crt1)
  8933. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  8934. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8935. const char *crtbegin = nullptr;
  8936. if (Args.hasArg(options::OPT_static))
  8937. crtbegin = "crtbeginT.o";
  8938. else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8939. crtbegin = "crtbeginS.o";
  8940. else
  8941. crtbegin = "crtbegin.o";
  8942. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8943. }
  8944. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8945. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8946. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  8947. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8948. Args.AddAllArgs(CmdArgs, options::OPT_s);
  8949. Args.AddAllArgs(CmdArgs, options::OPT_t);
  8950. Args.AddAllArgs(CmdArgs, options::OPT_r);
  8951. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8952. CmdArgs.push_back("--no-demangle");
  8953. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8954. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8955. // For PS4, we always want to pass libm, libstdc++ and libkernel
  8956. // libraries for both C and C++ compilations.
  8957. CmdArgs.push_back("-lkernel");
  8958. if (D.CCCIsCXX()) {
  8959. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8960. if (Args.hasArg(options::OPT_pg))
  8961. CmdArgs.push_back("-lm_p");
  8962. else
  8963. CmdArgs.push_back("-lm");
  8964. }
  8965. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  8966. // the default system libraries. Just mimic this for now.
  8967. if (Args.hasArg(options::OPT_pg))
  8968. CmdArgs.push_back("-lgcc_p");
  8969. else
  8970. CmdArgs.push_back("-lcompiler_rt");
  8971. if (Args.hasArg(options::OPT_static)) {
  8972. CmdArgs.push_back("-lstdc++");
  8973. } else if (Args.hasArg(options::OPT_pg)) {
  8974. CmdArgs.push_back("-lgcc_eh_p");
  8975. } else {
  8976. CmdArgs.push_back("--as-needed");
  8977. CmdArgs.push_back("-lstdc++");
  8978. CmdArgs.push_back("--no-as-needed");
  8979. }
  8980. if (Args.hasArg(options::OPT_pthread)) {
  8981. if (Args.hasArg(options::OPT_pg))
  8982. CmdArgs.push_back("-lpthread_p");
  8983. else
  8984. CmdArgs.push_back("-lpthread");
  8985. }
  8986. if (Args.hasArg(options::OPT_pg)) {
  8987. if (Args.hasArg(options::OPT_shared))
  8988. CmdArgs.push_back("-lc");
  8989. else {
  8990. if (Args.hasArg(options::OPT_static)) {
  8991. CmdArgs.push_back("--start-group");
  8992. CmdArgs.push_back("-lc_p");
  8993. CmdArgs.push_back("-lpthread_p");
  8994. CmdArgs.push_back("--end-group");
  8995. } else {
  8996. CmdArgs.push_back("-lc_p");
  8997. }
  8998. }
  8999. CmdArgs.push_back("-lgcc_p");
  9000. } else {
  9001. if (Args.hasArg(options::OPT_static)) {
  9002. CmdArgs.push_back("--start-group");
  9003. CmdArgs.push_back("-lc");
  9004. CmdArgs.push_back("-lpthread");
  9005. CmdArgs.push_back("--end-group");
  9006. } else {
  9007. CmdArgs.push_back("-lc");
  9008. }
  9009. CmdArgs.push_back("-lcompiler_rt");
  9010. }
  9011. if (Args.hasArg(options::OPT_static)) {
  9012. CmdArgs.push_back("-lstdc++");
  9013. } else if (Args.hasArg(options::OPT_pg)) {
  9014. CmdArgs.push_back("-lgcc_eh_p");
  9015. } else {
  9016. CmdArgs.push_back("--as-needed");
  9017. CmdArgs.push_back("-lstdc++");
  9018. CmdArgs.push_back("--no-as-needed");
  9019. }
  9020. }
  9021. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9022. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9023. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  9024. else
  9025. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  9026. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  9027. }
  9028. AddPS4ProfileRT(ToolChain, Args, CmdArgs);
  9029. const char *Exec =
  9030. #ifdef LLVM_ON_WIN32
  9031. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold.exe"));
  9032. #else
  9033. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  9034. #endif
  9035. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9036. }
  9037. void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
  9038. const InputInfo &Output,
  9039. const InputInfoList &Inputs,
  9040. const ArgList &Args,
  9041. const char *LinkingOutput) const {
  9042. const toolchains::FreeBSD &ToolChain =
  9043. static_cast<const toolchains::FreeBSD &>(getToolChain());
  9044. const Driver &D = ToolChain.getDriver();
  9045. bool PS4Linker;
  9046. StringRef LinkerOptName;
  9047. if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
  9048. LinkerOptName = A->getValue();
  9049. if (LinkerOptName != "ps4" && LinkerOptName != "gold")
  9050. D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
  9051. }
  9052. if (LinkerOptName == "gold")
  9053. PS4Linker = false;
  9054. else if (LinkerOptName == "ps4")
  9055. PS4Linker = true;
  9056. else
  9057. PS4Linker = !Args.hasArg(options::OPT_shared);
  9058. if (PS4Linker)
  9059. ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9060. else
  9061. ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9062. }