Tools.cpp 451 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322
  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/ScopedPrinter.h"
  43. #include "llvm/Support/TargetParser.h"
  44. #include "llvm/Support/YAMLParser.h"
  45. #ifdef LLVM_ON_UNIX
  46. #include <unistd.h> // For getuid().
  47. #endif
  48. using namespace clang::driver;
  49. using namespace clang::driver::tools;
  50. using namespace clang;
  51. using namespace llvm::opt;
  52. static void handleTargetFeaturesGroup(const ArgList &Args,
  53. std::vector<StringRef> &Features,
  54. OptSpecifier Group) {
  55. for (const Arg *A : Args.filtered(Group)) {
  56. StringRef Name = A->getOption().getName();
  57. A->claim();
  58. // Skip over "-m".
  59. assert(Name.startswith("m") && "Invalid feature name.");
  60. Name = Name.substr(1);
  61. bool IsNegative = Name.startswith("no-");
  62. if (IsNegative)
  63. Name = Name.substr(3);
  64. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  65. }
  66. }
  67. static const char *getSparcAsmModeForCPU(StringRef Name,
  68. const llvm::Triple &Triple) {
  69. if (Triple.getArch() == llvm::Triple::sparcv9) {
  70. return llvm::StringSwitch<const char *>(Name)
  71. .Case("niagara", "-Av9b")
  72. .Case("niagara2", "-Av9b")
  73. .Case("niagara3", "-Av9d")
  74. .Case("niagara4", "-Av9d")
  75. .Default("-Av9");
  76. } else {
  77. return llvm::StringSwitch<const char *>(Name)
  78. .Case("v8", "-Av8")
  79. .Case("supersparc", "-Av8")
  80. .Case("sparclite", "-Asparclite")
  81. .Case("f934", "-Asparclite")
  82. .Case("hypersparc", "-Av8")
  83. .Case("sparclite86x", "-Asparclite")
  84. .Case("sparclet", "-Asparclet")
  85. .Case("tsc701", "-Asparclet")
  86. .Case("v9", "-Av8plus")
  87. .Case("ultrasparc", "-Av8plus")
  88. .Case("ultrasparc3", "-Av8plus")
  89. .Case("niagara", "-Av8plusb")
  90. .Case("niagara2", "-Av8plusb")
  91. .Case("niagara3", "-Av8plusd")
  92. .Case("niagara4", "-Av8plusd")
  93. .Case("leon2", "-Av8")
  94. .Case("at697e", "-Av8")
  95. .Case("at697f", "-Av8")
  96. .Case("leon3", "-Av8")
  97. .Case("ut699", "-Av8")
  98. .Case("gr712rc", "-Av8")
  99. .Case("leon4", "-Av8")
  100. .Case("gr740", "-Av8")
  101. .Default("-Av8");
  102. }
  103. }
  104. static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
  105. if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
  106. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
  107. !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
  108. D.Diag(diag::err_drv_argument_only_allowed_with)
  109. << A->getBaseArg().getAsString(Args)
  110. << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
  111. }
  112. }
  113. }
  114. static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
  115. // In gcc, only ARM checks this, but it seems reasonable to check universally.
  116. if (Args.hasArg(options::OPT_static))
  117. if (const Arg *A =
  118. Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
  119. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  120. << "-static";
  121. }
  122. // Add backslashes to escape spaces and other backslashes.
  123. // This is used for the space-separated argument list specified with
  124. // the -dwarf-debug-flags option.
  125. static void EscapeSpacesAndBackslashes(const char *Arg,
  126. SmallVectorImpl<char> &Res) {
  127. for (; *Arg; ++Arg) {
  128. switch (*Arg) {
  129. default:
  130. break;
  131. case ' ':
  132. case '\\':
  133. Res.push_back('\\');
  134. break;
  135. }
  136. Res.push_back(*Arg);
  137. }
  138. }
  139. // Quote target names for inclusion in GNU Make dependency files.
  140. // Only the characters '$', '#', ' ', '\t' are quoted.
  141. static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
  142. for (unsigned i = 0, e = Target.size(); i != e; ++i) {
  143. switch (Target[i]) {
  144. case ' ':
  145. case '\t':
  146. // Escape the preceding backslashes
  147. for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
  148. Res.push_back('\\');
  149. // Escape the space/tab
  150. Res.push_back('\\');
  151. break;
  152. case '$':
  153. Res.push_back('$');
  154. break;
  155. case '#':
  156. Res.push_back('\\');
  157. break;
  158. default:
  159. break;
  160. }
  161. Res.push_back(Target[i]);
  162. }
  163. }
  164. static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
  165. const char *ArgName, const char *EnvVar) {
  166. const char *DirList = ::getenv(EnvVar);
  167. bool CombinedArg = false;
  168. if (!DirList)
  169. return; // Nothing to do.
  170. StringRef Name(ArgName);
  171. if (Name.equals("-I") || Name.equals("-L"))
  172. CombinedArg = true;
  173. StringRef Dirs(DirList);
  174. if (Dirs.empty()) // Empty string should not add '.'.
  175. return;
  176. StringRef::size_type Delim;
  177. while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
  178. if (Delim == 0) { // Leading colon.
  179. if (CombinedArg) {
  180. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  181. } else {
  182. CmdArgs.push_back(ArgName);
  183. CmdArgs.push_back(".");
  184. }
  185. } else {
  186. if (CombinedArg) {
  187. CmdArgs.push_back(
  188. Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
  189. } else {
  190. CmdArgs.push_back(ArgName);
  191. CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
  192. }
  193. }
  194. Dirs = Dirs.substr(Delim + 1);
  195. }
  196. if (Dirs.empty()) { // Trailing colon.
  197. if (CombinedArg) {
  198. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  199. } else {
  200. CmdArgs.push_back(ArgName);
  201. CmdArgs.push_back(".");
  202. }
  203. } else { // Add the last path.
  204. if (CombinedArg) {
  205. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
  206. } else {
  207. CmdArgs.push_back(ArgName);
  208. CmdArgs.push_back(Args.MakeArgString(Dirs));
  209. }
  210. }
  211. }
  212. static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
  213. const ArgList &Args, ArgStringList &CmdArgs,
  214. const JobAction &JA) {
  215. const Driver &D = TC.getDriver();
  216. // Add extra linker input arguments which are not treated as inputs
  217. // (constructed via -Xarch_).
  218. Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
  219. for (const auto &II : Inputs) {
  220. // If the current tool chain refers to an OpenMP offloading host, we should
  221. // ignore inputs that refer to OpenMP offloading devices - they will be
  222. // embedded according to a proper linker script.
  223. if (auto *IA = II.getAction())
  224. if (JA.isHostOffloading(Action::OFK_OpenMP) &&
  225. IA->isDeviceOffloading(Action::OFK_OpenMP))
  226. continue;
  227. if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
  228. // Don't try to pass LLVM inputs unless we have native support.
  229. D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
  230. // Add filenames immediately.
  231. if (II.isFilename()) {
  232. CmdArgs.push_back(II.getFilename());
  233. continue;
  234. }
  235. // Otherwise, this is a linker input argument.
  236. const Arg &A = II.getInputArg();
  237. // Handle reserved library options.
  238. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
  239. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  240. else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
  241. TC.AddCCKextLibArgs(Args, CmdArgs);
  242. else if (A.getOption().matches(options::OPT_z)) {
  243. // Pass -z prefix for gcc linker compatibility.
  244. A.claim();
  245. A.render(Args, CmdArgs);
  246. } else {
  247. A.renderAsInput(Args, CmdArgs);
  248. }
  249. }
  250. // LIBRARY_PATH - included following the user specified library paths.
  251. // and only supported on native toolchains.
  252. if (!TC.isCrossCompiling())
  253. addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
  254. }
  255. /// Add OpenMP linker script arguments at the end of the argument list so that
  256. /// the fat binary is built by embedding each of the device images into the
  257. /// host. The linker script also defines a few symbols required by the code
  258. /// generation so that the images can be easily retrieved at runtime by the
  259. /// offloading library. This should be used only in tool chains that support
  260. /// linker scripts.
  261. static void AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
  262. const InputInfo &Output,
  263. const InputInfoList &Inputs,
  264. const ArgList &Args, ArgStringList &CmdArgs,
  265. const JobAction &JA) {
  266. // If this is not an OpenMP host toolchain, we don't need to do anything.
  267. if (!JA.isHostOffloading(Action::OFK_OpenMP))
  268. return;
  269. // Create temporary linker script. Keep it if save-temps is enabled.
  270. const char *LKS;
  271. SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
  272. if (C.getDriver().isSaveTempsEnabled()) {
  273. llvm::sys::path::replace_extension(Name, "lk");
  274. LKS = C.getArgs().MakeArgString(Name.c_str());
  275. } else {
  276. llvm::sys::path::replace_extension(Name, "");
  277. Name = C.getDriver().GetTemporaryPath(Name, "lk");
  278. LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
  279. }
  280. // Add linker script option to the command.
  281. CmdArgs.push_back("-T");
  282. CmdArgs.push_back(LKS);
  283. // Create a buffer to write the contents of the linker script.
  284. std::string LksBuffer;
  285. llvm::raw_string_ostream LksStream(LksBuffer);
  286. // Get the OpenMP offload tool chains so that we can extract the triple
  287. // associated with each device input.
  288. auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
  289. assert(OpenMPToolChains.first != OpenMPToolChains.second &&
  290. "No OpenMP toolchains??");
  291. // Track the input file name and device triple in order to build the script,
  292. // inserting binaries in the designated sections.
  293. SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
  294. // Add commands to embed target binaries. We ensure that each section and
  295. // image is 16-byte aligned. This is not mandatory, but increases the
  296. // likelihood of data to be aligned with a cache block in several main host
  297. // machines.
  298. LksStream << "/*\n";
  299. LksStream << " OpenMP Offload Linker Script\n";
  300. LksStream << " *** Automatically generated by Clang ***\n";
  301. LksStream << "*/\n";
  302. LksStream << "TARGET(binary)\n";
  303. auto DTC = OpenMPToolChains.first;
  304. for (auto &II : Inputs) {
  305. const Action *A = II.getAction();
  306. // Is this a device linking action?
  307. if (A && isa<LinkJobAction>(A) &&
  308. A->isDeviceOffloading(Action::OFK_OpenMP)) {
  309. assert(DTC != OpenMPToolChains.second &&
  310. "More device inputs than device toolchains??");
  311. InputBinaryInfo.push_back(std::make_pair(
  312. DTC->second->getTriple().normalize(), II.getFilename()));
  313. ++DTC;
  314. LksStream << "INPUT(" << II.getFilename() << ")\n";
  315. }
  316. }
  317. assert(DTC == OpenMPToolChains.second &&
  318. "Less device inputs than device toolchains??");
  319. LksStream << "SECTIONS\n";
  320. LksStream << "{\n";
  321. LksStream << " .omp_offloading :\n";
  322. LksStream << " ALIGN(0x10)\n";
  323. LksStream << " {\n";
  324. for (auto &BI : InputBinaryInfo) {
  325. LksStream << " . = ALIGN(0x10);\n";
  326. LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
  327. << " = .);\n";
  328. LksStream << " " << BI.second << "\n";
  329. LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
  330. << " = .);\n";
  331. }
  332. LksStream << " }\n";
  333. // Add commands to define host entries begin and end. We use 1-byte subalign
  334. // so that the linker does not add any padding and the elements in this
  335. // section form an array.
  336. LksStream << " .omp_offloading.entries :\n";
  337. LksStream << " ALIGN(0x10)\n";
  338. LksStream << " SUBALIGN(0x01)\n";
  339. LksStream << " {\n";
  340. LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
  341. LksStream << " *(.omp_offloading.entries)\n";
  342. LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
  343. LksStream << " }\n";
  344. LksStream << "}\n";
  345. LksStream << "INSERT BEFORE .data\n";
  346. LksStream.flush();
  347. // Dump the contents of the linker script if the user requested that. We
  348. // support this option to enable testing of behavior with -###.
  349. if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
  350. llvm::errs() << LksBuffer;
  351. // If this is a dry run, do not create the linker script file.
  352. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
  353. return;
  354. // Open script file and write the contents.
  355. std::error_code EC;
  356. llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
  357. if (EC) {
  358. C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  359. return;
  360. }
  361. Lksf << LksBuffer;
  362. }
  363. /// \brief Determine whether Objective-C automated reference counting is
  364. /// enabled.
  365. static bool isObjCAutoRefCount(const ArgList &Args) {
  366. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  367. }
  368. /// \brief Determine whether we are linking the ObjC runtime.
  369. static bool isObjCRuntimeLinked(const ArgList &Args) {
  370. if (isObjCAutoRefCount(Args)) {
  371. Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
  372. return true;
  373. }
  374. return Args.hasArg(options::OPT_fobjc_link_runtime);
  375. }
  376. static bool forwardToGCC(const Option &O) {
  377. // Don't forward inputs from the original command line. They are added from
  378. // InputInfoList.
  379. return O.getKind() != Option::InputClass &&
  380. !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
  381. }
  382. /// Apply \a Work on the current tool chain \a RegularToolChain and any other
  383. /// offloading tool chain that is associated with the current action \a JA.
  384. static void
  385. forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
  386. const ToolChain &RegularToolChain,
  387. llvm::function_ref<void(const ToolChain &)> Work) {
  388. // Apply Work on the current/regular tool chain.
  389. Work(RegularToolChain);
  390. // Apply Work on all the offloading tool chains associated with the current
  391. // action.
  392. if (JA.isHostOffloading(Action::OFK_Cuda))
  393. Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
  394. else if (JA.isDeviceOffloading(Action::OFK_Cuda))
  395. Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
  396. //
  397. // TODO: Add support for other offloading programming models here.
  398. //
  399. }
  400. void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
  401. const Driver &D, const ArgList &Args,
  402. ArgStringList &CmdArgs,
  403. const InputInfo &Output,
  404. const InputInfoList &Inputs) const {
  405. Arg *A;
  406. const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
  407. CheckPreprocessingOptions(D, Args);
  408. Args.AddLastArg(CmdArgs, options::OPT_C);
  409. Args.AddLastArg(CmdArgs, options::OPT_CC);
  410. // Handle dependency file generation.
  411. if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
  412. (A = Args.getLastArg(options::OPT_MD)) ||
  413. (A = Args.getLastArg(options::OPT_MMD))) {
  414. // Determine the output location.
  415. const char *DepFile;
  416. if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
  417. DepFile = MF->getValue();
  418. C.addFailureResultFile(DepFile, &JA);
  419. } else if (Output.getType() == types::TY_Dependencies) {
  420. DepFile = Output.getFilename();
  421. } else if (A->getOption().matches(options::OPT_M) ||
  422. A->getOption().matches(options::OPT_MM)) {
  423. DepFile = "-";
  424. } else {
  425. DepFile = getDependencyFileName(Args, Inputs);
  426. C.addFailureResultFile(DepFile, &JA);
  427. }
  428. CmdArgs.push_back("-dependency-file");
  429. CmdArgs.push_back(DepFile);
  430. // Add a default target if one wasn't specified.
  431. if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
  432. const char *DepTarget;
  433. // If user provided -o, that is the dependency target, except
  434. // when we are only generating a dependency file.
  435. Arg *OutputOpt = Args.getLastArg(options::OPT_o);
  436. if (OutputOpt && Output.getType() != types::TY_Dependencies) {
  437. DepTarget = OutputOpt->getValue();
  438. } else {
  439. // Otherwise derive from the base input.
  440. //
  441. // FIXME: This should use the computed output file location.
  442. SmallString<128> P(Inputs[0].getBaseInput());
  443. llvm::sys::path::replace_extension(P, "o");
  444. DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
  445. }
  446. CmdArgs.push_back("-MT");
  447. SmallString<128> Quoted;
  448. QuoteTarget(DepTarget, Quoted);
  449. CmdArgs.push_back(Args.MakeArgString(Quoted));
  450. }
  451. if (A->getOption().matches(options::OPT_M) ||
  452. A->getOption().matches(options::OPT_MD))
  453. CmdArgs.push_back("-sys-header-deps");
  454. if ((isa<PrecompileJobAction>(JA) &&
  455. !Args.hasArg(options::OPT_fno_module_file_deps)) ||
  456. Args.hasArg(options::OPT_fmodule_file_deps))
  457. CmdArgs.push_back("-module-file-deps");
  458. }
  459. if (Args.hasArg(options::OPT_MG)) {
  460. if (!A || A->getOption().matches(options::OPT_MD) ||
  461. A->getOption().matches(options::OPT_MMD))
  462. D.Diag(diag::err_drv_mg_requires_m_or_mm);
  463. CmdArgs.push_back("-MG");
  464. }
  465. Args.AddLastArg(CmdArgs, options::OPT_MP);
  466. Args.AddLastArg(CmdArgs, options::OPT_MV);
  467. // Convert all -MQ <target> args to -MT <quoted target>
  468. for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
  469. A->claim();
  470. if (A->getOption().matches(options::OPT_MQ)) {
  471. CmdArgs.push_back("-MT");
  472. SmallString<128> Quoted;
  473. QuoteTarget(A->getValue(), Quoted);
  474. CmdArgs.push_back(Args.MakeArgString(Quoted));
  475. // -MT flag - no change
  476. } else {
  477. A->render(Args, CmdArgs);
  478. }
  479. }
  480. // Add offload include arguments specific for CUDA. This must happen before
  481. // we -I or -include anything else, because we must pick up the CUDA headers
  482. // from the particular CUDA installation, rather than from e.g.
  483. // /usr/local/include.
  484. if (JA.isOffloading(Action::OFK_Cuda))
  485. getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
  486. // Add -i* options, and automatically translate to
  487. // -include-pch/-include-pth for transparent PCH support. It's
  488. // wonky, but we include looking for .gch so we can support seamless
  489. // replacement into a build system already set up to be generating
  490. // .gch files.
  491. int YcIndex = -1, YuIndex = -1;
  492. {
  493. int AI = -1;
  494. const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  495. const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  496. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  497. // Walk the whole i_Group and skip non "-include" flags so that the index
  498. // here matches the index in the next loop below.
  499. ++AI;
  500. if (!A->getOption().matches(options::OPT_include))
  501. continue;
  502. if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
  503. YcIndex = AI;
  504. if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
  505. YuIndex = AI;
  506. }
  507. }
  508. if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
  509. Driver::InputList Inputs;
  510. D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
  511. assert(Inputs.size() == 1 && "Need one input when building pch");
  512. CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
  513. Inputs[0].second->getValue()));
  514. }
  515. bool RenderedImplicitInclude = false;
  516. int AI = -1;
  517. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  518. ++AI;
  519. if (getToolChain().getDriver().IsCLMode() &&
  520. A->getOption().matches(options::OPT_include)) {
  521. // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
  522. // include is compiled into foo.h, and everything after goes into
  523. // the .obj file. /Yufoo.h means that all includes prior to and including
  524. // foo.h are completely skipped and replaced with a use of the pch file
  525. // for foo.h. (Each flag can have at most one value, multiple /Yc flags
  526. // just mean that the last one wins.) If /Yc and /Yu are both present
  527. // and refer to the same file, /Yc wins.
  528. // Note that OPT__SLASH_FI gets mapped to OPT_include.
  529. // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
  530. // cl.exe seems to support both flags with different values, but that
  531. // seems strange (which flag does /Fp now refer to?), so don't implement
  532. // that until someone needs it.
  533. int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
  534. if (PchIndex != -1) {
  535. if (isa<PrecompileJobAction>(JA)) {
  536. // When building the pch, skip all includes after the pch.
  537. assert(YcIndex != -1 && PchIndex == YcIndex);
  538. if (AI >= YcIndex)
  539. continue;
  540. } else {
  541. // When using the pch, skip all includes prior to the pch.
  542. if (AI < PchIndex) {
  543. A->claim();
  544. continue;
  545. }
  546. if (AI == PchIndex) {
  547. A->claim();
  548. CmdArgs.push_back("-include-pch");
  549. CmdArgs.push_back(
  550. Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
  551. continue;
  552. }
  553. }
  554. }
  555. } else if (A->getOption().matches(options::OPT_include)) {
  556. // Handling of gcc-style gch precompiled headers.
  557. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  558. RenderedImplicitInclude = true;
  559. // Use PCH if the user requested it.
  560. bool UsePCH = D.CCCUsePCH;
  561. bool FoundPTH = false;
  562. bool FoundPCH = false;
  563. SmallString<128> P(A->getValue());
  564. // We want the files to have a name like foo.h.pch. Add a dummy extension
  565. // so that replace_extension does the right thing.
  566. P += ".dummy";
  567. if (UsePCH) {
  568. llvm::sys::path::replace_extension(P, "pch");
  569. if (llvm::sys::fs::exists(P))
  570. FoundPCH = true;
  571. }
  572. if (!FoundPCH) {
  573. llvm::sys::path::replace_extension(P, "pth");
  574. if (llvm::sys::fs::exists(P))
  575. FoundPTH = true;
  576. }
  577. if (!FoundPCH && !FoundPTH) {
  578. llvm::sys::path::replace_extension(P, "gch");
  579. if (llvm::sys::fs::exists(P)) {
  580. FoundPCH = UsePCH;
  581. FoundPTH = !UsePCH;
  582. }
  583. }
  584. if (FoundPCH || FoundPTH) {
  585. if (IsFirstImplicitInclude) {
  586. A->claim();
  587. if (UsePCH)
  588. CmdArgs.push_back("-include-pch");
  589. else
  590. CmdArgs.push_back("-include-pth");
  591. CmdArgs.push_back(Args.MakeArgString(P));
  592. continue;
  593. } else {
  594. // Ignore the PCH if not first on command line and emit warning.
  595. D.Diag(diag::warn_drv_pch_not_first_include) << P
  596. << A->getAsString(Args);
  597. }
  598. }
  599. } else if (A->getOption().matches(options::OPT_isystem_after)) {
  600. // Handling of paths which must come late. These entries are handled by
  601. // the toolchain itself after the resource dir is inserted in the right
  602. // search order.
  603. // Do not claim the argument so that the use of the argument does not
  604. // silently go unnoticed on toolchains which do not honour the option.
  605. continue;
  606. }
  607. // Not translated, render as usual.
  608. A->claim();
  609. A->render(Args, CmdArgs);
  610. }
  611. Args.AddAllArgs(CmdArgs,
  612. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  613. options::OPT_F, options::OPT_index_header_map});
  614. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  615. // FIXME: There is a very unfortunate problem here, some troubled
  616. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  617. // really support that we would have to parse and then translate
  618. // those options. :(
  619. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  620. options::OPT_Xpreprocessor);
  621. // -I- is a deprecated GCC feature, reject it.
  622. if (Arg *A = Args.getLastArg(options::OPT_I_))
  623. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  624. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  625. // -isysroot to the CC1 invocation.
  626. StringRef sysroot = C.getSysRoot();
  627. if (sysroot != "") {
  628. if (!Args.hasArg(options::OPT_isysroot)) {
  629. CmdArgs.push_back("-isysroot");
  630. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  631. }
  632. }
  633. // Parse additional include paths from environment variables.
  634. // FIXME: We should probably sink the logic for handling these from the
  635. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  636. // CPATH - included following the user specified includes (but prior to
  637. // builtin and standard includes).
  638. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  639. // C_INCLUDE_PATH - system includes enabled when compiling C.
  640. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  641. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  642. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  643. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  644. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  645. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  646. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  647. // While adding the include arguments, we also attempt to retrieve the
  648. // arguments of related offloading toolchains or arguments that are specific
  649. // of an offloading programming model.
  650. // Add C++ include arguments, if needed.
  651. if (types::isCXX(Inputs[0].getType()))
  652. forAllAssociatedToolChains(C, JA, getToolChain(),
  653. [&Args, &CmdArgs](const ToolChain &TC) {
  654. TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  655. });
  656. // Add system include arguments for all targets but IAMCU.
  657. if (!IsIAMCU)
  658. forAllAssociatedToolChains(C, JA, getToolChain(),
  659. [&Args, &CmdArgs](const ToolChain &TC) {
  660. TC.AddClangSystemIncludeArgs(Args, CmdArgs);
  661. });
  662. else {
  663. // For IAMCU add special include arguments.
  664. getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
  665. }
  666. }
  667. // FIXME: Move to target hook.
  668. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  669. switch (Triple.getArch()) {
  670. default:
  671. return true;
  672. case llvm::Triple::aarch64:
  673. case llvm::Triple::aarch64_be:
  674. case llvm::Triple::arm:
  675. case llvm::Triple::armeb:
  676. case llvm::Triple::thumb:
  677. case llvm::Triple::thumbeb:
  678. if (Triple.isOSDarwin() || Triple.isOSWindows())
  679. return true;
  680. return false;
  681. case llvm::Triple::ppc:
  682. case llvm::Triple::ppc64:
  683. if (Triple.isOSDarwin())
  684. return true;
  685. return false;
  686. case llvm::Triple::hexagon:
  687. case llvm::Triple::ppc64le:
  688. case llvm::Triple::systemz:
  689. case llvm::Triple::xcore:
  690. return false;
  691. }
  692. }
  693. static bool isNoCommonDefault(const llvm::Triple &Triple) {
  694. switch (Triple.getArch()) {
  695. default:
  696. return false;
  697. case llvm::Triple::xcore:
  698. case llvm::Triple::wasm32:
  699. case llvm::Triple::wasm64:
  700. return true;
  701. }
  702. }
  703. // ARM tools start.
  704. // Get SubArch (vN).
  705. static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
  706. llvm::StringRef Arch = Triple.getArchName();
  707. return llvm::ARM::parseArchVersion(Arch);
  708. }
  709. // True if M-profile.
  710. static bool isARMMProfile(const llvm::Triple &Triple) {
  711. llvm::StringRef Arch = Triple.getArchName();
  712. unsigned Profile = llvm::ARM::parseArchProfile(Arch);
  713. return Profile == llvm::ARM::PK_M;
  714. }
  715. // Get Arch/CPU from args.
  716. static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
  717. llvm::StringRef &CPU, bool FromAs = false) {
  718. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  719. CPU = A->getValue();
  720. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  721. Arch = A->getValue();
  722. if (!FromAs)
  723. return;
  724. for (const Arg *A :
  725. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  726. StringRef Value = A->getValue();
  727. if (Value.startswith("-mcpu="))
  728. CPU = Value.substr(6);
  729. if (Value.startswith("-march="))
  730. Arch = Value.substr(7);
  731. }
  732. }
  733. // Handle -mhwdiv=.
  734. // FIXME: Use ARMTargetParser.
  735. static void getARMHWDivFeatures(const Driver &D, const Arg *A,
  736. const ArgList &Args, StringRef HWDiv,
  737. std::vector<StringRef> &Features) {
  738. unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
  739. if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
  740. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  741. }
  742. // Handle -mfpu=.
  743. static void getARMFPUFeatures(const Driver &D, const Arg *A,
  744. const ArgList &Args, StringRef FPU,
  745. std::vector<StringRef> &Features) {
  746. unsigned FPUID = llvm::ARM::parseFPU(FPU);
  747. if (!llvm::ARM::getFPUFeatures(FPUID, Features))
  748. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  749. }
  750. // Decode ARM features from string like +[no]featureA+[no]featureB+...
  751. static bool DecodeARMFeatures(const Driver &D, StringRef text,
  752. std::vector<StringRef> &Features) {
  753. SmallVector<StringRef, 8> Split;
  754. text.split(Split, StringRef("+"), -1, false);
  755. for (StringRef Feature : Split) {
  756. StringRef FeatureName = llvm::ARM::getArchExtFeature(Feature);
  757. if (!FeatureName.empty())
  758. Features.push_back(FeatureName);
  759. else
  760. return false;
  761. }
  762. return true;
  763. }
  764. // Check if -march is valid by checking if it can be canonicalised and parsed.
  765. // getARMArch is used here instead of just checking the -march value in order
  766. // to handle -march=native correctly.
  767. static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
  768. llvm::StringRef ArchName,
  769. std::vector<StringRef> &Features,
  770. const llvm::Triple &Triple) {
  771. std::pair<StringRef, StringRef> Split = ArchName.split("+");
  772. std::string MArch = arm::getARMArch(ArchName, Triple);
  773. if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
  774. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  775. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  776. }
  777. // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
  778. static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
  779. llvm::StringRef CPUName, llvm::StringRef ArchName,
  780. std::vector<StringRef> &Features,
  781. const llvm::Triple &Triple) {
  782. std::pair<StringRef, StringRef> Split = CPUName.split("+");
  783. std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
  784. if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
  785. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  786. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  787. }
  788. static bool useAAPCSForMachO(const llvm::Triple &T) {
  789. // The backend is hardwired to assume AAPCS for M-class processors, ensure
  790. // the frontend matches that.
  791. return T.getEnvironment() == llvm::Triple::EABI ||
  792. T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
  793. }
  794. // Select the float ABI as determined by -msoft-float, -mhard-float, and
  795. // -mfloat-abi=.
  796. arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
  797. const Driver &D = TC.getDriver();
  798. const llvm::Triple &Triple = TC.getEffectiveTriple();
  799. auto SubArch = getARMSubArchVersionNumber(Triple);
  800. arm::FloatABI ABI = FloatABI::Invalid;
  801. if (Arg *A =
  802. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  803. options::OPT_mfloat_abi_EQ)) {
  804. if (A->getOption().matches(options::OPT_msoft_float)) {
  805. ABI = FloatABI::Soft;
  806. } else if (A->getOption().matches(options::OPT_mhard_float)) {
  807. ABI = FloatABI::Hard;
  808. } else {
  809. ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
  810. .Case("soft", FloatABI::Soft)
  811. .Case("softfp", FloatABI::SoftFP)
  812. .Case("hard", FloatABI::Hard)
  813. .Default(FloatABI::Invalid);
  814. if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  815. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  816. ABI = FloatABI::Soft;
  817. }
  818. }
  819. // It is incorrect to select hard float ABI on MachO platforms if the ABI is
  820. // "apcs-gnu".
  821. if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
  822. ABI == FloatABI::Hard) {
  823. D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
  824. << Triple.getArchName();
  825. }
  826. }
  827. // If unspecified, choose the default based on the platform.
  828. if (ABI == FloatABI::Invalid) {
  829. switch (Triple.getOS()) {
  830. case llvm::Triple::Darwin:
  831. case llvm::Triple::MacOSX:
  832. case llvm::Triple::IOS:
  833. case llvm::Triple::TvOS: {
  834. // Darwin defaults to "softfp" for v6 and v7.
  835. ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  836. ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
  837. break;
  838. }
  839. case llvm::Triple::WatchOS:
  840. ABI = FloatABI::Hard;
  841. break;
  842. // FIXME: this is invalid for WindowsCE
  843. case llvm::Triple::Win32:
  844. ABI = FloatABI::Hard;
  845. break;
  846. case llvm::Triple::FreeBSD:
  847. switch (Triple.getEnvironment()) {
  848. case llvm::Triple::GNUEABIHF:
  849. ABI = FloatABI::Hard;
  850. break;
  851. default:
  852. // FreeBSD defaults to soft float
  853. ABI = FloatABI::Soft;
  854. break;
  855. }
  856. break;
  857. default:
  858. switch (Triple.getEnvironment()) {
  859. case llvm::Triple::GNUEABIHF:
  860. case llvm::Triple::MuslEABIHF:
  861. case llvm::Triple::EABIHF:
  862. ABI = FloatABI::Hard;
  863. break;
  864. case llvm::Triple::GNUEABI:
  865. case llvm::Triple::MuslEABI:
  866. case llvm::Triple::EABI:
  867. // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
  868. ABI = FloatABI::SoftFP;
  869. break;
  870. case llvm::Triple::Android:
  871. ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  872. break;
  873. default:
  874. // Assume "soft", but warn the user we are guessing.
  875. if (Triple.isOSBinFormatMachO() &&
  876. Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
  877. ABI = FloatABI::Hard;
  878. else
  879. ABI = FloatABI::Soft;
  880. if (Triple.getOS() != llvm::Triple::UnknownOS ||
  881. !Triple.isOSBinFormatMachO())
  882. D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
  883. break;
  884. }
  885. }
  886. }
  887. assert(ABI != FloatABI::Invalid && "must select an ABI");
  888. return ABI;
  889. }
  890. static void getARMTargetFeatures(const ToolChain &TC,
  891. const llvm::Triple &Triple,
  892. const ArgList &Args,
  893. ArgStringList &CmdArgs,
  894. std::vector<StringRef> &Features,
  895. bool ForAS) {
  896. const Driver &D = TC.getDriver();
  897. bool KernelOrKext =
  898. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  899. arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
  900. const Arg *WaCPU = nullptr, *WaFPU = nullptr;
  901. const Arg *WaHDiv = nullptr, *WaArch = nullptr;
  902. if (!ForAS) {
  903. // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
  904. // yet (it uses the -mfloat-abi and -msoft-float options), and it is
  905. // stripped out by the ARM target. We should probably pass this a new
  906. // -target-option, which is handled by the -cc1/-cc1as invocation.
  907. //
  908. // FIXME2: For consistency, it would be ideal if we set up the target
  909. // machine state the same when using the frontend or the assembler. We don't
  910. // currently do that for the assembler, we pass the options directly to the
  911. // backend and never even instantiate the frontend TargetInfo. If we did,
  912. // and used its handleTargetFeatures hook, then we could ensure the
  913. // assembler and the frontend behave the same.
  914. // Use software floating point operations?
  915. if (ABI == arm::FloatABI::Soft)
  916. Features.push_back("+soft-float");
  917. // Use software floating point argument passing?
  918. if (ABI != arm::FloatABI::Hard)
  919. Features.push_back("+soft-float-abi");
  920. } else {
  921. // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
  922. // to the assembler correctly.
  923. for (const Arg *A :
  924. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  925. StringRef Value = A->getValue();
  926. if (Value.startswith("-mfpu=")) {
  927. WaFPU = A;
  928. } else if (Value.startswith("-mcpu=")) {
  929. WaCPU = A;
  930. } else if (Value.startswith("-mhwdiv=")) {
  931. WaHDiv = A;
  932. } else if (Value.startswith("-march=")) {
  933. WaArch = A;
  934. }
  935. }
  936. }
  937. // Check -march. ClangAs gives preference to -Wa,-march=.
  938. const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
  939. StringRef ArchName;
  940. if (WaArch) {
  941. if (ArchArg)
  942. D.Diag(clang::diag::warn_drv_unused_argument)
  943. << ArchArg->getAsString(Args);
  944. ArchName = StringRef(WaArch->getValue()).substr(7);
  945. checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
  946. // FIXME: Set Arch.
  947. D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
  948. } else if (ArchArg) {
  949. ArchName = ArchArg->getValue();
  950. checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
  951. }
  952. // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
  953. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  954. StringRef CPUName;
  955. if (WaCPU) {
  956. if (CPUArg)
  957. D.Diag(clang::diag::warn_drv_unused_argument)
  958. << CPUArg->getAsString(Args);
  959. CPUName = StringRef(WaCPU->getValue()).substr(6);
  960. checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
  961. } else if (CPUArg) {
  962. CPUName = CPUArg->getValue();
  963. checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
  964. }
  965. // Add CPU features for generic CPUs
  966. if (CPUName == "native") {
  967. llvm::StringMap<bool> HostFeatures;
  968. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  969. for (auto &F : HostFeatures)
  970. Features.push_back(
  971. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  972. }
  973. // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
  974. const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
  975. if (WaFPU) {
  976. if (FPUArg)
  977. D.Diag(clang::diag::warn_drv_unused_argument)
  978. << FPUArg->getAsString(Args);
  979. getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
  980. Features);
  981. } else if (FPUArg) {
  982. getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
  983. }
  984. // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
  985. const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
  986. if (WaHDiv) {
  987. if (HDivArg)
  988. D.Diag(clang::diag::warn_drv_unused_argument)
  989. << HDivArg->getAsString(Args);
  990. getARMHWDivFeatures(D, WaHDiv, Args,
  991. StringRef(WaHDiv->getValue()).substr(8), Features);
  992. } else if (HDivArg)
  993. getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
  994. // Setting -msoft-float effectively disables NEON because of the GCC
  995. // implementation, although the same isn't true of VFP or VFP3.
  996. if (ABI == arm::FloatABI::Soft) {
  997. Features.push_back("-neon");
  998. // Also need to explicitly disable features which imply NEON.
  999. Features.push_back("-crypto");
  1000. }
  1001. // En/disable crc code generation.
  1002. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  1003. if (A->getOption().matches(options::OPT_mcrc))
  1004. Features.push_back("+crc");
  1005. else
  1006. Features.push_back("-crc");
  1007. }
  1008. // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
  1009. // neither options are specified, see if we are compiling for kernel/kext and
  1010. // decide whether to pass "+long-calls" based on the OS and its version.
  1011. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  1012. options::OPT_mno_long_calls)) {
  1013. if (A->getOption().matches(options::OPT_mlong_calls))
  1014. Features.push_back("+long-calls");
  1015. } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  1016. !Triple.isWatchOS()) {
  1017. Features.push_back("+long-calls");
  1018. }
  1019. // Generate execute-only output (no data access to code sections).
  1020. // Supported only on ARMv6T2 and ARMv7 and above.
  1021. // Cannot be combined with -mno-movt or -mlong-calls
  1022. if (Arg *A = Args.getLastArg(options::OPT_mexecute_only, options::OPT_mno_execute_only)) {
  1023. if (A->getOption().matches(options::OPT_mexecute_only)) {
  1024. if (getARMSubArchVersionNumber(Triple) < 7 &&
  1025. llvm::ARM::parseArch(Triple.getArchName()) != llvm::ARM::AK_ARMV6T2)
  1026. D.Diag(diag::err_target_unsupported_execute_only) << Triple.getArchName();
  1027. else if (Arg *B = Args.getLastArg(options::OPT_mno_movt))
  1028. D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
  1029. // Long calls create constant pool entries and have not yet been fixed up
  1030. // to play nicely with execute-only. Hence, they cannot be used in
  1031. // execute-only code for now
  1032. else if (Arg *B = Args.getLastArg(options::OPT_mlong_calls, options::OPT_mno_long_calls)) {
  1033. if (B->getOption().matches(options::OPT_mlong_calls))
  1034. D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
  1035. }
  1036. CmdArgs.push_back("-backend-option");
  1037. CmdArgs.push_back("-arm-execute-only");
  1038. }
  1039. }
  1040. // Kernel code has more strict alignment requirements.
  1041. if (KernelOrKext)
  1042. Features.push_back("+strict-align");
  1043. else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  1044. options::OPT_munaligned_access)) {
  1045. if (A->getOption().matches(options::OPT_munaligned_access)) {
  1046. // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
  1047. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  1048. D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
  1049. // v8M Baseline follows on from v6M, so doesn't support unaligned memory
  1050. // access either.
  1051. else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
  1052. D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
  1053. } else
  1054. Features.push_back("+strict-align");
  1055. } else {
  1056. // Assume pre-ARMv6 doesn't support unaligned accesses.
  1057. //
  1058. // ARMv6 may or may not support unaligned accesses depending on the
  1059. // SCTLR.U bit, which is architecture-specific. We assume ARMv6
  1060. // Darwin and NetBSD targets support unaligned accesses, and others don't.
  1061. //
  1062. // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
  1063. // which raises an alignment fault on unaligned accesses. Linux
  1064. // defaults this bit to 0 and handles it as a system-wide (not
  1065. // per-process) setting. It is therefore safe to assume that ARMv7+
  1066. // Linux targets support unaligned accesses. The same goes for NaCl.
  1067. //
  1068. // The above behavior is consistent with GCC.
  1069. int VersionNum = getARMSubArchVersionNumber(Triple);
  1070. if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
  1071. if (VersionNum < 6 ||
  1072. Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  1073. Features.push_back("+strict-align");
  1074. } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
  1075. if (VersionNum < 7)
  1076. Features.push_back("+strict-align");
  1077. } else
  1078. Features.push_back("+strict-align");
  1079. }
  1080. // llvm does not support reserving registers in general. There is support
  1081. // for reserving r9 on ARM though (defined as a platform-specific register
  1082. // in ARM EABI).
  1083. if (Args.hasArg(options::OPT_ffixed_r9))
  1084. Features.push_back("+reserve-r9");
  1085. // The kext linker doesn't know how to deal with movw/movt.
  1086. if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
  1087. Features.push_back("+no-movt");
  1088. }
  1089. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  1090. ArgStringList &CmdArgs, bool KernelOrKext) const {
  1091. // Select the ABI to use.
  1092. // FIXME: Support -meabi.
  1093. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  1094. const char *ABIName = nullptr;
  1095. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  1096. ABIName = A->getValue();
  1097. } else if (Triple.isOSBinFormatMachO()) {
  1098. if (useAAPCSForMachO(Triple)) {
  1099. ABIName = "aapcs";
  1100. } else if (Triple.isWatchABI()) {
  1101. ABIName = "aapcs16";
  1102. } else {
  1103. ABIName = "apcs-gnu";
  1104. }
  1105. } else if (Triple.isOSWindows()) {
  1106. // FIXME: this is invalid for WindowsCE
  1107. ABIName = "aapcs";
  1108. } else {
  1109. // Select the default based on the platform.
  1110. switch (Triple.getEnvironment()) {
  1111. case llvm::Triple::Android:
  1112. case llvm::Triple::GNUEABI:
  1113. case llvm::Triple::GNUEABIHF:
  1114. case llvm::Triple::MuslEABI:
  1115. case llvm::Triple::MuslEABIHF:
  1116. ABIName = "aapcs-linux";
  1117. break;
  1118. case llvm::Triple::EABIHF:
  1119. case llvm::Triple::EABI:
  1120. ABIName = "aapcs";
  1121. break;
  1122. default:
  1123. if (Triple.getOS() == llvm::Triple::NetBSD)
  1124. ABIName = "apcs-gnu";
  1125. else
  1126. ABIName = "aapcs";
  1127. break;
  1128. }
  1129. }
  1130. CmdArgs.push_back("-target-abi");
  1131. CmdArgs.push_back(ABIName);
  1132. // Determine floating point ABI from the options & target defaults.
  1133. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  1134. if (ABI == arm::FloatABI::Soft) {
  1135. // Floating point operations and argument passing are soft.
  1136. // FIXME: This changes CPP defines, we need -target-soft-float.
  1137. CmdArgs.push_back("-msoft-float");
  1138. CmdArgs.push_back("-mfloat-abi");
  1139. CmdArgs.push_back("soft");
  1140. } else if (ABI == arm::FloatABI::SoftFP) {
  1141. // Floating point operations are hard, but argument passing is soft.
  1142. CmdArgs.push_back("-mfloat-abi");
  1143. CmdArgs.push_back("soft");
  1144. } else {
  1145. // Floating point operations and argument passing are hard.
  1146. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  1147. CmdArgs.push_back("-mfloat-abi");
  1148. CmdArgs.push_back("hard");
  1149. }
  1150. // Forward the -mglobal-merge option for explicit control over the pass.
  1151. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1152. options::OPT_mno_global_merge)) {
  1153. CmdArgs.push_back("-backend-option");
  1154. if (A->getOption().matches(options::OPT_mno_global_merge))
  1155. CmdArgs.push_back("-arm-global-merge=false");
  1156. else
  1157. CmdArgs.push_back("-arm-global-merge=true");
  1158. }
  1159. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1160. options::OPT_mno_implicit_float, true))
  1161. CmdArgs.push_back("-no-implicit-float");
  1162. }
  1163. // ARM tools end.
  1164. /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
  1165. /// targeting. Set \p A to the Arg corresponding to the -mcpu or -mtune
  1166. /// arguments if they are provided, or to nullptr otherwise.
  1167. static std::string getAArch64TargetCPU(const ArgList &Args, Arg *&A) {
  1168. std::string CPU;
  1169. // If we have -mtune or -mcpu, use that.
  1170. if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
  1171. CPU = StringRef(A->getValue()).lower();
  1172. } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
  1173. StringRef Mcpu = A->getValue();
  1174. CPU = Mcpu.split("+").first.lower();
  1175. }
  1176. // Handle CPU name is 'native'.
  1177. if (CPU == "native")
  1178. return llvm::sys::getHostCPUName();
  1179. else if (CPU.size())
  1180. return CPU;
  1181. // Make sure we pick "cyclone" if -arch is used.
  1182. // FIXME: Should this be picked by checking the target triple instead?
  1183. if (Args.getLastArg(options::OPT_arch))
  1184. return "cyclone";
  1185. return "generic";
  1186. }
  1187. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  1188. ArgStringList &CmdArgs) const {
  1189. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  1190. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1191. Args.hasArg(options::OPT_mkernel) ||
  1192. Args.hasArg(options::OPT_fapple_kext))
  1193. CmdArgs.push_back("-disable-red-zone");
  1194. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1195. options::OPT_mno_implicit_float, true))
  1196. CmdArgs.push_back("-no-implicit-float");
  1197. const char *ABIName = nullptr;
  1198. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1199. ABIName = A->getValue();
  1200. else if (Triple.isOSDarwin())
  1201. ABIName = "darwinpcs";
  1202. else
  1203. ABIName = "aapcs";
  1204. CmdArgs.push_back("-target-abi");
  1205. CmdArgs.push_back(ABIName);
  1206. if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
  1207. options::OPT_mno_fix_cortex_a53_835769)) {
  1208. CmdArgs.push_back("-backend-option");
  1209. if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
  1210. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1211. else
  1212. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
  1213. } else if (Triple.isAndroid()) {
  1214. // Enabled A53 errata (835769) workaround by default on android
  1215. CmdArgs.push_back("-backend-option");
  1216. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1217. }
  1218. // Forward the -mglobal-merge option for explicit control over the pass.
  1219. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1220. options::OPT_mno_global_merge)) {
  1221. CmdArgs.push_back("-backend-option");
  1222. if (A->getOption().matches(options::OPT_mno_global_merge))
  1223. CmdArgs.push_back("-aarch64-enable-global-merge=false");
  1224. else
  1225. CmdArgs.push_back("-aarch64-enable-global-merge=true");
  1226. }
  1227. }
  1228. // Get CPU and ABI names. They are not independent
  1229. // so we have to calculate them together.
  1230. void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
  1231. StringRef &CPUName, StringRef &ABIName) {
  1232. const char *DefMips32CPU = "mips32r2";
  1233. const char *DefMips64CPU = "mips64r2";
  1234. // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
  1235. // default for mips64(el)?-img-linux-gnu.
  1236. if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  1237. Triple.getEnvironment() == llvm::Triple::GNU) {
  1238. DefMips32CPU = "mips32r6";
  1239. DefMips64CPU = "mips64r6";
  1240. }
  1241. // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
  1242. if (Triple.isAndroid()) {
  1243. DefMips32CPU = "mips32";
  1244. DefMips64CPU = "mips64r6";
  1245. }
  1246. // MIPS3 is the default for mips64*-unknown-openbsd.
  1247. if (Triple.getOS() == llvm::Triple::OpenBSD)
  1248. DefMips64CPU = "mips3";
  1249. if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
  1250. CPUName = A->getValue();
  1251. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  1252. ABIName = A->getValue();
  1253. // Convert a GNU style Mips ABI name to the name
  1254. // accepted by LLVM Mips backend.
  1255. ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
  1256. .Case("32", "o32")
  1257. .Case("64", "n64")
  1258. .Default(ABIName);
  1259. }
  1260. // Setup default CPU and ABI names.
  1261. if (CPUName.empty() && ABIName.empty()) {
  1262. switch (Triple.getArch()) {
  1263. default:
  1264. llvm_unreachable("Unexpected triple arch name");
  1265. case llvm::Triple::mips:
  1266. case llvm::Triple::mipsel:
  1267. CPUName = DefMips32CPU;
  1268. break;
  1269. case llvm::Triple::mips64:
  1270. case llvm::Triple::mips64el:
  1271. CPUName = DefMips64CPU;
  1272. break;
  1273. }
  1274. }
  1275. if (ABIName.empty() &&
  1276. (Triple.getVendor() == llvm::Triple::MipsTechnologies ||
  1277. Triple.getVendor() == llvm::Triple::ImaginationTechnologies)) {
  1278. ABIName = llvm::StringSwitch<const char *>(CPUName)
  1279. .Case("mips1", "o32")
  1280. .Case("mips2", "o32")
  1281. .Case("mips3", "n64")
  1282. .Case("mips4", "n64")
  1283. .Case("mips5", "n64")
  1284. .Case("mips32", "o32")
  1285. .Case("mips32r2", "o32")
  1286. .Case("mips32r3", "o32")
  1287. .Case("mips32r5", "o32")
  1288. .Case("mips32r6", "o32")
  1289. .Case("mips64", "n64")
  1290. .Case("mips64r2", "n64")
  1291. .Case("mips64r3", "n64")
  1292. .Case("mips64r5", "n64")
  1293. .Case("mips64r6", "n64")
  1294. .Case("octeon", "n64")
  1295. .Case("p5600", "o32")
  1296. .Default("");
  1297. }
  1298. if (ABIName.empty()) {
  1299. // Deduce ABI name from the target triple.
  1300. if (Triple.getArch() == llvm::Triple::mips ||
  1301. Triple.getArch() == llvm::Triple::mipsel)
  1302. ABIName = "o32";
  1303. else
  1304. ABIName = "n64";
  1305. }
  1306. if (CPUName.empty()) {
  1307. // Deduce CPU name from ABI name.
  1308. CPUName = llvm::StringSwitch<const char *>(ABIName)
  1309. .Case("o32", DefMips32CPU)
  1310. .Cases("n32", "n64", DefMips64CPU)
  1311. .Default("");
  1312. }
  1313. // FIXME: Warn on inconsistent use of -march and -mabi.
  1314. }
  1315. std::string mips::getMipsABILibSuffix(const ArgList &Args,
  1316. const llvm::Triple &Triple) {
  1317. StringRef CPUName, ABIName;
  1318. tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1319. return llvm::StringSwitch<std::string>(ABIName)
  1320. .Case("o32", "")
  1321. .Case("n32", "32")
  1322. .Case("n64", "64");
  1323. }
  1324. // Convert ABI name to the GNU tools acceptable variant.
  1325. static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
  1326. return llvm::StringSwitch<llvm::StringRef>(ABI)
  1327. .Case("o32", "32")
  1328. .Case("n64", "64")
  1329. .Default(ABI);
  1330. }
  1331. // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
  1332. // and -mfloat-abi=.
  1333. static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
  1334. mips::FloatABI ABI = mips::FloatABI::Invalid;
  1335. if (Arg *A =
  1336. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1337. options::OPT_mfloat_abi_EQ)) {
  1338. if (A->getOption().matches(options::OPT_msoft_float))
  1339. ABI = mips::FloatABI::Soft;
  1340. else if (A->getOption().matches(options::OPT_mhard_float))
  1341. ABI = mips::FloatABI::Hard;
  1342. else {
  1343. ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
  1344. .Case("soft", mips::FloatABI::Soft)
  1345. .Case("hard", mips::FloatABI::Hard)
  1346. .Default(mips::FloatABI::Invalid);
  1347. if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1348. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1349. ABI = mips::FloatABI::Hard;
  1350. }
  1351. }
  1352. }
  1353. // If unspecified, choose the default based on the platform.
  1354. if (ABI == mips::FloatABI::Invalid) {
  1355. // Assume "hard", because it's a default value used by gcc.
  1356. // When we start to recognize specific target MIPS processors,
  1357. // we will be able to select the default more correctly.
  1358. ABI = mips::FloatABI::Hard;
  1359. }
  1360. assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
  1361. return ABI;
  1362. }
  1363. static void AddTargetFeature(const ArgList &Args,
  1364. std::vector<StringRef> &Features,
  1365. OptSpecifier OnOpt, OptSpecifier OffOpt,
  1366. StringRef FeatureName) {
  1367. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  1368. if (A->getOption().matches(OnOpt))
  1369. Features.push_back(Args.MakeArgString("+" + FeatureName));
  1370. else
  1371. Features.push_back(Args.MakeArgString("-" + FeatureName));
  1372. }
  1373. }
  1374. static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1375. const ArgList &Args,
  1376. std::vector<StringRef> &Features) {
  1377. StringRef CPUName;
  1378. StringRef ABIName;
  1379. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1380. ABIName = getGnuCompatibleMipsABIName(ABIName);
  1381. // Historically, PIC code for MIPS was associated with -mabicalls, a.k.a
  1382. // SVR4 abicalls. Static code does not use SVR4 calling sequences. An ABI
  1383. // extension was developed by Richard Sandiford & Code Sourcery to support
  1384. // static code calling PIC code (CPIC). For O32 and N32 this means we have
  1385. // several combinations of PIC/static and abicalls. Pure static, static
  1386. // with the CPIC extension, and pure PIC code.
  1387. // At final link time, O32 and N32 with CPIC will have another section
  1388. // added to the binary which contains the stub functions to perform
  1389. // any fixups required for PIC code.
  1390. // For N64, the situation is more regular: code can either be static
  1391. // (non-abicalls) or PIC (abicalls). GCC has traditionally picked PIC code
  1392. // code for N64. Since Clang has already built the relocation model portion
  1393. // of the commandline, we pick add +noabicalls feature in the N64 static
  1394. // case.
  1395. // The is another case to be accounted for: -msym32, which enforces that all
  1396. // symbols have 32 bits in size. In this case, N64 can in theory use CPIC
  1397. // but it is unsupported.
  1398. // The combinations for N64 are:
  1399. // a) Static without abicalls and 64bit symbols.
  1400. // b) Static with abicalls and 32bit symbols.
  1401. // c) PIC with abicalls and 64bit symbols.
  1402. // For case (a) we need to add +noabicalls for N64.
  1403. bool IsN64 = ABIName == "64";
  1404. bool NonPIC = false;
  1405. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  1406. options::OPT_fpic, options::OPT_fno_pic,
  1407. options::OPT_fPIE, options::OPT_fno_PIE,
  1408. options::OPT_fpie, options::OPT_fno_pie);
  1409. if (LastPICArg) {
  1410. Option O = LastPICArg->getOption();
  1411. NonPIC =
  1412. (O.matches(options::OPT_fno_PIC) || O.matches(options::OPT_fno_pic) ||
  1413. O.matches(options::OPT_fno_PIE) || O.matches(options::OPT_fno_pie));
  1414. }
  1415. if (IsN64 && NonPIC) {
  1416. Features.push_back("+noabicalls");
  1417. } else {
  1418. AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
  1419. options::OPT_mabicalls, "noabicalls");
  1420. }
  1421. mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
  1422. if (FloatABI == mips::FloatABI::Soft) {
  1423. // FIXME: Note, this is a hack. We need to pass the selected float
  1424. // mode to the MipsTargetInfoBase to define appropriate macros there.
  1425. // Now it is the only method.
  1426. Features.push_back("+soft-float");
  1427. }
  1428. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  1429. StringRef Val = StringRef(A->getValue());
  1430. if (Val == "2008") {
  1431. if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
  1432. Features.push_back("+nan2008");
  1433. else {
  1434. Features.push_back("-nan2008");
  1435. D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
  1436. }
  1437. } else if (Val == "legacy") {
  1438. if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
  1439. Features.push_back("-nan2008");
  1440. else {
  1441. Features.push_back("+nan2008");
  1442. D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
  1443. }
  1444. } else
  1445. D.Diag(diag::err_drv_unsupported_option_argument)
  1446. << A->getOption().getName() << Val;
  1447. }
  1448. AddTargetFeature(Args, Features, options::OPT_msingle_float,
  1449. options::OPT_mdouble_float, "single-float");
  1450. AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
  1451. "mips16");
  1452. AddTargetFeature(Args, Features, options::OPT_mmicromips,
  1453. options::OPT_mno_micromips, "micromips");
  1454. AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
  1455. "dsp");
  1456. AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
  1457. "dspr2");
  1458. AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
  1459. "msa");
  1460. // Add the last -mfp32/-mfpxx/-mfp64, if none are given and the ABI is O32
  1461. // pass -mfpxx, or if none are given and fp64a is default, pass fp64 and
  1462. // nooddspreg.
  1463. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  1464. options::OPT_mfp64)) {
  1465. if (A->getOption().matches(options::OPT_mfp32))
  1466. Features.push_back(Args.MakeArgString("-fp64"));
  1467. else if (A->getOption().matches(options::OPT_mfpxx)) {
  1468. Features.push_back(Args.MakeArgString("+fpxx"));
  1469. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1470. } else
  1471. Features.push_back(Args.MakeArgString("+fp64"));
  1472. } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
  1473. Features.push_back(Args.MakeArgString("+fpxx"));
  1474. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1475. } else if (mips::isFP64ADefault(Triple, CPUName)) {
  1476. Features.push_back(Args.MakeArgString("+fp64"));
  1477. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1478. }
  1479. AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
  1480. options::OPT_modd_spreg, "nooddspreg");
  1481. }
  1482. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1483. ArgStringList &CmdArgs) const {
  1484. const Driver &D = getToolChain().getDriver();
  1485. StringRef CPUName;
  1486. StringRef ABIName;
  1487. const llvm::Triple &Triple = getToolChain().getTriple();
  1488. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1489. CmdArgs.push_back("-target-abi");
  1490. CmdArgs.push_back(ABIName.data());
  1491. mips::FloatABI ABI = getMipsFloatABI(D, Args);
  1492. if (ABI == mips::FloatABI::Soft) {
  1493. // Floating point operations and argument passing are soft.
  1494. CmdArgs.push_back("-msoft-float");
  1495. CmdArgs.push_back("-mfloat-abi");
  1496. CmdArgs.push_back("soft");
  1497. } else {
  1498. // Floating point operations and argument passing are hard.
  1499. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1500. CmdArgs.push_back("-mfloat-abi");
  1501. CmdArgs.push_back("hard");
  1502. }
  1503. if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
  1504. if (A->getOption().matches(options::OPT_mxgot)) {
  1505. CmdArgs.push_back("-mllvm");
  1506. CmdArgs.push_back("-mxgot");
  1507. }
  1508. }
  1509. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1510. options::OPT_mno_ldc1_sdc1)) {
  1511. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1512. CmdArgs.push_back("-mllvm");
  1513. CmdArgs.push_back("-mno-ldc1-sdc1");
  1514. }
  1515. }
  1516. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1517. options::OPT_mno_check_zero_division)) {
  1518. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1519. CmdArgs.push_back("-mllvm");
  1520. CmdArgs.push_back("-mno-check-zero-division");
  1521. }
  1522. }
  1523. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1524. StringRef v = A->getValue();
  1525. CmdArgs.push_back("-mllvm");
  1526. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1527. A->claim();
  1528. }
  1529. if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
  1530. StringRef Val = StringRef(A->getValue());
  1531. if (mips::hasCompactBranches(CPUName)) {
  1532. if (Val == "never" || Val == "always" || Val == "optimal") {
  1533. CmdArgs.push_back("-mllvm");
  1534. CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
  1535. } else
  1536. D.Diag(diag::err_drv_unsupported_option_argument)
  1537. << A->getOption().getName() << Val;
  1538. } else
  1539. D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
  1540. }
  1541. }
  1542. /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
  1543. static std::string getPPCTargetCPU(const ArgList &Args) {
  1544. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1545. StringRef CPUName = A->getValue();
  1546. if (CPUName == "native") {
  1547. std::string CPU = llvm::sys::getHostCPUName();
  1548. if (!CPU.empty() && CPU != "generic")
  1549. return CPU;
  1550. else
  1551. return "";
  1552. }
  1553. return llvm::StringSwitch<const char *>(CPUName)
  1554. .Case("common", "generic")
  1555. .Case("440", "440")
  1556. .Case("440fp", "440")
  1557. .Case("450", "450")
  1558. .Case("601", "601")
  1559. .Case("602", "602")
  1560. .Case("603", "603")
  1561. .Case("603e", "603e")
  1562. .Case("603ev", "603ev")
  1563. .Case("604", "604")
  1564. .Case("604e", "604e")
  1565. .Case("620", "620")
  1566. .Case("630", "pwr3")
  1567. .Case("G3", "g3")
  1568. .Case("7400", "7400")
  1569. .Case("G4", "g4")
  1570. .Case("7450", "7450")
  1571. .Case("G4+", "g4+")
  1572. .Case("750", "750")
  1573. .Case("970", "970")
  1574. .Case("G5", "g5")
  1575. .Case("a2", "a2")
  1576. .Case("a2q", "a2q")
  1577. .Case("e500mc", "e500mc")
  1578. .Case("e5500", "e5500")
  1579. .Case("power3", "pwr3")
  1580. .Case("power4", "pwr4")
  1581. .Case("power5", "pwr5")
  1582. .Case("power5x", "pwr5x")
  1583. .Case("power6", "pwr6")
  1584. .Case("power6x", "pwr6x")
  1585. .Case("power7", "pwr7")
  1586. .Case("power8", "pwr8")
  1587. .Case("power9", "pwr9")
  1588. .Case("pwr3", "pwr3")
  1589. .Case("pwr4", "pwr4")
  1590. .Case("pwr5", "pwr5")
  1591. .Case("pwr5x", "pwr5x")
  1592. .Case("pwr6", "pwr6")
  1593. .Case("pwr6x", "pwr6x")
  1594. .Case("pwr7", "pwr7")
  1595. .Case("pwr8", "pwr8")
  1596. .Case("pwr9", "pwr9")
  1597. .Case("powerpc", "ppc")
  1598. .Case("powerpc64", "ppc64")
  1599. .Case("powerpc64le", "ppc64le")
  1600. .Default("");
  1601. }
  1602. return "";
  1603. }
  1604. static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1605. const ArgList &Args,
  1606. std::vector<StringRef> &Features) {
  1607. handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
  1608. ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
  1609. if (FloatABI == ppc::FloatABI::Soft)
  1610. Features.push_back("-hard-float");
  1611. // Altivec is a bit weird, allow overriding of the Altivec feature here.
  1612. AddTargetFeature(Args, Features, options::OPT_faltivec,
  1613. options::OPT_fno_altivec, "altivec");
  1614. }
  1615. ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
  1616. ppc::FloatABI ABI = ppc::FloatABI::Invalid;
  1617. if (Arg *A =
  1618. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1619. options::OPT_mfloat_abi_EQ)) {
  1620. if (A->getOption().matches(options::OPT_msoft_float))
  1621. ABI = ppc::FloatABI::Soft;
  1622. else if (A->getOption().matches(options::OPT_mhard_float))
  1623. ABI = ppc::FloatABI::Hard;
  1624. else {
  1625. ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
  1626. .Case("soft", ppc::FloatABI::Soft)
  1627. .Case("hard", ppc::FloatABI::Hard)
  1628. .Default(ppc::FloatABI::Invalid);
  1629. if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1630. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1631. ABI = ppc::FloatABI::Hard;
  1632. }
  1633. }
  1634. }
  1635. // If unspecified, choose the default based on the platform.
  1636. if (ABI == ppc::FloatABI::Invalid) {
  1637. ABI = ppc::FloatABI::Hard;
  1638. }
  1639. return ABI;
  1640. }
  1641. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1642. ArgStringList &CmdArgs) const {
  1643. // Select the ABI to use.
  1644. const char *ABIName = nullptr;
  1645. if (getToolChain().getTriple().isOSLinux())
  1646. switch (getToolChain().getArch()) {
  1647. case llvm::Triple::ppc64: {
  1648. // When targeting a processor that supports QPX, or if QPX is
  1649. // specifically enabled, default to using the ABI that supports QPX (so
  1650. // long as it is not specifically disabled).
  1651. bool HasQPX = false;
  1652. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1653. HasQPX = A->getValue() == StringRef("a2q");
  1654. HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
  1655. if (HasQPX) {
  1656. ABIName = "elfv1-qpx";
  1657. break;
  1658. }
  1659. ABIName = "elfv1";
  1660. break;
  1661. }
  1662. case llvm::Triple::ppc64le:
  1663. ABIName = "elfv2";
  1664. break;
  1665. default:
  1666. break;
  1667. }
  1668. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1669. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1670. // the option if given as we don't have backend support for any targets
  1671. // that don't use the altivec abi.
  1672. if (StringRef(A->getValue()) != "altivec")
  1673. ABIName = A->getValue();
  1674. ppc::FloatABI FloatABI =
  1675. ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
  1676. if (FloatABI == ppc::FloatABI::Soft) {
  1677. // Floating point operations and argument passing are soft.
  1678. CmdArgs.push_back("-msoft-float");
  1679. CmdArgs.push_back("-mfloat-abi");
  1680. CmdArgs.push_back("soft");
  1681. } else {
  1682. // Floating point operations and argument passing are hard.
  1683. assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
  1684. CmdArgs.push_back("-mfloat-abi");
  1685. CmdArgs.push_back("hard");
  1686. }
  1687. if (ABIName) {
  1688. CmdArgs.push_back("-target-abi");
  1689. CmdArgs.push_back(ABIName);
  1690. }
  1691. }
  1692. bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  1693. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  1694. return A && (A->getValue() == StringRef(Value));
  1695. }
  1696. /// Get the (LLVM) name of the R600 gpu we are targeting.
  1697. static std::string getR600TargetGPU(const ArgList &Args) {
  1698. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1699. const char *GPUName = A->getValue();
  1700. return llvm::StringSwitch<const char *>(GPUName)
  1701. .Cases("rv630", "rv635", "r600")
  1702. .Cases("rv610", "rv620", "rs780", "rs880")
  1703. .Case("rv740", "rv770")
  1704. .Case("palm", "cedar")
  1705. .Cases("sumo", "sumo2", "sumo")
  1706. .Case("hemlock", "cypress")
  1707. .Case("aruba", "cayman")
  1708. .Default(GPUName);
  1709. }
  1710. return "";
  1711. }
  1712. static std::string getLanaiTargetCPU(const ArgList &Args) {
  1713. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1714. return A->getValue();
  1715. }
  1716. return "";
  1717. }
  1718. sparc::FloatABI sparc::getSparcFloatABI(const Driver &D,
  1719. const ArgList &Args) {
  1720. sparc::FloatABI ABI = sparc::FloatABI::Invalid;
  1721. if (Arg *A =
  1722. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1723. options::OPT_mfloat_abi_EQ)) {
  1724. if (A->getOption().matches(options::OPT_msoft_float))
  1725. ABI = sparc::FloatABI::Soft;
  1726. else if (A->getOption().matches(options::OPT_mhard_float))
  1727. ABI = sparc::FloatABI::Hard;
  1728. else {
  1729. ABI = llvm::StringSwitch<sparc::FloatABI>(A->getValue())
  1730. .Case("soft", sparc::FloatABI::Soft)
  1731. .Case("hard", sparc::FloatABI::Hard)
  1732. .Default(sparc::FloatABI::Invalid);
  1733. if (ABI == sparc::FloatABI::Invalid &&
  1734. !StringRef(A->getValue()).empty()) {
  1735. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1736. ABI = sparc::FloatABI::Hard;
  1737. }
  1738. }
  1739. }
  1740. // If unspecified, choose the default based on the platform.
  1741. // Only the hard-float ABI on Sparc is standardized, and it is the
  1742. // default. GCC also supports a nonstandard soft-float ABI mode, also
  1743. // implemented in LLVM. However as this is not standard we set the default
  1744. // to be hard-float.
  1745. if (ABI == sparc::FloatABI::Invalid) {
  1746. ABI = sparc::FloatABI::Hard;
  1747. }
  1748. return ABI;
  1749. }
  1750. static void getSparcTargetFeatures(const Driver &D, const ArgList &Args,
  1751. std::vector<StringRef> &Features) {
  1752. sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
  1753. if (FloatABI == sparc::FloatABI::Soft)
  1754. Features.push_back("+soft-float");
  1755. }
  1756. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1757. ArgStringList &CmdArgs) const {
  1758. sparc::FloatABI FloatABI =
  1759. sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
  1760. if (FloatABI == sparc::FloatABI::Soft) {
  1761. // Floating point operations and argument passing are soft.
  1762. CmdArgs.push_back("-msoft-float");
  1763. CmdArgs.push_back("-mfloat-abi");
  1764. CmdArgs.push_back("soft");
  1765. } else {
  1766. // Floating point operations and argument passing are hard.
  1767. assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
  1768. CmdArgs.push_back("-mfloat-abi");
  1769. CmdArgs.push_back("hard");
  1770. }
  1771. }
  1772. void Clang::AddSystemZTargetArgs(const ArgList &Args,
  1773. ArgStringList &CmdArgs) const {
  1774. if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
  1775. CmdArgs.push_back("-mbackchain");
  1776. }
  1777. static const char *getSystemZTargetCPU(const ArgList &Args) {
  1778. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1779. return A->getValue();
  1780. return "z10";
  1781. }
  1782. static void getSystemZTargetFeatures(const ArgList &Args,
  1783. std::vector<StringRef> &Features) {
  1784. // -m(no-)htm overrides use of the transactional-execution facility.
  1785. if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
  1786. if (A->getOption().matches(options::OPT_mhtm))
  1787. Features.push_back("+transactional-execution");
  1788. else
  1789. Features.push_back("-transactional-execution");
  1790. }
  1791. // -m(no-)vx overrides use of the vector facility.
  1792. if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
  1793. if (A->getOption().matches(options::OPT_mvx))
  1794. Features.push_back("+vector");
  1795. else
  1796. Features.push_back("-vector");
  1797. }
  1798. }
  1799. static const char *getX86TargetCPU(const ArgList &Args,
  1800. const llvm::Triple &Triple) {
  1801. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1802. if (StringRef(A->getValue()) != "native") {
  1803. if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
  1804. return "core-avx2";
  1805. return A->getValue();
  1806. }
  1807. // FIXME: Reject attempts to use -march=native unless the target matches
  1808. // the host.
  1809. //
  1810. // FIXME: We should also incorporate the detected target features for use
  1811. // with -native.
  1812. std::string CPU = llvm::sys::getHostCPUName();
  1813. if (!CPU.empty() && CPU != "generic")
  1814. return Args.MakeArgString(CPU);
  1815. }
  1816. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1817. // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
  1818. StringRef Arch = A->getValue();
  1819. const char *CPU;
  1820. if (Triple.getArch() == llvm::Triple::x86) {
  1821. CPU = llvm::StringSwitch<const char *>(Arch)
  1822. .Case("IA32", "i386")
  1823. .Case("SSE", "pentium3")
  1824. .Case("SSE2", "pentium4")
  1825. .Case("AVX", "sandybridge")
  1826. .Case("AVX2", "haswell")
  1827. .Default(nullptr);
  1828. } else {
  1829. CPU = llvm::StringSwitch<const char *>(Arch)
  1830. .Case("AVX", "sandybridge")
  1831. .Case("AVX2", "haswell")
  1832. .Default(nullptr);
  1833. }
  1834. if (CPU)
  1835. return CPU;
  1836. }
  1837. // Select the default CPU if none was given (or detection failed).
  1838. if (Triple.getArch() != llvm::Triple::x86_64 &&
  1839. Triple.getArch() != llvm::Triple::x86)
  1840. return nullptr; // This routine is only handling x86 targets.
  1841. bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
  1842. // FIXME: Need target hooks.
  1843. if (Triple.isOSDarwin()) {
  1844. if (Triple.getArchName() == "x86_64h")
  1845. return "core-avx2";
  1846. // macosx10.12 drops support for all pre-Penryn Macs.
  1847. // Simulators can still run on 10.11 though, like Xcode.
  1848. if (Triple.isMacOSX() && !Triple.isOSVersionLT(10, 12))
  1849. return "penryn";
  1850. // The oldest x86_64 Macs have core2/Merom; the oldest x86 Macs have Yonah.
  1851. return Is64Bit ? "core2" : "yonah";
  1852. }
  1853. // Set up default CPU name for PS4 compilers.
  1854. if (Triple.isPS4CPU())
  1855. return "btver2";
  1856. // On Android use targets compatible with gcc
  1857. if (Triple.isAndroid())
  1858. return Is64Bit ? "x86-64" : "i686";
  1859. // Everything else goes to x86-64 in 64-bit mode.
  1860. if (Is64Bit)
  1861. return "x86-64";
  1862. switch (Triple.getOS()) {
  1863. case llvm::Triple::FreeBSD:
  1864. case llvm::Triple::NetBSD:
  1865. case llvm::Triple::OpenBSD:
  1866. return "i486";
  1867. case llvm::Triple::Haiku:
  1868. return "i586";
  1869. case llvm::Triple::Bitrig:
  1870. return "i686";
  1871. default:
  1872. // Fallback to p4.
  1873. return "pentium4";
  1874. }
  1875. }
  1876. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  1877. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  1878. // If we have -mcpu=, use that.
  1879. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1880. StringRef CPU = A->getValue();
  1881. #ifdef __wasm__
  1882. // Handle "native" by examining the host. "native" isn't meaningful when
  1883. // cross compiling, so only support this when the host is also WebAssembly.
  1884. if (CPU == "native")
  1885. return llvm::sys::getHostCPUName();
  1886. #endif
  1887. return CPU;
  1888. }
  1889. return "generic";
  1890. }
  1891. static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
  1892. bool FromAs = false) {
  1893. Arg *A;
  1894. switch (T.getArch()) {
  1895. default:
  1896. return "";
  1897. case llvm::Triple::aarch64:
  1898. case llvm::Triple::aarch64_be:
  1899. return getAArch64TargetCPU(Args, A);
  1900. case llvm::Triple::arm:
  1901. case llvm::Triple::armeb:
  1902. case llvm::Triple::thumb:
  1903. case llvm::Triple::thumbeb: {
  1904. StringRef MArch, MCPU;
  1905. getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  1906. return arm::getARMTargetCPU(MCPU, MArch, T);
  1907. }
  1908. case llvm::Triple::mips:
  1909. case llvm::Triple::mipsel:
  1910. case llvm::Triple::mips64:
  1911. case llvm::Triple::mips64el: {
  1912. StringRef CPUName;
  1913. StringRef ABIName;
  1914. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  1915. return CPUName;
  1916. }
  1917. case llvm::Triple::nvptx:
  1918. case llvm::Triple::nvptx64:
  1919. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1920. return A->getValue();
  1921. return "";
  1922. case llvm::Triple::ppc:
  1923. case llvm::Triple::ppc64:
  1924. case llvm::Triple::ppc64le: {
  1925. std::string TargetCPUName = getPPCTargetCPU(Args);
  1926. // LLVM may default to generating code for the native CPU,
  1927. // but, like gcc, we default to a more generic option for
  1928. // each architecture. (except on Darwin)
  1929. if (TargetCPUName.empty() && !T.isOSDarwin()) {
  1930. if (T.getArch() == llvm::Triple::ppc64)
  1931. TargetCPUName = "ppc64";
  1932. else if (T.getArch() == llvm::Triple::ppc64le)
  1933. TargetCPUName = "ppc64le";
  1934. else
  1935. TargetCPUName = "ppc";
  1936. }
  1937. return TargetCPUName;
  1938. }
  1939. case llvm::Triple::sparc:
  1940. case llvm::Triple::sparcel:
  1941. case llvm::Triple::sparcv9:
  1942. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1943. return A->getValue();
  1944. return "";
  1945. case llvm::Triple::x86:
  1946. case llvm::Triple::x86_64:
  1947. return getX86TargetCPU(Args, T);
  1948. case llvm::Triple::hexagon:
  1949. return "hexagon" +
  1950. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  1951. case llvm::Triple::lanai:
  1952. return getLanaiTargetCPU(Args);
  1953. case llvm::Triple::systemz:
  1954. return getSystemZTargetCPU(Args);
  1955. case llvm::Triple::r600:
  1956. case llvm::Triple::amdgcn:
  1957. return getR600TargetGPU(Args);
  1958. case llvm::Triple::wasm32:
  1959. case llvm::Triple::wasm64:
  1960. return getWebAssemblyTargetCPU(Args);
  1961. }
  1962. }
  1963. static unsigned getLTOParallelism(const ArgList &Args, const Driver &D) {
  1964. unsigned Parallelism = 0;
  1965. Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
  1966. if (LtoJobsArg &&
  1967. StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
  1968. D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
  1969. << LtoJobsArg->getValue();
  1970. return Parallelism;
  1971. }
  1972. // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
  1973. // default.
  1974. static bool isUseSeparateSections(const llvm::Triple &Triple) {
  1975. return Triple.getOS() == llvm::Triple::CloudABI ||
  1976. Triple.getArch() == llvm::Triple::wasm32 ||
  1977. Triple.getArch() == llvm::Triple::wasm64;
  1978. }
  1979. static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
  1980. ArgStringList &CmdArgs, bool IsThinLTO,
  1981. const Driver &D) {
  1982. // Tell the linker to load the plugin. This has to come before AddLinkerInputs
  1983. // as gold requires -plugin to come before any -plugin-opt that -Wl might
  1984. // forward.
  1985. CmdArgs.push_back("-plugin");
  1986. std::string Plugin =
  1987. ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
  1988. CmdArgs.push_back(Args.MakeArgString(Plugin));
  1989. // Try to pass driver level flags relevant to LTO code generation down to
  1990. // the plugin.
  1991. // Handle flags for selecting CPU variants.
  1992. std::string CPU = getCPUName(Args, ToolChain.getTriple());
  1993. if (!CPU.empty())
  1994. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  1995. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  1996. StringRef OOpt;
  1997. if (A->getOption().matches(options::OPT_O4) ||
  1998. A->getOption().matches(options::OPT_Ofast))
  1999. OOpt = "3";
  2000. else if (A->getOption().matches(options::OPT_O))
  2001. OOpt = A->getValue();
  2002. else if (A->getOption().matches(options::OPT_O0))
  2003. OOpt = "0";
  2004. if (!OOpt.empty())
  2005. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
  2006. }
  2007. if (IsThinLTO)
  2008. CmdArgs.push_back("-plugin-opt=thinlto");
  2009. if (unsigned Parallelism = getLTOParallelism(Args, D))
  2010. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=jobs=") +
  2011. llvm::to_string(Parallelism)));
  2012. // If an explicit debugger tuning argument appeared, pass it along.
  2013. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  2014. options::OPT_ggdbN_Group)) {
  2015. if (A->getOption().matches(options::OPT_glldb))
  2016. CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
  2017. else if (A->getOption().matches(options::OPT_gsce))
  2018. CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
  2019. else
  2020. CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
  2021. }
  2022. bool UseSeparateSections =
  2023. isUseSeparateSections(ToolChain.getEffectiveTriple());
  2024. if (Args.hasFlag(options::OPT_ffunction_sections,
  2025. options::OPT_fno_function_sections, UseSeparateSections)) {
  2026. CmdArgs.push_back("-plugin-opt=-function-sections");
  2027. }
  2028. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  2029. UseSeparateSections)) {
  2030. CmdArgs.push_back("-plugin-opt=-data-sections");
  2031. }
  2032. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  2033. StringRef FName = A->getValue();
  2034. if (!llvm::sys::fs::exists(FName))
  2035. D.Diag(diag::err_drv_no_such_file) << FName;
  2036. else
  2037. CmdArgs.push_back(
  2038. Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
  2039. }
  2040. }
  2041. /// This is a helper function for validating the optional refinement step
  2042. /// parameter in reciprocal argument strings. Return false if there is an error
  2043. /// parsing the refinement step. Otherwise, return true and set the Position
  2044. /// of the refinement step in the input string.
  2045. static bool getRefinementStep(StringRef In, const Driver &D,
  2046. const Arg &A, size_t &Position) {
  2047. const char RefinementStepToken = ':';
  2048. Position = In.find(RefinementStepToken);
  2049. if (Position != StringRef::npos) {
  2050. StringRef Option = A.getOption().getName();
  2051. StringRef RefStep = In.substr(Position + 1);
  2052. // Allow exactly one numeric character for the additional refinement
  2053. // step parameter. This is reasonable for all currently-supported
  2054. // operations and architectures because we would expect that a larger value
  2055. // of refinement steps would cause the estimate "optimization" to
  2056. // under-perform the native operation. Also, if the estimate does not
  2057. // converge quickly, it probably will not ever converge, so further
  2058. // refinement steps will not produce a better answer.
  2059. if (RefStep.size() != 1) {
  2060. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  2061. return false;
  2062. }
  2063. char RefStepChar = RefStep[0];
  2064. if (RefStepChar < '0' || RefStepChar > '9') {
  2065. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  2066. return false;
  2067. }
  2068. }
  2069. return true;
  2070. }
  2071. /// The -mrecip flag requires processing of many optional parameters.
  2072. static void ParseMRecip(const Driver &D, const ArgList &Args,
  2073. ArgStringList &OutStrings) {
  2074. StringRef DisabledPrefixIn = "!";
  2075. StringRef DisabledPrefixOut = "!";
  2076. StringRef EnabledPrefixOut = "";
  2077. StringRef Out = "-mrecip=";
  2078. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  2079. if (!A)
  2080. return;
  2081. unsigned NumOptions = A->getNumValues();
  2082. if (NumOptions == 0) {
  2083. // No option is the same as "all".
  2084. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  2085. return;
  2086. }
  2087. // Pass through "all", "none", or "default" with an optional refinement step.
  2088. if (NumOptions == 1) {
  2089. StringRef Val = A->getValue(0);
  2090. size_t RefStepLoc;
  2091. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  2092. return;
  2093. StringRef ValBase = Val.slice(0, RefStepLoc);
  2094. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  2095. OutStrings.push_back(Args.MakeArgString(Out + Val));
  2096. return;
  2097. }
  2098. }
  2099. // Each reciprocal type may be enabled or disabled individually.
  2100. // Check each input value for validity, concatenate them all back together,
  2101. // and pass through.
  2102. llvm::StringMap<bool> OptionStrings;
  2103. OptionStrings.insert(std::make_pair("divd", false));
  2104. OptionStrings.insert(std::make_pair("divf", false));
  2105. OptionStrings.insert(std::make_pair("vec-divd", false));
  2106. OptionStrings.insert(std::make_pair("vec-divf", false));
  2107. OptionStrings.insert(std::make_pair("sqrtd", false));
  2108. OptionStrings.insert(std::make_pair("sqrtf", false));
  2109. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  2110. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  2111. for (unsigned i = 0; i != NumOptions; ++i) {
  2112. StringRef Val = A->getValue(i);
  2113. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  2114. // Ignore the disablement token for string matching.
  2115. if (IsDisabled)
  2116. Val = Val.substr(1);
  2117. size_t RefStep;
  2118. if (!getRefinementStep(Val, D, *A, RefStep))
  2119. return;
  2120. StringRef ValBase = Val.slice(0, RefStep);
  2121. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  2122. if (OptionIter == OptionStrings.end()) {
  2123. // Try again specifying float suffix.
  2124. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  2125. if (OptionIter == OptionStrings.end()) {
  2126. // The input name did not match any known option string.
  2127. D.Diag(diag::err_drv_unknown_argument) << Val;
  2128. return;
  2129. }
  2130. // The option was specified without a float or double suffix.
  2131. // Make sure that the double entry was not already specified.
  2132. // The float entry will be checked below.
  2133. if (OptionStrings[ValBase.str() + 'd']) {
  2134. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  2135. return;
  2136. }
  2137. }
  2138. if (OptionIter->second == true) {
  2139. // Duplicate option specified.
  2140. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  2141. return;
  2142. }
  2143. // Mark the matched option as found. Do not allow duplicate specifiers.
  2144. OptionIter->second = true;
  2145. // If the precision was not specified, also mark the double entry as found.
  2146. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  2147. OptionStrings[ValBase.str() + 'd'] = true;
  2148. // Build the output string.
  2149. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  2150. Out = Args.MakeArgString(Out + Prefix + Val);
  2151. if (i != NumOptions - 1)
  2152. Out = Args.MakeArgString(Out + ",");
  2153. }
  2154. OutStrings.push_back(Args.MakeArgString(Out));
  2155. }
  2156. static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
  2157. const ArgList &Args,
  2158. std::vector<StringRef> &Features) {
  2159. // If -march=native, autodetect the feature list.
  2160. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  2161. if (StringRef(A->getValue()) == "native") {
  2162. llvm::StringMap<bool> HostFeatures;
  2163. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  2164. for (auto &F : HostFeatures)
  2165. Features.push_back(
  2166. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  2167. }
  2168. }
  2169. if (Triple.getArchName() == "x86_64h") {
  2170. // x86_64h implies quite a few of the more modern subtarget features
  2171. // for Haswell class CPUs, but not all of them. Opt-out of a few.
  2172. Features.push_back("-rdrnd");
  2173. Features.push_back("-aes");
  2174. Features.push_back("-pclmul");
  2175. Features.push_back("-rtm");
  2176. Features.push_back("-hle");
  2177. Features.push_back("-fsgsbase");
  2178. }
  2179. const llvm::Triple::ArchType ArchType = Triple.getArch();
  2180. // Add features to be compatible with gcc for Android.
  2181. if (Triple.isAndroid()) {
  2182. if (ArchType == llvm::Triple::x86_64) {
  2183. Features.push_back("+sse4.2");
  2184. Features.push_back("+popcnt");
  2185. } else
  2186. Features.push_back("+ssse3");
  2187. }
  2188. // Set features according to the -arch flag on MSVC.
  2189. if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  2190. StringRef Arch = A->getValue();
  2191. bool ArchUsed = false;
  2192. // First, look for flags that are shared in x86 and x86-64.
  2193. if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
  2194. if (Arch == "AVX" || Arch == "AVX2") {
  2195. ArchUsed = true;
  2196. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  2197. }
  2198. }
  2199. // Then, look for x86-specific flags.
  2200. if (ArchType == llvm::Triple::x86) {
  2201. if (Arch == "IA32") {
  2202. ArchUsed = true;
  2203. } else if (Arch == "SSE" || Arch == "SSE2") {
  2204. ArchUsed = true;
  2205. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  2206. }
  2207. }
  2208. if (!ArchUsed)
  2209. D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
  2210. }
  2211. // Now add any that the user explicitly requested on the command line,
  2212. // which may override the defaults.
  2213. handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
  2214. }
  2215. void Clang::AddX86TargetArgs(const ArgList &Args,
  2216. ArgStringList &CmdArgs) const {
  2217. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  2218. Args.hasArg(options::OPT_mkernel) ||
  2219. Args.hasArg(options::OPT_fapple_kext))
  2220. CmdArgs.push_back("-disable-red-zone");
  2221. // Default to avoid implicit floating-point for kernel/kext code, but allow
  2222. // that to be overridden with -mno-soft-float.
  2223. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  2224. Args.hasArg(options::OPT_fapple_kext));
  2225. if (Arg *A = Args.getLastArg(
  2226. options::OPT_msoft_float, options::OPT_mno_soft_float,
  2227. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  2228. const Option &O = A->getOption();
  2229. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  2230. O.matches(options::OPT_msoft_float));
  2231. }
  2232. if (NoImplicitFloat)
  2233. CmdArgs.push_back("-no-implicit-float");
  2234. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  2235. StringRef Value = A->getValue();
  2236. if (Value == "intel" || Value == "att") {
  2237. CmdArgs.push_back("-mllvm");
  2238. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  2239. } else {
  2240. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  2241. << A->getOption().getName() << Value;
  2242. }
  2243. }
  2244. // Set flags to support MCU ABI.
  2245. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
  2246. CmdArgs.push_back("-mfloat-abi");
  2247. CmdArgs.push_back("soft");
  2248. CmdArgs.push_back("-mstack-alignment=4");
  2249. }
  2250. }
  2251. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  2252. ArgStringList &CmdArgs) const {
  2253. CmdArgs.push_back("-mqdsp6-compat");
  2254. CmdArgs.push_back("-Wreturn-type");
  2255. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  2256. std::string N = llvm::utostr(G.getValue());
  2257. std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
  2258. CmdArgs.push_back("-mllvm");
  2259. CmdArgs.push_back(Args.MakeArgString(Opt));
  2260. }
  2261. if (!Args.hasArg(options::OPT_fno_short_enums))
  2262. CmdArgs.push_back("-fshort-enums");
  2263. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  2264. CmdArgs.push_back("-mllvm");
  2265. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  2266. }
  2267. CmdArgs.push_back("-mllvm");
  2268. CmdArgs.push_back("-machine-sink-split=0");
  2269. }
  2270. void Clang::AddLanaiTargetArgs(const ArgList &Args,
  2271. ArgStringList &CmdArgs) const {
  2272. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  2273. StringRef CPUName = A->getValue();
  2274. CmdArgs.push_back("-target-cpu");
  2275. CmdArgs.push_back(Args.MakeArgString(CPUName));
  2276. }
  2277. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  2278. StringRef Value = A->getValue();
  2279. // Only support mregparm=4 to support old usage. Report error for all other
  2280. // cases.
  2281. int Mregparm;
  2282. if (Value.getAsInteger(10, Mregparm)) {
  2283. if (Mregparm != 4) {
  2284. getToolChain().getDriver().Diag(
  2285. diag::err_drv_unsupported_option_argument)
  2286. << A->getOption().getName() << Value;
  2287. }
  2288. }
  2289. }
  2290. }
  2291. void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
  2292. ArgStringList &CmdArgs) const {
  2293. // Default to "hidden" visibility.
  2294. if (!Args.hasArg(options::OPT_fvisibility_EQ,
  2295. options::OPT_fvisibility_ms_compat)) {
  2296. CmdArgs.push_back("-fvisibility");
  2297. CmdArgs.push_back("hidden");
  2298. }
  2299. }
  2300. // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
  2301. static bool DecodeAArch64Features(const Driver &D, StringRef text,
  2302. std::vector<StringRef> &Features) {
  2303. SmallVector<StringRef, 8> Split;
  2304. text.split(Split, StringRef("+"), -1, false);
  2305. for (StringRef Feature : Split) {
  2306. StringRef FeatureName = llvm::AArch64::getArchExtFeature(Feature);
  2307. if (!FeatureName.empty())
  2308. Features.push_back(FeatureName);
  2309. else if (Feature == "neon" || Feature == "noneon")
  2310. D.Diag(diag::err_drv_no_neon_modifier);
  2311. else
  2312. return false;
  2313. }
  2314. return true;
  2315. }
  2316. // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
  2317. // decode CPU and feature.
  2318. static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
  2319. std::vector<StringRef> &Features) {
  2320. std::pair<StringRef, StringRef> Split = Mcpu.split("+");
  2321. CPU = Split.first;
  2322. if (CPU == "generic") {
  2323. Features.push_back("+neon");
  2324. } else {
  2325. unsigned ArchKind = llvm::AArch64::parseCPUArch(CPU);
  2326. if (!llvm::AArch64::getArchFeatures(ArchKind, Features))
  2327. return false;
  2328. unsigned Extension = llvm::AArch64::getDefaultExtensions(CPU, ArchKind);
  2329. if (!llvm::AArch64::getExtensionFeatures(Extension, Features))
  2330. return false;
  2331. }
  2332. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  2333. return false;
  2334. return true;
  2335. }
  2336. static bool
  2337. getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
  2338. const ArgList &Args,
  2339. std::vector<StringRef> &Features) {
  2340. std::string MarchLowerCase = March.lower();
  2341. std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
  2342. unsigned ArchKind = llvm::AArch64::parseArch(Split.first);
  2343. if (ArchKind == static_cast<unsigned>(llvm::AArch64::ArchKind::AK_INVALID) ||
  2344. !llvm::AArch64::getArchFeatures(ArchKind, Features) ||
  2345. (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features)))
  2346. return false;
  2347. return true;
  2348. }
  2349. static bool
  2350. getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2351. const ArgList &Args,
  2352. std::vector<StringRef> &Features) {
  2353. StringRef CPU;
  2354. std::string McpuLowerCase = Mcpu.lower();
  2355. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
  2356. return false;
  2357. return true;
  2358. }
  2359. static bool
  2360. getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
  2361. const ArgList &Args,
  2362. std::vector<StringRef> &Features) {
  2363. std::string MtuneLowerCase = Mtune.lower();
  2364. // Handle CPU name is 'native'.
  2365. if (MtuneLowerCase == "native")
  2366. MtuneLowerCase = llvm::sys::getHostCPUName();
  2367. if (MtuneLowerCase == "cyclone") {
  2368. Features.push_back("+zcm");
  2369. Features.push_back("+zcz");
  2370. }
  2371. return true;
  2372. }
  2373. static bool
  2374. getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2375. const ArgList &Args,
  2376. std::vector<StringRef> &Features) {
  2377. StringRef CPU;
  2378. std::vector<StringRef> DecodedFeature;
  2379. std::string McpuLowerCase = Mcpu.lower();
  2380. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
  2381. return false;
  2382. return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
  2383. }
  2384. static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
  2385. std::vector<StringRef> &Features) {
  2386. Arg *A;
  2387. bool success = true;
  2388. // Enable NEON by default.
  2389. Features.push_back("+neon");
  2390. if ((A = Args.getLastArg(options::OPT_march_EQ)))
  2391. success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
  2392. else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2393. success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2394. else if (Args.hasArg(options::OPT_arch))
  2395. success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args, A),
  2396. Args, Features);
  2397. if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
  2398. success =
  2399. getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
  2400. else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2401. success =
  2402. getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2403. else if (success && Args.hasArg(options::OPT_arch))
  2404. success = getAArch64MicroArchFeaturesFromMcpu(
  2405. D, getAArch64TargetCPU(Args, A), Args, Features);
  2406. if (!success)
  2407. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  2408. if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
  2409. Features.push_back("-fp-armv8");
  2410. Features.push_back("-crypto");
  2411. Features.push_back("-neon");
  2412. }
  2413. // En/disable crc
  2414. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  2415. if (A->getOption().matches(options::OPT_mcrc))
  2416. Features.push_back("+crc");
  2417. else
  2418. Features.push_back("-crc");
  2419. }
  2420. if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  2421. options::OPT_munaligned_access))
  2422. if (A->getOption().matches(options::OPT_mno_unaligned_access))
  2423. Features.push_back("+strict-align");
  2424. if (Args.hasArg(options::OPT_ffixed_x18))
  2425. Features.push_back("+reserve-x18");
  2426. }
  2427. static void getHexagonTargetFeatures(const ArgList &Args,
  2428. std::vector<StringRef> &Features) {
  2429. handleTargetFeaturesGroup(Args, Features,
  2430. options::OPT_m_hexagon_Features_Group);
  2431. bool UseLongCalls = false;
  2432. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  2433. options::OPT_mno_long_calls)) {
  2434. if (A->getOption().matches(options::OPT_mlong_calls))
  2435. UseLongCalls = true;
  2436. }
  2437. Features.push_back(UseLongCalls ? "+long-calls" : "-long-calls");
  2438. }
  2439. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  2440. std::vector<StringRef> &Features) {
  2441. handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
  2442. }
  2443. static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
  2444. std::vector<StringRef> &Features) {
  2445. if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
  2446. StringRef value = dAbi->getValue();
  2447. if (value == "1.0") {
  2448. Features.push_back("+amdgpu-debugger-insert-nops");
  2449. Features.push_back("+amdgpu-debugger-reserve-regs");
  2450. Features.push_back("+amdgpu-debugger-emit-prologue");
  2451. } else {
  2452. D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
  2453. }
  2454. }
  2455. handleTargetFeaturesGroup(
  2456. Args, Features, options::OPT_m_amdgpu_Features_Group);
  2457. }
  2458. static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  2459. const ArgList &Args, ArgStringList &CmdArgs,
  2460. bool ForAS) {
  2461. const Driver &D = TC.getDriver();
  2462. std::vector<StringRef> Features;
  2463. switch (Triple.getArch()) {
  2464. default:
  2465. break;
  2466. case llvm::Triple::mips:
  2467. case llvm::Triple::mipsel:
  2468. case llvm::Triple::mips64:
  2469. case llvm::Triple::mips64el:
  2470. getMIPSTargetFeatures(D, Triple, Args, Features);
  2471. break;
  2472. case llvm::Triple::arm:
  2473. case llvm::Triple::armeb:
  2474. case llvm::Triple::thumb:
  2475. case llvm::Triple::thumbeb:
  2476. getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
  2477. break;
  2478. case llvm::Triple::ppc:
  2479. case llvm::Triple::ppc64:
  2480. case llvm::Triple::ppc64le:
  2481. getPPCTargetFeatures(D, Triple, Args, Features);
  2482. break;
  2483. case llvm::Triple::systemz:
  2484. getSystemZTargetFeatures(Args, Features);
  2485. break;
  2486. case llvm::Triple::aarch64:
  2487. case llvm::Triple::aarch64_be:
  2488. getAArch64TargetFeatures(D, Args, Features);
  2489. break;
  2490. case llvm::Triple::x86:
  2491. case llvm::Triple::x86_64:
  2492. getX86TargetFeatures(D, Triple, Args, Features);
  2493. break;
  2494. case llvm::Triple::hexagon:
  2495. getHexagonTargetFeatures(Args, Features);
  2496. break;
  2497. case llvm::Triple::wasm32:
  2498. case llvm::Triple::wasm64:
  2499. getWebAssemblyTargetFeatures(Args, Features);
  2500. break;
  2501. case llvm::Triple::sparc:
  2502. case llvm::Triple::sparcel:
  2503. case llvm::Triple::sparcv9:
  2504. getSparcTargetFeatures(D, Args, Features);
  2505. break;
  2506. case llvm::Triple::r600:
  2507. case llvm::Triple::amdgcn:
  2508. getAMDGPUTargetFeatures(D, Args, Features);
  2509. break;
  2510. }
  2511. // Find the last of each feature.
  2512. llvm::StringMap<unsigned> LastOpt;
  2513. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2514. StringRef Name = Features[I];
  2515. assert(Name[0] == '-' || Name[0] == '+');
  2516. LastOpt[Name.drop_front(1)] = I;
  2517. }
  2518. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2519. // If this feature was overridden, ignore it.
  2520. StringRef Name = Features[I];
  2521. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
  2522. assert(LastI != LastOpt.end());
  2523. unsigned Last = LastI->second;
  2524. if (Last != I)
  2525. continue;
  2526. CmdArgs.push_back("-target-feature");
  2527. CmdArgs.push_back(Name.data());
  2528. }
  2529. }
  2530. static bool
  2531. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  2532. const llvm::Triple &Triple) {
  2533. // We use the zero-cost exception tables for Objective-C if the non-fragile
  2534. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  2535. // later.
  2536. if (runtime.isNonFragile())
  2537. return true;
  2538. if (!Triple.isMacOSX())
  2539. return false;
  2540. return (!Triple.isMacOSXVersionLT(10, 5) &&
  2541. (Triple.getArch() == llvm::Triple::x86_64 ||
  2542. Triple.getArch() == llvm::Triple::arm));
  2543. }
  2544. /// Adds exception related arguments to the driver command arguments. There's a
  2545. /// master flag, -fexceptions and also language specific flags to enable/disable
  2546. /// C++ and Objective-C exceptions. This makes it possible to for example
  2547. /// disable C++ exceptions but enable Objective-C exceptions.
  2548. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  2549. const ToolChain &TC, bool KernelOrKext,
  2550. const ObjCRuntime &objcRuntime,
  2551. ArgStringList &CmdArgs) {
  2552. const Driver &D = TC.getDriver();
  2553. const llvm::Triple &Triple = TC.getTriple();
  2554. if (KernelOrKext) {
  2555. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  2556. // arguments now to avoid warnings about unused arguments.
  2557. Args.ClaimAllArgs(options::OPT_fexceptions);
  2558. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  2559. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  2560. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  2561. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  2562. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  2563. return;
  2564. }
  2565. // See if the user explicitly enabled exceptions.
  2566. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  2567. false);
  2568. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  2569. // is not necessarily sensible, but follows GCC.
  2570. if (types::isObjC(InputType) &&
  2571. Args.hasFlag(options::OPT_fobjc_exceptions,
  2572. options::OPT_fno_objc_exceptions, true)) {
  2573. CmdArgs.push_back("-fobjc-exceptions");
  2574. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  2575. }
  2576. if (types::isCXX(InputType)) {
  2577. // Disable C++ EH by default on XCore and PS4.
  2578. bool CXXExceptionsEnabled =
  2579. Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
  2580. Arg *ExceptionArg = Args.getLastArg(
  2581. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  2582. options::OPT_fexceptions, options::OPT_fno_exceptions);
  2583. if (ExceptionArg)
  2584. CXXExceptionsEnabled =
  2585. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  2586. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  2587. if (CXXExceptionsEnabled) {
  2588. if (Triple.isPS4CPU()) {
  2589. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  2590. assert(ExceptionArg &&
  2591. "On the PS4 exceptions should only be enabled if passing "
  2592. "an argument");
  2593. if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
  2594. const Arg *RTTIArg = TC.getRTTIArg();
  2595. assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
  2596. D.Diag(diag::err_drv_argument_not_allowed_with)
  2597. << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
  2598. } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
  2599. D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
  2600. } else
  2601. assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
  2602. CmdArgs.push_back("-fcxx-exceptions");
  2603. EH = true;
  2604. }
  2605. }
  2606. if (EH)
  2607. CmdArgs.push_back("-fexceptions");
  2608. }
  2609. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  2610. bool Default = true;
  2611. if (TC.getTriple().isOSDarwin()) {
  2612. // The native darwin assembler doesn't support the linker_option directives,
  2613. // so we disable them if we think the .s file will be passed to it.
  2614. Default = TC.useIntegratedAs();
  2615. }
  2616. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  2617. Default);
  2618. }
  2619. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  2620. const ToolChain &TC) {
  2621. bool UseDwarfDirectory =
  2622. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  2623. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  2624. return !UseDwarfDirectory;
  2625. }
  2626. /// \brief Check whether the given input tree contains any compilation actions.
  2627. static bool ContainsCompileAction(const Action *A) {
  2628. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  2629. return true;
  2630. for (const auto &AI : A->inputs())
  2631. if (ContainsCompileAction(AI))
  2632. return true;
  2633. return false;
  2634. }
  2635. /// \brief Check if -relax-all should be passed to the internal assembler.
  2636. /// This is done by default when compiling non-assembler source with -O0.
  2637. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  2638. bool RelaxDefault = true;
  2639. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2640. RelaxDefault = A->getOption().matches(options::OPT_O0);
  2641. if (RelaxDefault) {
  2642. RelaxDefault = false;
  2643. for (const auto &Act : C.getActions()) {
  2644. if (ContainsCompileAction(Act)) {
  2645. RelaxDefault = true;
  2646. break;
  2647. }
  2648. }
  2649. }
  2650. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  2651. RelaxDefault);
  2652. }
  2653. // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
  2654. // to the corresponding DebugInfoKind.
  2655. static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
  2656. assert(A.getOption().matches(options::OPT_gN_Group) &&
  2657. "Not a -g option that specifies a debug-info level");
  2658. if (A.getOption().matches(options::OPT_g0) ||
  2659. A.getOption().matches(options::OPT_ggdb0))
  2660. return codegenoptions::NoDebugInfo;
  2661. if (A.getOption().matches(options::OPT_gline_tables_only) ||
  2662. A.getOption().matches(options::OPT_ggdb1))
  2663. return codegenoptions::DebugLineTablesOnly;
  2664. return codegenoptions::LimitedDebugInfo;
  2665. }
  2666. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  2667. // on mismatch. The StringRef input (rather than an Arg) allows
  2668. // for use by the "-Xassembler" option parser.
  2669. static unsigned DwarfVersionNum(StringRef ArgValue) {
  2670. return llvm::StringSwitch<unsigned>(ArgValue)
  2671. .Case("-gdwarf-2", 2)
  2672. .Case("-gdwarf-3", 3)
  2673. .Case("-gdwarf-4", 4)
  2674. .Case("-gdwarf-5", 5)
  2675. .Default(0);
  2676. }
  2677. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2678. codegenoptions::DebugInfoKind DebugInfoKind,
  2679. unsigned DwarfVersion,
  2680. llvm::DebuggerKind DebuggerTuning) {
  2681. switch (DebugInfoKind) {
  2682. case codegenoptions::DebugLineTablesOnly:
  2683. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  2684. break;
  2685. case codegenoptions::LimitedDebugInfo:
  2686. CmdArgs.push_back("-debug-info-kind=limited");
  2687. break;
  2688. case codegenoptions::FullDebugInfo:
  2689. CmdArgs.push_back("-debug-info-kind=standalone");
  2690. break;
  2691. default:
  2692. break;
  2693. }
  2694. if (DwarfVersion > 0)
  2695. CmdArgs.push_back(
  2696. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  2697. switch (DebuggerTuning) {
  2698. case llvm::DebuggerKind::GDB:
  2699. CmdArgs.push_back("-debugger-tuning=gdb");
  2700. break;
  2701. case llvm::DebuggerKind::LLDB:
  2702. CmdArgs.push_back("-debugger-tuning=lldb");
  2703. break;
  2704. case llvm::DebuggerKind::SCE:
  2705. CmdArgs.push_back("-debugger-tuning=sce");
  2706. break;
  2707. default:
  2708. break;
  2709. }
  2710. }
  2711. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2712. const ArgList &Args,
  2713. ArgStringList &CmdArgs,
  2714. const Driver &D) {
  2715. if (UseRelaxAll(C, Args))
  2716. CmdArgs.push_back("-mrelax-all");
  2717. // Only default to -mincremental-linker-compatible if we think we are
  2718. // targeting the MSVC linker.
  2719. bool DefaultIncrementalLinkerCompatible =
  2720. C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
  2721. if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
  2722. options::OPT_mno_incremental_linker_compatible,
  2723. DefaultIncrementalLinkerCompatible))
  2724. CmdArgs.push_back("-mincremental-linker-compatible");
  2725. switch (C.getDefaultToolChain().getArch()) {
  2726. case llvm::Triple::arm:
  2727. case llvm::Triple::armeb:
  2728. case llvm::Triple::thumb:
  2729. case llvm::Triple::thumbeb:
  2730. if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
  2731. StringRef Value = A->getValue();
  2732. if (Value == "always" || Value == "never" || Value == "arm" ||
  2733. Value == "thumb") {
  2734. CmdArgs.push_back("-mllvm");
  2735. CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
  2736. } else {
  2737. D.Diag(diag::err_drv_unsupported_option_argument)
  2738. << A->getOption().getName() << Value;
  2739. }
  2740. }
  2741. break;
  2742. default:
  2743. break;
  2744. }
  2745. // When passing -I arguments to the assembler we sometimes need to
  2746. // unconditionally take the next argument. For example, when parsing
  2747. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2748. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2749. // arg after parsing the '-I' arg.
  2750. bool TakeNextArg = false;
  2751. // When using an integrated assembler, translate -Wa, and -Xassembler
  2752. // options.
  2753. bool CompressDebugSections = false;
  2754. bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
  2755. const char *MipsTargetFeature = nullptr;
  2756. for (const Arg *A :
  2757. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  2758. A->claim();
  2759. for (StringRef Value : A->getValues()) {
  2760. if (TakeNextArg) {
  2761. CmdArgs.push_back(Value.data());
  2762. TakeNextArg = false;
  2763. continue;
  2764. }
  2765. if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
  2766. Value == "-mbig-obj")
  2767. continue; // LLVM handles bigobj automatically
  2768. switch (C.getDefaultToolChain().getArch()) {
  2769. default:
  2770. break;
  2771. case llvm::Triple::mips:
  2772. case llvm::Triple::mipsel:
  2773. case llvm::Triple::mips64:
  2774. case llvm::Triple::mips64el:
  2775. if (Value == "--trap") {
  2776. CmdArgs.push_back("-target-feature");
  2777. CmdArgs.push_back("+use-tcc-in-div");
  2778. continue;
  2779. }
  2780. if (Value == "--break") {
  2781. CmdArgs.push_back("-target-feature");
  2782. CmdArgs.push_back("-use-tcc-in-div");
  2783. continue;
  2784. }
  2785. if (Value.startswith("-msoft-float")) {
  2786. CmdArgs.push_back("-target-feature");
  2787. CmdArgs.push_back("+soft-float");
  2788. continue;
  2789. }
  2790. if (Value.startswith("-mhard-float")) {
  2791. CmdArgs.push_back("-target-feature");
  2792. CmdArgs.push_back("-soft-float");
  2793. continue;
  2794. }
  2795. MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
  2796. .Case("-mips1", "+mips1")
  2797. .Case("-mips2", "+mips2")
  2798. .Case("-mips3", "+mips3")
  2799. .Case("-mips4", "+mips4")
  2800. .Case("-mips5", "+mips5")
  2801. .Case("-mips32", "+mips32")
  2802. .Case("-mips32r2", "+mips32r2")
  2803. .Case("-mips32r3", "+mips32r3")
  2804. .Case("-mips32r5", "+mips32r5")
  2805. .Case("-mips32r6", "+mips32r6")
  2806. .Case("-mips64", "+mips64")
  2807. .Case("-mips64r2", "+mips64r2")
  2808. .Case("-mips64r3", "+mips64r3")
  2809. .Case("-mips64r5", "+mips64r5")
  2810. .Case("-mips64r6", "+mips64r6")
  2811. .Default(nullptr);
  2812. if (MipsTargetFeature)
  2813. continue;
  2814. }
  2815. if (Value == "-force_cpusubtype_ALL") {
  2816. // Do nothing, this is the default and we don't support anything else.
  2817. } else if (Value == "-L") {
  2818. CmdArgs.push_back("-msave-temp-labels");
  2819. } else if (Value == "--fatal-warnings") {
  2820. CmdArgs.push_back("-massembler-fatal-warnings");
  2821. } else if (Value == "--noexecstack") {
  2822. CmdArgs.push_back("-mnoexecstack");
  2823. } else if (Value == "-compress-debug-sections" ||
  2824. Value == "--compress-debug-sections") {
  2825. CompressDebugSections = true;
  2826. } else if (Value == "-nocompress-debug-sections" ||
  2827. Value == "--nocompress-debug-sections") {
  2828. CompressDebugSections = false;
  2829. } else if (Value == "-mrelax-relocations=yes" ||
  2830. Value == "--mrelax-relocations=yes") {
  2831. UseRelaxRelocations = true;
  2832. } else if (Value == "-mrelax-relocations=no" ||
  2833. Value == "--mrelax-relocations=no") {
  2834. UseRelaxRelocations = false;
  2835. } else if (Value.startswith("-I")) {
  2836. CmdArgs.push_back(Value.data());
  2837. // We need to consume the next argument if the current arg is a plain
  2838. // -I. The next arg will be the include directory.
  2839. if (Value == "-I")
  2840. TakeNextArg = true;
  2841. } else if (Value.startswith("-gdwarf-")) {
  2842. // "-gdwarf-N" options are not cc1as options.
  2843. unsigned DwarfVersion = DwarfVersionNum(Value);
  2844. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2845. CmdArgs.push_back(Value.data());
  2846. } else {
  2847. RenderDebugEnablingArgs(Args, CmdArgs,
  2848. codegenoptions::LimitedDebugInfo,
  2849. DwarfVersion, llvm::DebuggerKind::Default);
  2850. }
  2851. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2852. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2853. // Do nothing, we'll validate it later.
  2854. } else if (Value == "-defsym") {
  2855. if (A->getNumValues() != 2) {
  2856. D.Diag(diag::err_drv_defsym_invalid_format) << Value;
  2857. break;
  2858. }
  2859. const char *S = A->getValue(1);
  2860. auto Pair = StringRef(S).split('=');
  2861. auto Sym = Pair.first;
  2862. auto SVal = Pair.second;
  2863. if (Sym.empty() || SVal.empty()) {
  2864. D.Diag(diag::err_drv_defsym_invalid_format) << S;
  2865. break;
  2866. }
  2867. int64_t IVal;
  2868. if (SVal.getAsInteger(0, IVal)) {
  2869. D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
  2870. break;
  2871. }
  2872. CmdArgs.push_back(Value.data());
  2873. TakeNextArg = true;
  2874. } else {
  2875. D.Diag(diag::err_drv_unsupported_option_argument)
  2876. << A->getOption().getName() << Value;
  2877. }
  2878. }
  2879. }
  2880. if (CompressDebugSections) {
  2881. if (llvm::zlib::isAvailable())
  2882. CmdArgs.push_back("-compress-debug-sections");
  2883. else
  2884. D.Diag(diag::warn_debug_compression_unavailable);
  2885. }
  2886. if (UseRelaxRelocations)
  2887. CmdArgs.push_back("--mrelax-relocations");
  2888. if (MipsTargetFeature != nullptr) {
  2889. CmdArgs.push_back("-target-feature");
  2890. CmdArgs.push_back(MipsTargetFeature);
  2891. }
  2892. }
  2893. // This adds the static libclang_rt.builtins-arch.a directly to the command line
  2894. // FIXME: Make sure we can also emit shared objects if they're requested
  2895. // and available, check for possible errors, etc.
  2896. static void addClangRT(const ToolChain &TC, const ArgList &Args,
  2897. ArgStringList &CmdArgs) {
  2898. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  2899. }
  2900. static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  2901. const ArgList &Args) {
  2902. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  2903. options::OPT_fno_openmp, false))
  2904. return;
  2905. switch (TC.getDriver().getOpenMPRuntime(Args)) {
  2906. case Driver::OMPRT_OMP:
  2907. CmdArgs.push_back("-lomp");
  2908. break;
  2909. case Driver::OMPRT_GOMP:
  2910. CmdArgs.push_back("-lgomp");
  2911. break;
  2912. case Driver::OMPRT_IOMP5:
  2913. CmdArgs.push_back("-liomp5");
  2914. break;
  2915. case Driver::OMPRT_Unknown:
  2916. // Already diagnosed.
  2917. break;
  2918. }
  2919. }
  2920. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  2921. ArgStringList &CmdArgs, StringRef Sanitizer,
  2922. bool IsShared, bool IsWhole) {
  2923. // Wrap any static runtimes that must be forced into executable in
  2924. // whole-archive.
  2925. if (IsWhole) CmdArgs.push_back("-whole-archive");
  2926. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
  2927. if (IsWhole) CmdArgs.push_back("-no-whole-archive");
  2928. }
  2929. // Tries to use a file with the list of dynamic symbols that need to be exported
  2930. // from the runtime library. Returns true if the file was found.
  2931. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  2932. ArgStringList &CmdArgs,
  2933. StringRef Sanitizer) {
  2934. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  2935. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  2936. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  2937. return true;
  2938. }
  2939. return false;
  2940. }
  2941. static void linkSanitizerRuntimeDeps(const ToolChain &TC,
  2942. ArgStringList &CmdArgs) {
  2943. // Force linking against the system libraries sanitizers depends on
  2944. // (see PR15823 why this is necessary).
  2945. CmdArgs.push_back("--no-as-needed");
  2946. // There's no libpthread or librt on RTEMS.
  2947. if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
  2948. CmdArgs.push_back("-lpthread");
  2949. CmdArgs.push_back("-lrt");
  2950. }
  2951. CmdArgs.push_back("-lm");
  2952. // There's no libdl on FreeBSD or RTEMS.
  2953. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
  2954. TC.getTriple().getOS() != llvm::Triple::RTEMS)
  2955. CmdArgs.push_back("-ldl");
  2956. }
  2957. static void
  2958. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2959. SmallVectorImpl<StringRef> &SharedRuntimes,
  2960. SmallVectorImpl<StringRef> &StaticRuntimes,
  2961. SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
  2962. SmallVectorImpl<StringRef> &HelperStaticRuntimes,
  2963. SmallVectorImpl<StringRef> &RequiredSymbols) {
  2964. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2965. // Collect shared runtimes.
  2966. if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
  2967. SharedRuntimes.push_back("asan");
  2968. }
  2969. // The stats_client library is also statically linked into DSOs.
  2970. if (SanArgs.needsStatsRt())
  2971. StaticRuntimes.push_back("stats_client");
  2972. // Collect static runtimes.
  2973. if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
  2974. // Don't link static runtimes into DSOs or if compiling for Android.
  2975. return;
  2976. }
  2977. if (SanArgs.needsAsanRt()) {
  2978. if (SanArgs.needsSharedAsanRt()) {
  2979. HelperStaticRuntimes.push_back("asan-preinit");
  2980. } else {
  2981. StaticRuntimes.push_back("asan");
  2982. if (SanArgs.linkCXXRuntimes())
  2983. StaticRuntimes.push_back("asan_cxx");
  2984. }
  2985. }
  2986. if (SanArgs.needsDfsanRt())
  2987. StaticRuntimes.push_back("dfsan");
  2988. if (SanArgs.needsLsanRt())
  2989. StaticRuntimes.push_back("lsan");
  2990. if (SanArgs.needsMsanRt()) {
  2991. StaticRuntimes.push_back("msan");
  2992. if (SanArgs.linkCXXRuntimes())
  2993. StaticRuntimes.push_back("msan_cxx");
  2994. }
  2995. if (SanArgs.needsTsanRt()) {
  2996. StaticRuntimes.push_back("tsan");
  2997. if (SanArgs.linkCXXRuntimes())
  2998. StaticRuntimes.push_back("tsan_cxx");
  2999. }
  3000. if (SanArgs.needsUbsanRt()) {
  3001. StaticRuntimes.push_back("ubsan_standalone");
  3002. if (SanArgs.linkCXXRuntimes())
  3003. StaticRuntimes.push_back("ubsan_standalone_cxx");
  3004. }
  3005. if (SanArgs.needsSafeStackRt()) {
  3006. NonWholeStaticRuntimes.push_back("safestack");
  3007. RequiredSymbols.push_back("__safestack_init");
  3008. }
  3009. if (SanArgs.needsCfiRt())
  3010. StaticRuntimes.push_back("cfi");
  3011. if (SanArgs.needsCfiDiagRt()) {
  3012. StaticRuntimes.push_back("cfi_diag");
  3013. if (SanArgs.linkCXXRuntimes())
  3014. StaticRuntimes.push_back("ubsan_standalone_cxx");
  3015. }
  3016. if (SanArgs.needsStatsRt()) {
  3017. NonWholeStaticRuntimes.push_back("stats");
  3018. RequiredSymbols.push_back("__sanitizer_stats_register");
  3019. }
  3020. if (SanArgs.needsEsanRt())
  3021. StaticRuntimes.push_back("esan");
  3022. }
  3023. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  3024. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  3025. static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  3026. ArgStringList &CmdArgs) {
  3027. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  3028. NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
  3029. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  3030. NonWholeStaticRuntimes, HelperStaticRuntimes,
  3031. RequiredSymbols);
  3032. for (auto RT : SharedRuntimes)
  3033. addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
  3034. for (auto RT : HelperStaticRuntimes)
  3035. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  3036. bool AddExportDynamic = false;
  3037. for (auto RT : StaticRuntimes) {
  3038. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  3039. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  3040. }
  3041. for (auto RT : NonWholeStaticRuntimes) {
  3042. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
  3043. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  3044. }
  3045. for (auto S : RequiredSymbols) {
  3046. CmdArgs.push_back("-u");
  3047. CmdArgs.push_back(Args.MakeArgString(S));
  3048. }
  3049. // If there is a static runtime with no dynamic list, force all the symbols
  3050. // to be dynamic to be sure we export sanitizer interface functions.
  3051. if (AddExportDynamic)
  3052. CmdArgs.push_back("-export-dynamic");
  3053. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  3054. if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
  3055. CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
  3056. return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
  3057. }
  3058. static bool addXRayRuntime(const ToolChain &TC, const ArgList &Args,
  3059. ArgStringList &CmdArgs) {
  3060. if (Args.hasFlag(options::OPT_fxray_instrument,
  3061. options::OPT_fnoxray_instrument, false)) {
  3062. CmdArgs.push_back("-whole-archive");
  3063. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
  3064. CmdArgs.push_back("-no-whole-archive");
  3065. return true;
  3066. }
  3067. return false;
  3068. }
  3069. static void linkXRayRuntimeDeps(const ToolChain &TC, const ArgList &Args,
  3070. ArgStringList &CmdArgs) {
  3071. CmdArgs.push_back("--no-as-needed");
  3072. CmdArgs.push_back("-lpthread");
  3073. CmdArgs.push_back("-lrt");
  3074. CmdArgs.push_back("-lm");
  3075. CmdArgs.push_back("-latomic");
  3076. if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  3077. CmdArgs.push_back("-lc++");
  3078. else
  3079. CmdArgs.push_back("-lstdc++");
  3080. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
  3081. CmdArgs.push_back("-ldl");
  3082. }
  3083. static bool areOptimizationsEnabled(const ArgList &Args) {
  3084. // Find the last -O arg and see if it is non-zero.
  3085. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  3086. return !A->getOption().matches(options::OPT_O0);
  3087. // Defaults to -O0.
  3088. return false;
  3089. }
  3090. static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
  3091. switch (Triple.getArch()){
  3092. default:
  3093. return false;
  3094. case llvm::Triple::arm:
  3095. case llvm::Triple::thumb:
  3096. // ARM Darwin targets require a frame pointer to be always present to aid
  3097. // offline debugging via backtraces.
  3098. return Triple.isOSDarwin();
  3099. }
  3100. }
  3101. static bool useFramePointerForTargetByDefault(const ArgList &Args,
  3102. const llvm::Triple &Triple) {
  3103. switch (Triple.getArch()) {
  3104. case llvm::Triple::xcore:
  3105. case llvm::Triple::wasm32:
  3106. case llvm::Triple::wasm64:
  3107. // XCore never wants frame pointers, regardless of OS.
  3108. // WebAssembly never wants frame pointers.
  3109. return false;
  3110. default:
  3111. break;
  3112. }
  3113. if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
  3114. switch (Triple.getArch()) {
  3115. // Don't use a frame pointer on linux if optimizing for certain targets.
  3116. case llvm::Triple::mips64:
  3117. case llvm::Triple::mips64el:
  3118. case llvm::Triple::mips:
  3119. case llvm::Triple::mipsel:
  3120. case llvm::Triple::systemz:
  3121. case llvm::Triple::x86:
  3122. case llvm::Triple::x86_64:
  3123. return !areOptimizationsEnabled(Args);
  3124. default:
  3125. return true;
  3126. }
  3127. }
  3128. if (Triple.isOSWindows()) {
  3129. switch (Triple.getArch()) {
  3130. case llvm::Triple::x86:
  3131. return !areOptimizationsEnabled(Args);
  3132. case llvm::Triple::x86_64:
  3133. return Triple.isOSBinFormatMachO();
  3134. case llvm::Triple::arm:
  3135. case llvm::Triple::thumb:
  3136. // Windows on ARM builds with FPO disabled to aid fast stack walking
  3137. return true;
  3138. default:
  3139. // All other supported Windows ISAs use xdata unwind information, so frame
  3140. // pointers are not generally useful.
  3141. return false;
  3142. }
  3143. }
  3144. return true;
  3145. }
  3146. static bool shouldUseFramePointer(const ArgList &Args,
  3147. const llvm::Triple &Triple) {
  3148. if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
  3149. options::OPT_fomit_frame_pointer))
  3150. return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
  3151. mustUseNonLeafFramePointerForTarget(Triple);
  3152. if (Args.hasArg(options::OPT_pg))
  3153. return true;
  3154. return useFramePointerForTargetByDefault(Args, Triple);
  3155. }
  3156. static bool shouldUseLeafFramePointer(const ArgList &Args,
  3157. const llvm::Triple &Triple) {
  3158. if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
  3159. options::OPT_momit_leaf_frame_pointer))
  3160. return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
  3161. if (Args.hasArg(options::OPT_pg))
  3162. return true;
  3163. if (Triple.isPS4CPU())
  3164. return false;
  3165. return useFramePointerForTargetByDefault(Args, Triple);
  3166. }
  3167. /// Add a CC1 option to specify the debug compilation directory.
  3168. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
  3169. SmallString<128> cwd;
  3170. if (!llvm::sys::fs::current_path(cwd)) {
  3171. CmdArgs.push_back("-fdebug-compilation-dir");
  3172. CmdArgs.push_back(Args.MakeArgString(cwd));
  3173. }
  3174. }
  3175. static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
  3176. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  3177. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  3178. SmallString<128> T(FinalOutput->getValue());
  3179. llvm::sys::path::replace_extension(T, "dwo");
  3180. return Args.MakeArgString(T);
  3181. } else {
  3182. // Use the compilation dir.
  3183. SmallString<128> T(
  3184. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  3185. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  3186. llvm::sys::path::replace_extension(F, "dwo");
  3187. T += F;
  3188. return Args.MakeArgString(F);
  3189. }
  3190. }
  3191. static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  3192. const JobAction &JA, const ArgList &Args,
  3193. const InputInfo &Output, const char *OutFile) {
  3194. ArgStringList ExtractArgs;
  3195. ExtractArgs.push_back("--extract-dwo");
  3196. ArgStringList StripArgs;
  3197. StripArgs.push_back("--strip-dwo");
  3198. // Grabbing the output of the earlier compile step.
  3199. StripArgs.push_back(Output.getFilename());
  3200. ExtractArgs.push_back(Output.getFilename());
  3201. ExtractArgs.push_back(OutFile);
  3202. const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
  3203. InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
  3204. // First extract the dwo sections.
  3205. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  3206. // Then remove them from the original .o file.
  3207. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
  3208. }
  3209. /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
  3210. /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
  3211. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  3212. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  3213. if (A->getOption().matches(options::OPT_O4) ||
  3214. A->getOption().matches(options::OPT_Ofast))
  3215. return true;
  3216. if (A->getOption().matches(options::OPT_O0))
  3217. return false;
  3218. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  3219. // Vectorize -Os.
  3220. StringRef S(A->getValue());
  3221. if (S == "s")
  3222. return true;
  3223. // Don't vectorize -Oz, unless it's the slp vectorizer.
  3224. if (S == "z")
  3225. return isSlpVec;
  3226. unsigned OptLevel = 0;
  3227. if (S.getAsInteger(10, OptLevel))
  3228. return false;
  3229. return OptLevel > 1;
  3230. }
  3231. return false;
  3232. }
  3233. /// Add -x lang to \p CmdArgs for \p Input.
  3234. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  3235. ArgStringList &CmdArgs) {
  3236. // When using -verify-pch, we don't want to provide the type
  3237. // 'precompiled-header' if it was inferred from the file extension
  3238. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  3239. return;
  3240. CmdArgs.push_back("-x");
  3241. if (Args.hasArg(options::OPT_rewrite_objc))
  3242. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  3243. else
  3244. CmdArgs.push_back(types::getTypeName(Input.getType()));
  3245. }
  3246. // Claim options we don't want to warn if they are unused. We do this for
  3247. // options that build systems might add but are unused when assembling or only
  3248. // running the preprocessor for example.
  3249. static void claimNoWarnArgs(const ArgList &Args) {
  3250. // Don't warn about unused -f(no-)?lto. This can happen when we're
  3251. // preprocessing, precompiling or assembling.
  3252. Args.ClaimAllArgs(options::OPT_flto_EQ);
  3253. Args.ClaimAllArgs(options::OPT_flto);
  3254. Args.ClaimAllArgs(options::OPT_fno_lto);
  3255. }
  3256. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  3257. #ifdef LLVM_ON_UNIX
  3258. const char *Username = getenv("LOGNAME");
  3259. #else
  3260. const char *Username = getenv("USERNAME");
  3261. #endif
  3262. if (Username) {
  3263. // Validate that LoginName can be used in a path, and get its length.
  3264. size_t Len = 0;
  3265. for (const char *P = Username; *P; ++P, ++Len) {
  3266. if (!isAlphanumeric(*P) && *P != '_') {
  3267. Username = nullptr;
  3268. break;
  3269. }
  3270. }
  3271. if (Username && Len > 0) {
  3272. Result.append(Username, Username + Len);
  3273. return;
  3274. }
  3275. }
  3276. // Fallback to user id.
  3277. #ifdef LLVM_ON_UNIX
  3278. std::string UID = llvm::utostr(getuid());
  3279. #else
  3280. // FIXME: Windows seems to have an 'SID' that might work.
  3281. std::string UID = "9999";
  3282. #endif
  3283. Result.append(UID.begin(), UID.end());
  3284. }
  3285. static Arg *getLastProfileUseArg(const ArgList &Args) {
  3286. auto *ProfileUseArg = Args.getLastArg(
  3287. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  3288. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  3289. options::OPT_fno_profile_instr_use);
  3290. if (ProfileUseArg &&
  3291. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  3292. ProfileUseArg = nullptr;
  3293. return ProfileUseArg;
  3294. }
  3295. static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
  3296. const InputInfo &Output, const ArgList &Args,
  3297. ArgStringList &CmdArgs) {
  3298. auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
  3299. options::OPT_fprofile_generate_EQ,
  3300. options::OPT_fno_profile_generate);
  3301. if (PGOGenerateArg &&
  3302. PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
  3303. PGOGenerateArg = nullptr;
  3304. auto *ProfileGenerateArg = Args.getLastArg(
  3305. options::OPT_fprofile_instr_generate,
  3306. options::OPT_fprofile_instr_generate_EQ,
  3307. options::OPT_fno_profile_instr_generate);
  3308. if (ProfileGenerateArg &&
  3309. ProfileGenerateArg->getOption().matches(
  3310. options::OPT_fno_profile_instr_generate))
  3311. ProfileGenerateArg = nullptr;
  3312. if (PGOGenerateArg && ProfileGenerateArg)
  3313. D.Diag(diag::err_drv_argument_not_allowed_with)
  3314. << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
  3315. auto *ProfileUseArg = getLastProfileUseArg(Args);
  3316. if (PGOGenerateArg && ProfileUseArg)
  3317. D.Diag(diag::err_drv_argument_not_allowed_with)
  3318. << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
  3319. if (ProfileGenerateArg && ProfileUseArg)
  3320. D.Diag(diag::err_drv_argument_not_allowed_with)
  3321. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  3322. if (ProfileGenerateArg) {
  3323. if (ProfileGenerateArg->getOption().matches(
  3324. options::OPT_fprofile_instr_generate_EQ))
  3325. CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
  3326. ProfileGenerateArg->getValue()));
  3327. // The default is to use Clang Instrumentation.
  3328. CmdArgs.push_back("-fprofile-instrument=clang");
  3329. }
  3330. if (PGOGenerateArg) {
  3331. CmdArgs.push_back("-fprofile-instrument=llvm");
  3332. if (PGOGenerateArg->getOption().matches(
  3333. options::OPT_fprofile_generate_EQ)) {
  3334. SmallString<128> Path(PGOGenerateArg->getValue());
  3335. llvm::sys::path::append(Path, "default_%m.profraw");
  3336. CmdArgs.push_back(
  3337. Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
  3338. }
  3339. }
  3340. if (ProfileUseArg) {
  3341. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  3342. CmdArgs.push_back(Args.MakeArgString(
  3343. Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
  3344. else if ((ProfileUseArg->getOption().matches(
  3345. options::OPT_fprofile_use_EQ) ||
  3346. ProfileUseArg->getOption().matches(
  3347. options::OPT_fprofile_instr_use))) {
  3348. SmallString<128> Path(
  3349. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  3350. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  3351. llvm::sys::path::append(Path, "default.profdata");
  3352. CmdArgs.push_back(
  3353. Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
  3354. }
  3355. }
  3356. if (Args.hasArg(options::OPT_ftest_coverage) ||
  3357. Args.hasArg(options::OPT_coverage))
  3358. CmdArgs.push_back("-femit-coverage-notes");
  3359. if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3360. false) ||
  3361. Args.hasArg(options::OPT_coverage))
  3362. CmdArgs.push_back("-femit-coverage-data");
  3363. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3364. options::OPT_fno_coverage_mapping, false) &&
  3365. !ProfileGenerateArg)
  3366. D.Diag(diag::err_drv_argument_only_allowed_with)
  3367. << "-fcoverage-mapping"
  3368. << "-fprofile-instr-generate";
  3369. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3370. options::OPT_fno_coverage_mapping, false))
  3371. CmdArgs.push_back("-fcoverage-mapping");
  3372. if (C.getArgs().hasArg(options::OPT_c) ||
  3373. C.getArgs().hasArg(options::OPT_S)) {
  3374. if (Output.isFilename()) {
  3375. CmdArgs.push_back("-coverage-notes-file");
  3376. SmallString<128> OutputFilename;
  3377. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  3378. OutputFilename = FinalOutput->getValue();
  3379. else
  3380. OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
  3381. SmallString<128> CoverageFilename = OutputFilename;
  3382. if (llvm::sys::path::is_relative(CoverageFilename)) {
  3383. SmallString<128> Pwd;
  3384. if (!llvm::sys::fs::current_path(Pwd)) {
  3385. llvm::sys::path::append(Pwd, CoverageFilename);
  3386. CoverageFilename.swap(Pwd);
  3387. }
  3388. }
  3389. llvm::sys::path::replace_extension(CoverageFilename, "gcno");
  3390. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  3391. // Leave -fprofile-dir= an unused argument unless .gcda emission is
  3392. // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
  3393. // the flag used. There is no -fno-profile-dir, so the user has no
  3394. // targeted way to suppress the warning.
  3395. if (Args.hasArg(options::OPT_fprofile_arcs) ||
  3396. Args.hasArg(options::OPT_coverage)) {
  3397. CmdArgs.push_back("-coverage-data-file");
  3398. if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
  3399. CoverageFilename = FProfileDir->getValue();
  3400. llvm::sys::path::append(CoverageFilename, OutputFilename);
  3401. }
  3402. llvm::sys::path::replace_extension(CoverageFilename, "gcda");
  3403. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  3404. }
  3405. }
  3406. }
  3407. }
  3408. static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
  3409. ArgStringList &CmdArgs) {
  3410. if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3411. false) ||
  3412. Args.hasFlag(options::OPT_fprofile_generate,
  3413. options::OPT_fno_profile_instr_generate, false) ||
  3414. Args.hasFlag(options::OPT_fprofile_generate_EQ,
  3415. options::OPT_fno_profile_instr_generate, false) ||
  3416. Args.hasFlag(options::OPT_fprofile_instr_generate,
  3417. options::OPT_fno_profile_instr_generate, false) ||
  3418. Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
  3419. options::OPT_fno_profile_instr_generate, false) ||
  3420. Args.hasArg(options::OPT_fcreate_profile) ||
  3421. Args.hasArg(options::OPT_coverage)))
  3422. CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
  3423. }
  3424. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  3425. /// smooshes them together with platform defaults, to decide whether
  3426. /// this compile should be using PIC mode or not. Returns a tuple of
  3427. /// (RelocationModel, PICLevel, IsPIE).
  3428. static std::tuple<llvm::Reloc::Model, unsigned, bool>
  3429. ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
  3430. const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
  3431. const llvm::Triple &Triple = ToolChain.getTriple();
  3432. bool PIE = ToolChain.isPIEDefault();
  3433. bool PIC = PIE || ToolChain.isPICDefault();
  3434. // The Darwin/MachO default to use PIC does not apply when using -static.
  3435. if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
  3436. PIE = PIC = false;
  3437. bool IsPICLevelTwo = PIC;
  3438. bool KernelOrKext =
  3439. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3440. // Android-specific defaults for PIC/PIE
  3441. if (Triple.isAndroid()) {
  3442. switch (Triple.getArch()) {
  3443. case llvm::Triple::arm:
  3444. case llvm::Triple::armeb:
  3445. case llvm::Triple::thumb:
  3446. case llvm::Triple::thumbeb:
  3447. case llvm::Triple::aarch64:
  3448. case llvm::Triple::mips:
  3449. case llvm::Triple::mipsel:
  3450. case llvm::Triple::mips64:
  3451. case llvm::Triple::mips64el:
  3452. PIC = true; // "-fpic"
  3453. break;
  3454. case llvm::Triple::x86:
  3455. case llvm::Triple::x86_64:
  3456. PIC = true; // "-fPIC"
  3457. IsPICLevelTwo = true;
  3458. break;
  3459. default:
  3460. break;
  3461. }
  3462. }
  3463. // OpenBSD-specific defaults for PIE
  3464. if (Triple.getOS() == llvm::Triple::OpenBSD) {
  3465. switch (ToolChain.getArch()) {
  3466. case llvm::Triple::mips64:
  3467. case llvm::Triple::mips64el:
  3468. case llvm::Triple::sparcel:
  3469. case llvm::Triple::x86:
  3470. case llvm::Triple::x86_64:
  3471. IsPICLevelTwo = false; // "-fpie"
  3472. break;
  3473. case llvm::Triple::ppc:
  3474. case llvm::Triple::sparc:
  3475. case llvm::Triple::sparcv9:
  3476. IsPICLevelTwo = true; // "-fPIE"
  3477. break;
  3478. default:
  3479. break;
  3480. }
  3481. }
  3482. // The last argument relating to either PIC or PIE wins, and no
  3483. // other argument is used. If the last argument is any flavor of the
  3484. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  3485. // option implicitly enables PIC at the same level.
  3486. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  3487. options::OPT_fpic, options::OPT_fno_pic,
  3488. options::OPT_fPIE, options::OPT_fno_PIE,
  3489. options::OPT_fpie, options::OPT_fno_pie);
  3490. if (Triple.isOSWindows() && LastPICArg &&
  3491. LastPICArg ==
  3492. Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
  3493. options::OPT_fPIE, options::OPT_fpie)) {
  3494. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3495. << LastPICArg->getSpelling() << Triple.str();
  3496. if (Triple.getArch() == llvm::Triple::x86_64)
  3497. return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
  3498. return std::make_tuple(llvm::Reloc::Static, 0U, false);
  3499. }
  3500. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  3501. // is forced, then neither PIC nor PIE flags will have no effect.
  3502. if (!ToolChain.isPICDefaultForced()) {
  3503. if (LastPICArg) {
  3504. Option O = LastPICArg->getOption();
  3505. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  3506. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  3507. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  3508. PIC =
  3509. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  3510. IsPICLevelTwo =
  3511. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  3512. } else {
  3513. PIE = PIC = false;
  3514. if (EffectiveTriple.isPS4CPU()) {
  3515. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  3516. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  3517. if (Model != "kernel") {
  3518. PIC = true;
  3519. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  3520. << LastPICArg->getSpelling();
  3521. }
  3522. }
  3523. }
  3524. }
  3525. }
  3526. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  3527. // PIC level would've been set to level 1, force it back to level 2 PIC
  3528. // instead.
  3529. if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
  3530. IsPICLevelTwo |= ToolChain.isPICDefault();
  3531. // This kernel flags are a trump-card: they will disable PIC/PIE
  3532. // generation, independent of the argument order.
  3533. if (KernelOrKext &&
  3534. ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
  3535. !EffectiveTriple.isWatchOS()))
  3536. PIC = PIE = false;
  3537. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  3538. // This is a very special mode. It trumps the other modes, almost no one
  3539. // uses it, and it isn't even valid on any OS but Darwin.
  3540. if (!Triple.isOSDarwin())
  3541. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3542. << A->getSpelling() << Triple.str();
  3543. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  3544. // Only a forced PIC mode can cause the actual compile to have PIC defines
  3545. // etc., no flags are sufficient. This behavior was selected to closely
  3546. // match that of llvm-gcc and Apple GCC before that.
  3547. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  3548. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
  3549. }
  3550. bool EmbeddedPISupported;
  3551. switch (Triple.getArch()) {
  3552. case llvm::Triple::arm:
  3553. case llvm::Triple::armeb:
  3554. case llvm::Triple::thumb:
  3555. case llvm::Triple::thumbeb:
  3556. EmbeddedPISupported = true;
  3557. break;
  3558. default:
  3559. EmbeddedPISupported = false;
  3560. break;
  3561. }
  3562. bool ROPI = false, RWPI = false;
  3563. Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
  3564. if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
  3565. if (!EmbeddedPISupported)
  3566. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3567. << LastROPIArg->getSpelling() << Triple.str();
  3568. ROPI = true;
  3569. }
  3570. Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
  3571. if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
  3572. if (!EmbeddedPISupported)
  3573. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3574. << LastRWPIArg->getSpelling() << Triple.str();
  3575. RWPI = true;
  3576. }
  3577. // ROPI and RWPI are not comaptible with PIC or PIE.
  3578. if ((ROPI || RWPI) && (PIC || PIE))
  3579. ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
  3580. // When targettng MIPS64 with N64, the default is PIC, unless -mno-abicalls is
  3581. // used.
  3582. if ((Triple.getArch() == llvm::Triple::mips64 ||
  3583. Triple.getArch() == llvm::Triple::mips64el) &&
  3584. Args.hasArg(options::OPT_mno_abicalls))
  3585. return std::make_tuple(llvm::Reloc::Static, 0U, false);
  3586. if (PIC)
  3587. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
  3588. llvm::Reloc::Model RelocM = llvm::Reloc::Static;
  3589. if (ROPI && RWPI)
  3590. RelocM = llvm::Reloc::ROPI_RWPI;
  3591. else if (ROPI)
  3592. RelocM = llvm::Reloc::ROPI;
  3593. else if (RWPI)
  3594. RelocM = llvm::Reloc::RWPI;
  3595. return std::make_tuple(RelocM, 0U, false);
  3596. }
  3597. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  3598. switch (Model) {
  3599. case llvm::Reloc::Static:
  3600. return "static";
  3601. case llvm::Reloc::PIC_:
  3602. return "pic";
  3603. case llvm::Reloc::DynamicNoPIC:
  3604. return "dynamic-no-pic";
  3605. case llvm::Reloc::ROPI:
  3606. return "ropi";
  3607. case llvm::Reloc::RWPI:
  3608. return "rwpi";
  3609. case llvm::Reloc::ROPI_RWPI:
  3610. return "ropi-rwpi";
  3611. }
  3612. llvm_unreachable("Unknown Reloc::Model kind");
  3613. }
  3614. static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  3615. ArgStringList &CmdArgs) {
  3616. llvm::Reloc::Model RelocationModel;
  3617. unsigned PICLevel;
  3618. bool IsPIE;
  3619. std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
  3620. if (RelocationModel != llvm::Reloc::Static)
  3621. CmdArgs.push_back("-KPIC");
  3622. }
  3623. void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
  3624. StringRef Target, const InputInfo &Output,
  3625. const InputInfo &Input, const ArgList &Args) const {
  3626. // If this is a dry run, do not create the compilation database file.
  3627. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
  3628. return;
  3629. using llvm::yaml::escape;
  3630. const Driver &D = getToolChain().getDriver();
  3631. if (!CompilationDatabase) {
  3632. std::error_code EC;
  3633. auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
  3634. if (EC) {
  3635. D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
  3636. << EC.message();
  3637. return;
  3638. }
  3639. CompilationDatabase = std::move(File);
  3640. }
  3641. auto &CDB = *CompilationDatabase;
  3642. SmallString<128> Buf;
  3643. if (llvm::sys::fs::current_path(Buf))
  3644. Buf = ".";
  3645. CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
  3646. CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
  3647. CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
  3648. CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
  3649. Buf = "-x";
  3650. Buf += types::getTypeName(Input.getType());
  3651. CDB << ", \"" << escape(Buf) << "\"";
  3652. if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
  3653. Buf = "--sysroot=";
  3654. Buf += D.SysRoot;
  3655. CDB << ", \"" << escape(Buf) << "\"";
  3656. }
  3657. CDB << ", \"" << escape(Input.getFilename()) << "\"";
  3658. for (auto &A: Args) {
  3659. auto &O = A->getOption();
  3660. // Skip language selection, which is positional.
  3661. if (O.getID() == options::OPT_x)
  3662. continue;
  3663. // Skip writing dependency output and the compilation database itself.
  3664. if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
  3665. continue;
  3666. // Skip inputs.
  3667. if (O.getKind() == Option::InputClass)
  3668. continue;
  3669. // All other arguments are quoted and appended.
  3670. ArgStringList ASL;
  3671. A->render(Args, ASL);
  3672. for (auto &it: ASL)
  3673. CDB << ", \"" << escape(it) << "\"";
  3674. }
  3675. Buf = "--target=";
  3676. Buf += Target;
  3677. CDB << ", \"" << escape(Buf) << "\"]},\n";
  3678. }
  3679. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  3680. const InputInfo &Output, const InputInfoList &Inputs,
  3681. const ArgList &Args, const char *LinkingOutput) const {
  3682. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  3683. const std::string &TripleStr = Triple.getTriple();
  3684. bool KernelOrKext =
  3685. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3686. const Driver &D = getToolChain().getDriver();
  3687. ArgStringList CmdArgs;
  3688. // Check number of inputs for sanity. We need at least one input.
  3689. assert(Inputs.size() >= 1 && "Must have at least one input.");
  3690. const InputInfo &Input = Inputs[0];
  3691. // CUDA compilation may have multiple inputs (source file + results of
  3692. // device-side compilations). OpenMP device jobs also take the host IR as a
  3693. // second input. All other jobs are expected to have exactly one
  3694. // input.
  3695. bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
  3696. bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
  3697. assert((IsCuda || (IsOpenMPDevice && Inputs.size() == 2) ||
  3698. Inputs.size() == 1) &&
  3699. "Unable to handle multiple inputs.");
  3700. bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
  3701. bool IsWindowsCygnus =
  3702. getToolChain().getTriple().isWindowsCygwinEnvironment();
  3703. bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
  3704. bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
  3705. bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
  3706. // Adjust IsWindowsXYZ for CUDA compilations. Even when compiling in device
  3707. // mode (i.e., getToolchain().getTriple() is NVPTX, not Windows), we need to
  3708. // pass Windows-specific flags to cc1.
  3709. if (IsCuda) {
  3710. const llvm::Triple *AuxTriple = getToolChain().getAuxTriple();
  3711. IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
  3712. IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
  3713. IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
  3714. }
  3715. // C++ is not supported for IAMCU.
  3716. if (IsIAMCU && types::isCXX(Input.getType()))
  3717. D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
  3718. // Invoke ourselves in -cc1 mode.
  3719. //
  3720. // FIXME: Implement custom jobs for internal actions.
  3721. CmdArgs.push_back("-cc1");
  3722. // Add the "effective" target triple.
  3723. CmdArgs.push_back("-triple");
  3724. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  3725. if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
  3726. DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
  3727. Args.ClaimAllArgs(options::OPT_MJ);
  3728. }
  3729. if (IsCuda) {
  3730. // We have to pass the triple of the host if compiling for a CUDA device and
  3731. // vice-versa.
  3732. std::string NormalizedTriple;
  3733. if (JA.isDeviceOffloading(Action::OFK_Cuda))
  3734. NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
  3735. ->getTriple()
  3736. .normalize();
  3737. else
  3738. NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
  3739. ->getTriple()
  3740. .normalize();
  3741. CmdArgs.push_back("-aux-triple");
  3742. CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
  3743. }
  3744. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  3745. Triple.getArch() == llvm::Triple::thumb)) {
  3746. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  3747. unsigned Version;
  3748. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  3749. if (Version < 7)
  3750. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  3751. << TripleStr;
  3752. }
  3753. // Push all default warning arguments that are specific to
  3754. // the given target. These come before user provided warning options
  3755. // are provided.
  3756. getToolChain().addClangWarningOptions(CmdArgs);
  3757. // Select the appropriate action.
  3758. RewriteKind rewriteKind = RK_None;
  3759. if (isa<AnalyzeJobAction>(JA)) {
  3760. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  3761. CmdArgs.push_back("-analyze");
  3762. } else if (isa<MigrateJobAction>(JA)) {
  3763. CmdArgs.push_back("-migrate");
  3764. } else if (isa<PreprocessJobAction>(JA)) {
  3765. if (Output.getType() == types::TY_Dependencies)
  3766. CmdArgs.push_back("-Eonly");
  3767. else {
  3768. CmdArgs.push_back("-E");
  3769. if (Args.hasArg(options::OPT_rewrite_objc) &&
  3770. !Args.hasArg(options::OPT_g_Group))
  3771. CmdArgs.push_back("-P");
  3772. }
  3773. } else if (isa<AssembleJobAction>(JA)) {
  3774. CmdArgs.push_back("-emit-obj");
  3775. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  3776. // Also ignore explicit -force_cpusubtype_ALL option.
  3777. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  3778. } else if (isa<PrecompileJobAction>(JA)) {
  3779. // Use PCH if the user requested it.
  3780. bool UsePCH = D.CCCUsePCH;
  3781. if (JA.getType() == types::TY_Nothing)
  3782. CmdArgs.push_back("-fsyntax-only");
  3783. else if (JA.getType() == types::TY_ModuleFile)
  3784. CmdArgs.push_back("-emit-module-interface");
  3785. else if (UsePCH)
  3786. CmdArgs.push_back("-emit-pch");
  3787. else
  3788. CmdArgs.push_back("-emit-pth");
  3789. } else if (isa<VerifyPCHJobAction>(JA)) {
  3790. CmdArgs.push_back("-verify-pch");
  3791. } else {
  3792. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  3793. "Invalid action for clang tool.");
  3794. if (JA.getType() == types::TY_Nothing) {
  3795. CmdArgs.push_back("-fsyntax-only");
  3796. } else if (JA.getType() == types::TY_LLVM_IR ||
  3797. JA.getType() == types::TY_LTO_IR) {
  3798. CmdArgs.push_back("-emit-llvm");
  3799. } else if (JA.getType() == types::TY_LLVM_BC ||
  3800. JA.getType() == types::TY_LTO_BC) {
  3801. CmdArgs.push_back("-emit-llvm-bc");
  3802. } else if (JA.getType() == types::TY_PP_Asm) {
  3803. CmdArgs.push_back("-S");
  3804. } else if (JA.getType() == types::TY_AST) {
  3805. CmdArgs.push_back("-emit-pch");
  3806. } else if (JA.getType() == types::TY_ModuleFile) {
  3807. CmdArgs.push_back("-module-file-info");
  3808. } else if (JA.getType() == types::TY_RewrittenObjC) {
  3809. CmdArgs.push_back("-rewrite-objc");
  3810. rewriteKind = RK_NonFragile;
  3811. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  3812. CmdArgs.push_back("-rewrite-objc");
  3813. rewriteKind = RK_Fragile;
  3814. } else {
  3815. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  3816. }
  3817. // Preserve use-list order by default when emitting bitcode, so that
  3818. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  3819. // same result as running passes here. For LTO, we don't need to preserve
  3820. // the use-list order, since serialization to bitcode is part of the flow.
  3821. if (JA.getType() == types::TY_LLVM_BC)
  3822. CmdArgs.push_back("-emit-llvm-uselists");
  3823. if (D.isUsingLTO()) {
  3824. Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
  3825. // The Darwin linker currently uses the legacy LTO API, which does not
  3826. // support LTO unit features (CFI, whole program vtable opt) under
  3827. // ThinLTO.
  3828. if (!getToolChain().getTriple().isOSDarwin() ||
  3829. D.getLTOMode() == LTOK_Full)
  3830. CmdArgs.push_back("-flto-unit");
  3831. }
  3832. }
  3833. if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
  3834. if (!types::isLLVMIR(Input.getType()))
  3835. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3836. << "-x ir";
  3837. Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
  3838. }
  3839. // Embed-bitcode option.
  3840. if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
  3841. (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
  3842. // Add flags implied by -fembed-bitcode.
  3843. Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
  3844. // Disable all llvm IR level optimizations.
  3845. CmdArgs.push_back("-disable-llvm-passes");
  3846. }
  3847. if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
  3848. CmdArgs.push_back("-fembed-bitcode=marker");
  3849. // We normally speed up the clang process a bit by skipping destructors at
  3850. // exit, but when we're generating diagnostics we can rely on some of the
  3851. // cleanup.
  3852. if (!C.isForDiagnostics())
  3853. CmdArgs.push_back("-disable-free");
  3854. // Disable the verification pass in -asserts builds.
  3855. #ifdef NDEBUG
  3856. CmdArgs.push_back("-disable-llvm-verifier");
  3857. // Discard LLVM value names in -asserts builds.
  3858. CmdArgs.push_back("-discard-value-names");
  3859. #endif
  3860. // Set the main file name, so that debug info works even with
  3861. // -save-temps.
  3862. CmdArgs.push_back("-main-file-name");
  3863. CmdArgs.push_back(getBaseInputName(Args, Input));
  3864. // Some flags which affect the language (via preprocessor
  3865. // defines).
  3866. if (Args.hasArg(options::OPT_static))
  3867. CmdArgs.push_back("-static-define");
  3868. if (isa<AnalyzeJobAction>(JA)) {
  3869. // Enable region store model by default.
  3870. CmdArgs.push_back("-analyzer-store=region");
  3871. // Treat blocks as analysis entry points.
  3872. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  3873. CmdArgs.push_back("-analyzer-eagerly-assume");
  3874. // Add default argument set.
  3875. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  3876. CmdArgs.push_back("-analyzer-checker=core");
  3877. CmdArgs.push_back("-analyzer-checker=apiModeling");
  3878. if (!IsWindowsMSVC) {
  3879. CmdArgs.push_back("-analyzer-checker=unix");
  3880. } else {
  3881. // Enable "unix" checkers that also work on Windows.
  3882. CmdArgs.push_back("-analyzer-checker=unix.API");
  3883. CmdArgs.push_back("-analyzer-checker=unix.Malloc");
  3884. CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
  3885. CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
  3886. CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
  3887. CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
  3888. }
  3889. // Disable some unix checkers for PS4.
  3890. if (IsPS4CPU) {
  3891. CmdArgs.push_back("-analyzer-disable-checker=unix.API");
  3892. CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
  3893. }
  3894. if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
  3895. CmdArgs.push_back("-analyzer-checker=osx");
  3896. CmdArgs.push_back("-analyzer-checker=deadcode");
  3897. if (types::isCXX(Input.getType()))
  3898. CmdArgs.push_back("-analyzer-checker=cplusplus");
  3899. if (!IsPS4CPU) {
  3900. CmdArgs.push_back(
  3901. "-analyzer-checker=security.insecureAPI.UncheckedReturn");
  3902. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  3903. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  3904. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  3905. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  3906. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  3907. }
  3908. // Default nullability checks.
  3909. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  3910. CmdArgs.push_back(
  3911. "-analyzer-checker=nullability.NullReturnedFromNonnull");
  3912. }
  3913. // Set the output format. The default is plist, for (lame) historical
  3914. // reasons.
  3915. CmdArgs.push_back("-analyzer-output");
  3916. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  3917. CmdArgs.push_back(A->getValue());
  3918. else
  3919. CmdArgs.push_back("plist");
  3920. // Disable the presentation of standard compiler warnings when
  3921. // using --analyze. We only want to show static analyzer diagnostics
  3922. // or frontend errors.
  3923. CmdArgs.push_back("-w");
  3924. // Add -Xanalyzer arguments when running as analyzer.
  3925. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  3926. }
  3927. CheckCodeGenerationOptions(D, Args);
  3928. llvm::Reloc::Model RelocationModel;
  3929. unsigned PICLevel;
  3930. bool IsPIE;
  3931. std::tie(RelocationModel, PICLevel, IsPIE) =
  3932. ParsePICArgs(getToolChain(), Args);
  3933. const char *RMName = RelocationModelName(RelocationModel);
  3934. if ((RelocationModel == llvm::Reloc::ROPI ||
  3935. RelocationModel == llvm::Reloc::ROPI_RWPI) &&
  3936. types::isCXX(Input.getType()) &&
  3937. !Args.hasArg(options::OPT_fallow_unsupported))
  3938. D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
  3939. if (RMName) {
  3940. CmdArgs.push_back("-mrelocation-model");
  3941. CmdArgs.push_back(RMName);
  3942. }
  3943. if (PICLevel > 0) {
  3944. CmdArgs.push_back("-pic-level");
  3945. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3946. if (IsPIE)
  3947. CmdArgs.push_back("-pic-is-pie");
  3948. }
  3949. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  3950. CmdArgs.push_back("-meabi");
  3951. CmdArgs.push_back(A->getValue());
  3952. }
  3953. CmdArgs.push_back("-mthread-model");
  3954. if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
  3955. CmdArgs.push_back(A->getValue());
  3956. else
  3957. CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
  3958. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3959. if (!Args.hasFlag(options::OPT_fmerge_all_constants,
  3960. options::OPT_fno_merge_all_constants))
  3961. CmdArgs.push_back("-fno-merge-all-constants");
  3962. // LLVM Code Generator Options.
  3963. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3964. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3965. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3966. options::OPT_frewrite_map_file_EQ)) {
  3967. StringRef Map = A->getValue();
  3968. if (!llvm::sys::fs::exists(Map)) {
  3969. D.Diag(diag::err_drv_no_such_file) << Map;
  3970. } else {
  3971. CmdArgs.push_back("-frewrite-map-file");
  3972. CmdArgs.push_back(A->getValue());
  3973. A->claim();
  3974. }
  3975. }
  3976. }
  3977. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3978. StringRef v = A->getValue();
  3979. CmdArgs.push_back("-mllvm");
  3980. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3981. A->claim();
  3982. }
  3983. if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
  3984. true))
  3985. CmdArgs.push_back("-fno-jump-tables");
  3986. if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
  3987. options::OPT_fno_preserve_as_comments, true))
  3988. CmdArgs.push_back("-fno-preserve-as-comments");
  3989. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3990. CmdArgs.push_back("-mregparm");
  3991. CmdArgs.push_back(A->getValue());
  3992. }
  3993. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3994. options::OPT_freg_struct_return)) {
  3995. if (getToolChain().getArch() != llvm::Triple::x86) {
  3996. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3997. << A->getSpelling() << getToolChain().getTriple().str();
  3998. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3999. CmdArgs.push_back("-fpcc-struct-return");
  4000. } else {
  4001. assert(A->getOption().matches(options::OPT_freg_struct_return));
  4002. CmdArgs.push_back("-freg-struct-return");
  4003. }
  4004. }
  4005. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  4006. CmdArgs.push_back("-fdefault-calling-conv=stdcall");
  4007. if (shouldUseFramePointer(Args, getToolChain().getTriple()))
  4008. CmdArgs.push_back("-mdisable-fp-elim");
  4009. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  4010. options::OPT_fno_zero_initialized_in_bss))
  4011. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  4012. bool OFastEnabled = isOptimizationLevelFast(Args);
  4013. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  4014. // enabled. This alias option is being used to simplify the hasFlag logic.
  4015. OptSpecifier StrictAliasingAliasOption =
  4016. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  4017. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  4018. // doesn't do any TBAA.
  4019. bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
  4020. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  4021. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  4022. CmdArgs.push_back("-relaxed-aliasing");
  4023. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  4024. options::OPT_fno_struct_path_tbaa))
  4025. CmdArgs.push_back("-no-struct-path-tbaa");
  4026. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  4027. false))
  4028. CmdArgs.push_back("-fstrict-enums");
  4029. if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
  4030. true))
  4031. CmdArgs.push_back("-fno-strict-return");
  4032. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  4033. options::OPT_fno_strict_vtable_pointers,
  4034. false))
  4035. CmdArgs.push_back("-fstrict-vtable-pointers");
  4036. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  4037. options::OPT_fno_optimize_sibling_calls))
  4038. CmdArgs.push_back("-mdisable-tail-calls");
  4039. // Handle segmented stacks.
  4040. if (Args.hasArg(options::OPT_fsplit_stack))
  4041. CmdArgs.push_back("-split-stacks");
  4042. // If -Ofast is the optimization level, then -ffast-math should be enabled.
  4043. // This alias option is being used to simplify the getLastArg logic.
  4044. OptSpecifier FastMathAliasOption =
  4045. OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
  4046. // Handle various floating point optimization flags, mapping them to the
  4047. // appropriate LLVM code generation flags. The pattern for all of these is to
  4048. // default off the codegen optimizations, and if any flag enables them and no
  4049. // flag disables them after the flag enabling them, enable the codegen
  4050. // optimization. This is complicated by several "umbrella" flags.
  4051. if (Arg *A = Args.getLastArg(
  4052. options::OPT_ffast_math, FastMathAliasOption,
  4053. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  4054. options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
  4055. options::OPT_fno_honor_infinities))
  4056. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  4057. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  4058. A->getOption().getID() != options::OPT_fhonor_infinities)
  4059. CmdArgs.push_back("-menable-no-infs");
  4060. if (Arg *A = Args.getLastArg(
  4061. options::OPT_ffast_math, FastMathAliasOption,
  4062. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  4063. options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
  4064. options::OPT_fno_honor_nans))
  4065. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  4066. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  4067. A->getOption().getID() != options::OPT_fhonor_nans)
  4068. CmdArgs.push_back("-menable-no-nans");
  4069. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  4070. bool MathErrno = getToolChain().IsMathErrnoDefault();
  4071. if (Arg *A =
  4072. Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  4073. options::OPT_fno_fast_math, options::OPT_fmath_errno,
  4074. options::OPT_fno_math_errno)) {
  4075. // Turning on -ffast_math (with either flag) removes the need for MathErrno.
  4076. // However, turning *off* -ffast_math merely restores the toolchain default
  4077. // (which may be false).
  4078. if (A->getOption().getID() == options::OPT_fno_math_errno ||
  4079. A->getOption().getID() == options::OPT_ffast_math ||
  4080. A->getOption().getID() == options::OPT_Ofast)
  4081. MathErrno = false;
  4082. else if (A->getOption().getID() == options::OPT_fmath_errno)
  4083. MathErrno = true;
  4084. }
  4085. if (MathErrno)
  4086. CmdArgs.push_back("-fmath-errno");
  4087. // There are several flags which require disabling very specific
  4088. // optimizations. Any of these being disabled forces us to turn off the
  4089. // entire set of LLVM optimizations, so collect them through all the flag
  4090. // madness.
  4091. bool AssociativeMath = false;
  4092. if (Arg *A = Args.getLastArg(
  4093. options::OPT_ffast_math, FastMathAliasOption,
  4094. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  4095. options::OPT_fno_unsafe_math_optimizations,
  4096. options::OPT_fassociative_math, options::OPT_fno_associative_math))
  4097. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  4098. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  4099. A->getOption().getID() != options::OPT_fno_associative_math)
  4100. AssociativeMath = true;
  4101. bool ReciprocalMath = false;
  4102. if (Arg *A = Args.getLastArg(
  4103. options::OPT_ffast_math, FastMathAliasOption,
  4104. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  4105. options::OPT_fno_unsafe_math_optimizations,
  4106. options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
  4107. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  4108. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  4109. A->getOption().getID() != options::OPT_fno_reciprocal_math)
  4110. ReciprocalMath = true;
  4111. bool SignedZeros = true;
  4112. if (Arg *A = Args.getLastArg(
  4113. options::OPT_ffast_math, FastMathAliasOption,
  4114. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  4115. options::OPT_fno_unsafe_math_optimizations,
  4116. options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
  4117. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  4118. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  4119. A->getOption().getID() != options::OPT_fsigned_zeros)
  4120. SignedZeros = false;
  4121. bool TrappingMath = true;
  4122. if (Arg *A = Args.getLastArg(
  4123. options::OPT_ffast_math, FastMathAliasOption,
  4124. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  4125. options::OPT_fno_unsafe_math_optimizations,
  4126. options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
  4127. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  4128. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  4129. A->getOption().getID() != options::OPT_ftrapping_math)
  4130. TrappingMath = false;
  4131. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  4132. !TrappingMath)
  4133. CmdArgs.push_back("-menable-unsafe-fp-math");
  4134. if (!SignedZeros)
  4135. CmdArgs.push_back("-fno-signed-zeros");
  4136. if (ReciprocalMath)
  4137. CmdArgs.push_back("-freciprocal-math");
  4138. if (!TrappingMath)
  4139. CmdArgs.push_back("-fno-trapping-math");
  4140. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  4141. options::OPT_fno_fast_math,
  4142. options::OPT_funsafe_math_optimizations,
  4143. options::OPT_fno_unsafe_math_optimizations,
  4144. options::OPT_fdenormal_fp_math_EQ))
  4145. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  4146. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations)
  4147. Args.AddLastArg(CmdArgs, options::OPT_fdenormal_fp_math_EQ);
  4148. // Validate and pass through -fp-contract option.
  4149. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  4150. options::OPT_fno_fast_math,
  4151. options::OPT_ffp_contract)) {
  4152. if (A->getOption().getID() == options::OPT_ffp_contract) {
  4153. StringRef Val = A->getValue();
  4154. if (Val == "fast" || Val == "on" || Val == "off") {
  4155. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
  4156. } else {
  4157. D.Diag(diag::err_drv_unsupported_option_argument)
  4158. << A->getOption().getName() << Val;
  4159. }
  4160. } else if (A->getOption().matches(options::OPT_ffast_math) ||
  4161. (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
  4162. // If fast-math is set then set the fp-contract mode to fast.
  4163. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  4164. }
  4165. }
  4166. ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
  4167. // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
  4168. // and if we find them, tell the frontend to provide the appropriate
  4169. // preprocessor macros. This is distinct from enabling any optimizations as
  4170. // these options induce language changes which must survive serialization
  4171. // and deserialization, etc.
  4172. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  4173. options::OPT_fno_fast_math))
  4174. if (!A->getOption().matches(options::OPT_fno_fast_math))
  4175. CmdArgs.push_back("-ffast-math");
  4176. if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
  4177. options::OPT_fno_fast_math))
  4178. if (A->getOption().matches(options::OPT_ffinite_math_only))
  4179. CmdArgs.push_back("-ffinite-math-only");
  4180. // Decide whether to use verbose asm. Verbose assembly is the default on
  4181. // toolchains which have the integrated assembler on by default.
  4182. bool IsIntegratedAssemblerDefault =
  4183. getToolChain().IsIntegratedAssemblerDefault();
  4184. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  4185. IsIntegratedAssemblerDefault) ||
  4186. Args.hasArg(options::OPT_dA))
  4187. CmdArgs.push_back("-masm-verbose");
  4188. if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
  4189. IsIntegratedAssemblerDefault))
  4190. CmdArgs.push_back("-no-integrated-as");
  4191. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  4192. CmdArgs.push_back("-mdebug-pass");
  4193. CmdArgs.push_back("Structure");
  4194. }
  4195. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  4196. CmdArgs.push_back("-mdebug-pass");
  4197. CmdArgs.push_back("Arguments");
  4198. }
  4199. // Enable -mconstructor-aliases except on darwin, where we have to work around
  4200. // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
  4201. // aliases aren't supported.
  4202. if (!getToolChain().getTriple().isOSDarwin() &&
  4203. !getToolChain().getTriple().isNVPTX())
  4204. CmdArgs.push_back("-mconstructor-aliases");
  4205. // Darwin's kernel doesn't support guard variables; just die if we
  4206. // try to use them.
  4207. if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
  4208. CmdArgs.push_back("-fforbid-guard-variables");
  4209. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  4210. false)) {
  4211. CmdArgs.push_back("-mms-bitfields");
  4212. }
  4213. if (Args.hasFlag(options::OPT_mpie_copy_relocations,
  4214. options::OPT_mno_pie_copy_relocations,
  4215. false)) {
  4216. CmdArgs.push_back("-mpie-copy-relocations");
  4217. }
  4218. // This is a coarse approximation of what llvm-gcc actually does, both
  4219. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  4220. // complicated ways.
  4221. bool AsynchronousUnwindTables =
  4222. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  4223. options::OPT_fno_asynchronous_unwind_tables,
  4224. (getToolChain().IsUnwindTablesDefault() ||
  4225. getToolChain().getSanitizerArgs().needsUnwindTables()) &&
  4226. !KernelOrKext);
  4227. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  4228. AsynchronousUnwindTables))
  4229. CmdArgs.push_back("-munwind-tables");
  4230. getToolChain().addClangTargetOptions(Args, CmdArgs);
  4231. if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  4232. CmdArgs.push_back("-mlimit-float-precision");
  4233. CmdArgs.push_back(A->getValue());
  4234. }
  4235. // FIXME: Handle -mtune=.
  4236. (void)Args.hasArg(options::OPT_mtune_EQ);
  4237. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  4238. CmdArgs.push_back("-mcode-model");
  4239. CmdArgs.push_back(A->getValue());
  4240. }
  4241. // Add the target cpu
  4242. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  4243. if (!CPU.empty()) {
  4244. CmdArgs.push_back("-target-cpu");
  4245. CmdArgs.push_back(Args.MakeArgString(CPU));
  4246. }
  4247. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  4248. CmdArgs.push_back("-mfpmath");
  4249. CmdArgs.push_back(A->getValue());
  4250. }
  4251. // Add the target features
  4252. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
  4253. // Add target specific flags.
  4254. switch (getToolChain().getArch()) {
  4255. default:
  4256. break;
  4257. case llvm::Triple::arm:
  4258. case llvm::Triple::armeb:
  4259. case llvm::Triple::thumb:
  4260. case llvm::Triple::thumbeb:
  4261. // Use the effective triple, which takes into account the deployment target.
  4262. AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
  4263. break;
  4264. case llvm::Triple::aarch64:
  4265. case llvm::Triple::aarch64_be:
  4266. AddAArch64TargetArgs(Args, CmdArgs);
  4267. break;
  4268. case llvm::Triple::mips:
  4269. case llvm::Triple::mipsel:
  4270. case llvm::Triple::mips64:
  4271. case llvm::Triple::mips64el:
  4272. AddMIPSTargetArgs(Args, CmdArgs);
  4273. break;
  4274. case llvm::Triple::ppc:
  4275. case llvm::Triple::ppc64:
  4276. case llvm::Triple::ppc64le:
  4277. AddPPCTargetArgs(Args, CmdArgs);
  4278. break;
  4279. case llvm::Triple::sparc:
  4280. case llvm::Triple::sparcel:
  4281. case llvm::Triple::sparcv9:
  4282. AddSparcTargetArgs(Args, CmdArgs);
  4283. break;
  4284. case llvm::Triple::systemz:
  4285. AddSystemZTargetArgs(Args, CmdArgs);
  4286. break;
  4287. case llvm::Triple::x86:
  4288. case llvm::Triple::x86_64:
  4289. AddX86TargetArgs(Args, CmdArgs);
  4290. break;
  4291. case llvm::Triple::lanai:
  4292. AddLanaiTargetArgs(Args, CmdArgs);
  4293. break;
  4294. case llvm::Triple::hexagon:
  4295. AddHexagonTargetArgs(Args, CmdArgs);
  4296. break;
  4297. case llvm::Triple::wasm32:
  4298. case llvm::Triple::wasm64:
  4299. AddWebAssemblyTargetArgs(Args, CmdArgs);
  4300. break;
  4301. }
  4302. // The 'g' groups options involve a somewhat intricate sequence of decisions
  4303. // about what to pass from the driver to the frontend, but by the time they
  4304. // reach cc1 they've been factored into three well-defined orthogonal choices:
  4305. // * what level of debug info to generate
  4306. // * what dwarf version to write
  4307. // * what debugger tuning to use
  4308. // This avoids having to monkey around further in cc1 other than to disable
  4309. // codeview if not running in a Windows environment. Perhaps even that
  4310. // decision should be made in the driver as well though.
  4311. unsigned DwarfVersion = 0;
  4312. llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
  4313. // These two are potentially updated by AddClangCLArgs.
  4314. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  4315. bool EmitCodeView = false;
  4316. // Add clang-cl arguments.
  4317. types::ID InputType = Input.getType();
  4318. if (getToolChain().getDriver().IsCLMode())
  4319. AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
  4320. // Pass the linker version in use.
  4321. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  4322. CmdArgs.push_back("-target-linker-version");
  4323. CmdArgs.push_back(A->getValue());
  4324. }
  4325. if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
  4326. CmdArgs.push_back("-momit-leaf-frame-pointer");
  4327. // Explicitly error on some things we know we don't support and can't just
  4328. // ignore.
  4329. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  4330. Arg *Unsupported;
  4331. if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
  4332. getToolChain().getArch() == llvm::Triple::x86) {
  4333. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  4334. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  4335. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  4336. << Unsupported->getOption().getName();
  4337. }
  4338. }
  4339. Args.AddAllArgs(CmdArgs, options::OPT_v);
  4340. Args.AddLastArg(CmdArgs, options::OPT_H);
  4341. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  4342. CmdArgs.push_back("-header-include-file");
  4343. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  4344. : "-");
  4345. }
  4346. Args.AddLastArg(CmdArgs, options::OPT_P);
  4347. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  4348. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  4349. CmdArgs.push_back("-diagnostic-log-file");
  4350. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  4351. : "-");
  4352. }
  4353. bool splitDwarfInlining =
  4354. Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
  4355. options::OPT_fno_split_dwarf_inlining, true);
  4356. Args.ClaimAllArgs(options::OPT_g_Group);
  4357. Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
  4358. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  4359. // If the last option explicitly specified a debug-info level, use it.
  4360. if (A->getOption().matches(options::OPT_gN_Group)) {
  4361. DebugInfoKind = DebugLevelToInfoKind(*A);
  4362. // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
  4363. // But -gsplit-dwarf is not a g_group option, hence we have to check the
  4364. // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
  4365. // This gets a bit more complicated if you've disabled inline info in the
  4366. // skeleton CUs (splitDwarfInlining) - then there's value in composing
  4367. // split-dwarf and line-tables-only, so let those compose naturally in
  4368. // that case.
  4369. // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
  4370. if (SplitDwarfArg) {
  4371. if (A->getIndex() > SplitDwarfArg->getIndex()) {
  4372. if (DebugInfoKind == codegenoptions::NoDebugInfo ||
  4373. (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
  4374. splitDwarfInlining))
  4375. SplitDwarfArg = nullptr;
  4376. } else if (splitDwarfInlining)
  4377. DebugInfoKind = codegenoptions::NoDebugInfo;
  4378. }
  4379. } else
  4380. // For any other 'g' option, use Limited.
  4381. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  4382. }
  4383. // If a debugger tuning argument appeared, remember it.
  4384. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  4385. options::OPT_ggdbN_Group)) {
  4386. if (A->getOption().matches(options::OPT_glldb))
  4387. DebuggerTuning = llvm::DebuggerKind::LLDB;
  4388. else if (A->getOption().matches(options::OPT_gsce))
  4389. DebuggerTuning = llvm::DebuggerKind::SCE;
  4390. else
  4391. DebuggerTuning = llvm::DebuggerKind::GDB;
  4392. }
  4393. // If a -gdwarf argument appeared, remember it.
  4394. if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  4395. options::OPT_gdwarf_4, options::OPT_gdwarf_5))
  4396. DwarfVersion = DwarfVersionNum(A->getSpelling());
  4397. // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
  4398. // argument parsing.
  4399. if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
  4400. // DwarfVersion remains at 0 if no explicit choice was made.
  4401. CmdArgs.push_back("-gcodeview");
  4402. } else if (DwarfVersion == 0 &&
  4403. DebugInfoKind != codegenoptions::NoDebugInfo) {
  4404. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  4405. }
  4406. // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
  4407. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  4408. // Column info is included by default for everything except PS4 and CodeView.
  4409. // Clang doesn't track end columns, just starting columns, which, in theory,
  4410. // is fine for CodeView (and PDB). In practice, however, the Microsoft
  4411. // debuggers don't handle missing end columns well, so it's better not to
  4412. // include any column info.
  4413. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  4414. /*Default=*/ !IsPS4CPU && !(IsWindowsMSVC && EmitCodeView)))
  4415. CmdArgs.push_back("-dwarf-column-info");
  4416. // FIXME: Move backend command line options to the module.
  4417. // If -gline-tables-only is the last option it wins.
  4418. if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
  4419. Args.hasArg(options::OPT_gmodules)) {
  4420. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  4421. CmdArgs.push_back("-dwarf-ext-refs");
  4422. CmdArgs.push_back("-fmodule-format=obj");
  4423. }
  4424. // -gsplit-dwarf should turn on -g and enable the backend dwarf
  4425. // splitting and extraction.
  4426. // FIXME: Currently only works on Linux.
  4427. if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
  4428. if (!splitDwarfInlining)
  4429. CmdArgs.push_back("-fno-split-dwarf-inlining");
  4430. if (DebugInfoKind == codegenoptions::NoDebugInfo)
  4431. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  4432. CmdArgs.push_back("-backend-option");
  4433. CmdArgs.push_back("-split-dwarf=Enable");
  4434. }
  4435. // After we've dealt with all combinations of things that could
  4436. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  4437. // figure out if we need to "upgrade" it to standalone debug info.
  4438. // We parse these two '-f' options whether or not they will be used,
  4439. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  4440. bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
  4441. options::OPT_fno_standalone_debug,
  4442. getToolChain().GetDefaultStandaloneDebug());
  4443. if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
  4444. DebugInfoKind = codegenoptions::FullDebugInfo;
  4445. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  4446. DebuggerTuning);
  4447. // -fdebug-macro turns on macro debug info generation.
  4448. if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
  4449. false))
  4450. CmdArgs.push_back("-debug-info-macro");
  4451. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  4452. if (Args.hasArg(options::OPT_ggnu_pubnames)) {
  4453. CmdArgs.push_back("-backend-option");
  4454. CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
  4455. }
  4456. // -gdwarf-aranges turns on the emission of the aranges section in the
  4457. // backend.
  4458. // Always enabled on the PS4.
  4459. if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
  4460. CmdArgs.push_back("-backend-option");
  4461. CmdArgs.push_back("-generate-arange-section");
  4462. }
  4463. if (Args.hasFlag(options::OPT_fdebug_types_section,
  4464. options::OPT_fno_debug_types_section, false)) {
  4465. CmdArgs.push_back("-backend-option");
  4466. CmdArgs.push_back("-generate-type-units");
  4467. }
  4468. bool UseSeparateSections = isUseSeparateSections(Triple);
  4469. if (Args.hasFlag(options::OPT_ffunction_sections,
  4470. options::OPT_fno_function_sections, UseSeparateSections)) {
  4471. CmdArgs.push_back("-ffunction-sections");
  4472. }
  4473. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  4474. UseSeparateSections)) {
  4475. CmdArgs.push_back("-fdata-sections");
  4476. }
  4477. if (!Args.hasFlag(options::OPT_funique_section_names,
  4478. options::OPT_fno_unique_section_names, true))
  4479. CmdArgs.push_back("-fno-unique-section-names");
  4480. Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
  4481. if (Args.hasFlag(options::OPT_fxray_instrument,
  4482. options::OPT_fnoxray_instrument, false)) {
  4483. const char *const XRayInstrumentOption = "-fxray-instrument";
  4484. if (Triple.getOS() == llvm::Triple::Linux)
  4485. switch (Triple.getArch()) {
  4486. case llvm::Triple::x86_64:
  4487. case llvm::Triple::arm:
  4488. case llvm::Triple::aarch64:
  4489. // Supported.
  4490. break;
  4491. default:
  4492. D.Diag(diag::err_drv_clang_unsupported)
  4493. << (std::string(XRayInstrumentOption) + " on " + Triple.str());
  4494. }
  4495. else
  4496. D.Diag(diag::err_drv_clang_unsupported)
  4497. << (std::string(XRayInstrumentOption) + " on non-Linux target OS");
  4498. CmdArgs.push_back(XRayInstrumentOption);
  4499. if (const Arg *A =
  4500. Args.getLastArg(options::OPT_fxray_instruction_threshold_,
  4501. options::OPT_fxray_instruction_threshold_EQ)) {
  4502. CmdArgs.push_back("-fxray-instruction-threshold");
  4503. CmdArgs.push_back(A->getValue());
  4504. }
  4505. }
  4506. addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
  4507. // Add runtime flag for PS4 when PGO or Coverage are enabled.
  4508. if (getToolChain().getTriple().isPS4CPU())
  4509. addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
  4510. // Pass options for controlling the default header search paths.
  4511. if (Args.hasArg(options::OPT_nostdinc)) {
  4512. CmdArgs.push_back("-nostdsysteminc");
  4513. CmdArgs.push_back("-nobuiltininc");
  4514. } else {
  4515. if (Args.hasArg(options::OPT_nostdlibinc))
  4516. CmdArgs.push_back("-nostdsysteminc");
  4517. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  4518. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  4519. }
  4520. // Pass the path to compiler resource files.
  4521. CmdArgs.push_back("-resource-dir");
  4522. CmdArgs.push_back(D.ResourceDir.c_str());
  4523. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  4524. bool ARCMTEnabled = false;
  4525. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  4526. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  4527. options::OPT_ccc_arcmt_modify,
  4528. options::OPT_ccc_arcmt_migrate)) {
  4529. ARCMTEnabled = true;
  4530. switch (A->getOption().getID()) {
  4531. default:
  4532. llvm_unreachable("missed a case");
  4533. case options::OPT_ccc_arcmt_check:
  4534. CmdArgs.push_back("-arcmt-check");
  4535. break;
  4536. case options::OPT_ccc_arcmt_modify:
  4537. CmdArgs.push_back("-arcmt-modify");
  4538. break;
  4539. case options::OPT_ccc_arcmt_migrate:
  4540. CmdArgs.push_back("-arcmt-migrate");
  4541. CmdArgs.push_back("-mt-migrate-directory");
  4542. CmdArgs.push_back(A->getValue());
  4543. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  4544. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  4545. break;
  4546. }
  4547. }
  4548. } else {
  4549. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  4550. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  4551. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  4552. }
  4553. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  4554. if (ARCMTEnabled) {
  4555. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4556. << "-ccc-arcmt-migrate";
  4557. }
  4558. CmdArgs.push_back("-mt-migrate-directory");
  4559. CmdArgs.push_back(A->getValue());
  4560. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  4561. options::OPT_objcmt_migrate_subscripting,
  4562. options::OPT_objcmt_migrate_property)) {
  4563. // None specified, means enable them all.
  4564. CmdArgs.push_back("-objcmt-migrate-literals");
  4565. CmdArgs.push_back("-objcmt-migrate-subscripting");
  4566. CmdArgs.push_back("-objcmt-migrate-property");
  4567. } else {
  4568. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4569. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4570. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4571. }
  4572. } else {
  4573. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4574. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4575. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4576. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  4577. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  4578. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  4579. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  4580. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  4581. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  4582. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  4583. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  4584. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  4585. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  4586. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  4587. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  4588. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  4589. }
  4590. // Add preprocessing options like -I, -D, etc. if we are using the
  4591. // preprocessor.
  4592. //
  4593. // FIXME: Support -fpreprocessed
  4594. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  4595. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
  4596. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  4597. // that "The compiler can only warn and ignore the option if not recognized".
  4598. // When building with ccache, it will pass -D options to clang even on
  4599. // preprocessed inputs and configure concludes that -fPIC is not supported.
  4600. Args.ClaimAllArgs(options::OPT_D);
  4601. // Manually translate -O4 to -O3; let clang reject others.
  4602. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  4603. if (A->getOption().matches(options::OPT_O4)) {
  4604. CmdArgs.push_back("-O3");
  4605. D.Diag(diag::warn_O4_is_O3);
  4606. } else {
  4607. A->render(Args, CmdArgs);
  4608. }
  4609. }
  4610. // Warn about ignored options to clang.
  4611. for (const Arg *A :
  4612. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  4613. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  4614. A->claim();
  4615. }
  4616. claimNoWarnArgs(Args);
  4617. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  4618. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  4619. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  4620. CmdArgs.push_back("-pedantic");
  4621. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  4622. Args.AddLastArg(CmdArgs, options::OPT_w);
  4623. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  4624. // (-ansi is equivalent to -std=c89 or -std=c++98).
  4625. //
  4626. // If a std is supplied, only add -trigraphs if it follows the
  4627. // option.
  4628. bool ImplyVCPPCXXVer = false;
  4629. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
  4630. if (Std->getOption().matches(options::OPT_ansi))
  4631. if (types::isCXX(InputType))
  4632. CmdArgs.push_back("-std=c++98");
  4633. else
  4634. CmdArgs.push_back("-std=c89");
  4635. else
  4636. Std->render(Args, CmdArgs);
  4637. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  4638. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  4639. options::OPT_ftrigraphs,
  4640. options::OPT_fno_trigraphs))
  4641. if (A != Std)
  4642. A->render(Args, CmdArgs);
  4643. } else {
  4644. // Honor -std-default.
  4645. //
  4646. // FIXME: Clang doesn't correctly handle -std= when the input language
  4647. // doesn't match. For the time being just ignore this for C++ inputs;
  4648. // eventually we want to do all the standard defaulting here instead of
  4649. // splitting it between the driver and clang -cc1.
  4650. if (!types::isCXX(InputType))
  4651. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  4652. /*Joined=*/true);
  4653. else if (IsWindowsMSVC)
  4654. ImplyVCPPCXXVer = true;
  4655. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  4656. options::OPT_fno_trigraphs);
  4657. }
  4658. // GCC's behavior for -Wwrite-strings is a bit strange:
  4659. // * In C, this "warning flag" changes the types of string literals from
  4660. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  4661. // for the discarded qualifier.
  4662. // * In C++, this is just a normal warning flag.
  4663. //
  4664. // Implementing this warning correctly in C is hard, so we follow GCC's
  4665. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  4666. // a non-const char* in C, rather than using this crude hack.
  4667. if (!types::isCXX(InputType)) {
  4668. // FIXME: This should behave just like a warning flag, and thus should also
  4669. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  4670. Arg *WriteStrings =
  4671. Args.getLastArg(options::OPT_Wwrite_strings,
  4672. options::OPT_Wno_write_strings, options::OPT_w);
  4673. if (WriteStrings &&
  4674. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  4675. CmdArgs.push_back("-fconst-strings");
  4676. }
  4677. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  4678. // during C++ compilation, which it is by default. GCC keeps this define even
  4679. // in the presence of '-w', match this behavior bug-for-bug.
  4680. if (types::isCXX(InputType) &&
  4681. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  4682. true)) {
  4683. CmdArgs.push_back("-fdeprecated-macro");
  4684. }
  4685. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  4686. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  4687. if (Asm->getOption().matches(options::OPT_fasm))
  4688. CmdArgs.push_back("-fgnu-keywords");
  4689. else
  4690. CmdArgs.push_back("-fno-gnu-keywords");
  4691. }
  4692. if (ShouldDisableDwarfDirectory(Args, getToolChain()))
  4693. CmdArgs.push_back("-fno-dwarf-directory-asm");
  4694. if (ShouldDisableAutolink(Args, getToolChain()))
  4695. CmdArgs.push_back("-fno-autolink");
  4696. // Add in -fdebug-compilation-dir if necessary.
  4697. addDebugCompDirArg(Args, CmdArgs);
  4698. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  4699. StringRef Map = A->getValue();
  4700. if (Map.find('=') == StringRef::npos)
  4701. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  4702. else
  4703. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  4704. A->claim();
  4705. }
  4706. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  4707. options::OPT_ftemplate_depth_EQ)) {
  4708. CmdArgs.push_back("-ftemplate-depth");
  4709. CmdArgs.push_back(A->getValue());
  4710. }
  4711. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  4712. CmdArgs.push_back("-foperator-arrow-depth");
  4713. CmdArgs.push_back(A->getValue());
  4714. }
  4715. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  4716. CmdArgs.push_back("-fconstexpr-depth");
  4717. CmdArgs.push_back(A->getValue());
  4718. }
  4719. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  4720. CmdArgs.push_back("-fconstexpr-steps");
  4721. CmdArgs.push_back(A->getValue());
  4722. }
  4723. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  4724. CmdArgs.push_back("-fbracket-depth");
  4725. CmdArgs.push_back(A->getValue());
  4726. }
  4727. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  4728. options::OPT_Wlarge_by_value_copy_def)) {
  4729. if (A->getNumValues()) {
  4730. StringRef bytes = A->getValue();
  4731. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  4732. } else
  4733. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  4734. }
  4735. if (Args.hasArg(options::OPT_relocatable_pch))
  4736. CmdArgs.push_back("-relocatable-pch");
  4737. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  4738. CmdArgs.push_back("-fconstant-string-class");
  4739. CmdArgs.push_back(A->getValue());
  4740. }
  4741. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  4742. CmdArgs.push_back("-ftabstop");
  4743. CmdArgs.push_back(A->getValue());
  4744. }
  4745. CmdArgs.push_back("-ferror-limit");
  4746. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  4747. CmdArgs.push_back(A->getValue());
  4748. else
  4749. CmdArgs.push_back("19");
  4750. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  4751. CmdArgs.push_back("-fmacro-backtrace-limit");
  4752. CmdArgs.push_back(A->getValue());
  4753. }
  4754. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  4755. CmdArgs.push_back("-ftemplate-backtrace-limit");
  4756. CmdArgs.push_back(A->getValue());
  4757. }
  4758. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  4759. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  4760. CmdArgs.push_back(A->getValue());
  4761. }
  4762. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  4763. CmdArgs.push_back("-fspell-checking-limit");
  4764. CmdArgs.push_back(A->getValue());
  4765. }
  4766. // Pass -fmessage-length=.
  4767. CmdArgs.push_back("-fmessage-length");
  4768. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  4769. CmdArgs.push_back(A->getValue());
  4770. } else {
  4771. // If -fmessage-length=N was not specified, determine whether this is a
  4772. // terminal and, if so, implicitly define -fmessage-length appropriately.
  4773. unsigned N = llvm::sys::Process::StandardErrColumns();
  4774. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  4775. }
  4776. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  4777. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  4778. options::OPT_fvisibility_ms_compat)) {
  4779. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  4780. CmdArgs.push_back("-fvisibility");
  4781. CmdArgs.push_back(A->getValue());
  4782. } else {
  4783. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  4784. CmdArgs.push_back("-fvisibility");
  4785. CmdArgs.push_back("hidden");
  4786. CmdArgs.push_back("-ftype-visibility");
  4787. CmdArgs.push_back("default");
  4788. }
  4789. }
  4790. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  4791. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  4792. // -fhosted is default.
  4793. bool IsHosted = true;
  4794. if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  4795. KernelOrKext) {
  4796. CmdArgs.push_back("-ffreestanding");
  4797. IsHosted = false;
  4798. }
  4799. // Forward -f (flag) options which we can pass directly.
  4800. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  4801. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  4802. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  4803. // Emulated TLS is enabled by default on Android, and can be enabled manually
  4804. // with -femulated-tls.
  4805. bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
  4806. if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
  4807. EmulatedTLSDefault))
  4808. CmdArgs.push_back("-femulated-tls");
  4809. // AltiVec-like language extensions aren't relevant for assembling.
  4810. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
  4811. Args.AddLastArg(CmdArgs, options::OPT_faltivec);
  4812. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  4813. }
  4814. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  4815. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  4816. // Forward flags for OpenMP. We don't do this if the current action is an
  4817. // device offloading action other than OpenMP.
  4818. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  4819. options::OPT_fno_openmp, false) &&
  4820. (JA.isDeviceOffloading(Action::OFK_None) ||
  4821. JA.isDeviceOffloading(Action::OFK_OpenMP))) {
  4822. switch (getToolChain().getDriver().getOpenMPRuntime(Args)) {
  4823. case Driver::OMPRT_OMP:
  4824. case Driver::OMPRT_IOMP5:
  4825. // Clang can generate useful OpenMP code for these two runtime libraries.
  4826. CmdArgs.push_back("-fopenmp");
  4827. // If no option regarding the use of TLS in OpenMP codegeneration is
  4828. // given, decide a default based on the target. Otherwise rely on the
  4829. // options and pass the right information to the frontend.
  4830. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  4831. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  4832. CmdArgs.push_back("-fnoopenmp-use-tls");
  4833. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
  4834. break;
  4835. default:
  4836. // By default, if Clang doesn't know how to generate useful OpenMP code
  4837. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  4838. // down to the actual compilation.
  4839. // FIXME: It would be better to have a mode which *only* omits IR
  4840. // generation based on the OpenMP support so that we get consistent
  4841. // semantic analysis, etc.
  4842. break;
  4843. }
  4844. }
  4845. const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
  4846. Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
  4847. // Report an error for -faltivec on anything other than PowerPC.
  4848. if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
  4849. const llvm::Triple::ArchType Arch = getToolChain().getArch();
  4850. if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  4851. Arch == llvm::Triple::ppc64le))
  4852. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  4853. << "ppc/ppc64/ppc64le";
  4854. }
  4855. // -fzvector is incompatible with -faltivec.
  4856. if (Arg *A = Args.getLastArg(options::OPT_fzvector))
  4857. if (Args.hasArg(options::OPT_faltivec))
  4858. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4859. << "-faltivec";
  4860. if (getToolChain().SupportsProfiling())
  4861. Args.AddLastArg(CmdArgs, options::OPT_pg);
  4862. if (getToolChain().SupportsProfiling())
  4863. Args.AddLastArg(CmdArgs, options::OPT_mfentry);
  4864. // -flax-vector-conversions is default.
  4865. if (!Args.hasFlag(options::OPT_flax_vector_conversions,
  4866. options::OPT_fno_lax_vector_conversions))
  4867. CmdArgs.push_back("-fno-lax-vector-conversions");
  4868. if (Args.getLastArg(options::OPT_fapple_kext) ||
  4869. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  4870. CmdArgs.push_back("-fapple-kext");
  4871. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  4872. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  4873. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  4874. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  4875. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  4876. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  4877. CmdArgs.push_back("-ftrapv-handler");
  4878. CmdArgs.push_back(A->getValue());
  4879. }
  4880. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  4881. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  4882. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  4883. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  4884. if (A->getOption().matches(options::OPT_fwrapv))
  4885. CmdArgs.push_back("-fwrapv");
  4886. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  4887. options::OPT_fno_strict_overflow)) {
  4888. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  4889. CmdArgs.push_back("-fwrapv");
  4890. }
  4891. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  4892. options::OPT_fno_reroll_loops))
  4893. if (A->getOption().matches(options::OPT_freroll_loops))
  4894. CmdArgs.push_back("-freroll-loops");
  4895. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  4896. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  4897. options::OPT_fno_unroll_loops);
  4898. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  4899. // -stack-protector=0 is default.
  4900. unsigned StackProtectorLevel = 0;
  4901. if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  4902. options::OPT_fstack_protector_all,
  4903. options::OPT_fstack_protector_strong,
  4904. options::OPT_fstack_protector)) {
  4905. if (A->getOption().matches(options::OPT_fstack_protector)) {
  4906. StackProtectorLevel = std::max<unsigned>(
  4907. LangOptions::SSPOn,
  4908. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
  4909. } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  4910. StackProtectorLevel = LangOptions::SSPStrong;
  4911. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  4912. StackProtectorLevel = LangOptions::SSPReq;
  4913. } else {
  4914. StackProtectorLevel =
  4915. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
  4916. // Only use a default stack protector on Darwin in case -ffreestanding
  4917. // is not specified.
  4918. if (Triple.isOSDarwin() && !IsHosted)
  4919. StackProtectorLevel = 0;
  4920. }
  4921. if (StackProtectorLevel) {
  4922. CmdArgs.push_back("-stack-protector");
  4923. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  4924. }
  4925. // --param ssp-buffer-size=
  4926. for (const Arg *A : Args.filtered(options::OPT__param)) {
  4927. StringRef Str(A->getValue());
  4928. if (Str.startswith("ssp-buffer-size=")) {
  4929. if (StackProtectorLevel) {
  4930. CmdArgs.push_back("-stack-protector-buffer-size");
  4931. // FIXME: Verify the argument is a valid integer.
  4932. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  4933. }
  4934. A->claim();
  4935. }
  4936. }
  4937. // Translate -mstackrealign
  4938. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  4939. false))
  4940. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  4941. if (Args.hasArg(options::OPT_mstack_alignment)) {
  4942. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  4943. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  4944. }
  4945. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  4946. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  4947. if (!Size.empty())
  4948. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  4949. else
  4950. CmdArgs.push_back("-mstack-probe-size=0");
  4951. }
  4952. switch (getToolChain().getArch()) {
  4953. case llvm::Triple::aarch64:
  4954. case llvm::Triple::aarch64_be:
  4955. case llvm::Triple::arm:
  4956. case llvm::Triple::armeb:
  4957. case llvm::Triple::thumb:
  4958. case llvm::Triple::thumbeb:
  4959. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  4960. break;
  4961. default:
  4962. break;
  4963. }
  4964. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  4965. options::OPT_mno_restrict_it)) {
  4966. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  4967. CmdArgs.push_back("-backend-option");
  4968. CmdArgs.push_back("-arm-restrict-it");
  4969. } else {
  4970. CmdArgs.push_back("-backend-option");
  4971. CmdArgs.push_back("-arm-no-restrict-it");
  4972. }
  4973. } else if (Triple.isOSWindows() &&
  4974. (Triple.getArch() == llvm::Triple::arm ||
  4975. Triple.getArch() == llvm::Triple::thumb)) {
  4976. // Windows on ARM expects restricted IT blocks
  4977. CmdArgs.push_back("-backend-option");
  4978. CmdArgs.push_back("-arm-restrict-it");
  4979. }
  4980. // Forward -cl options to -cc1
  4981. if (Args.getLastArg(options::OPT_cl_opt_disable)) {
  4982. CmdArgs.push_back("-cl-opt-disable");
  4983. }
  4984. if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
  4985. CmdArgs.push_back("-cl-strict-aliasing");
  4986. }
  4987. if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
  4988. CmdArgs.push_back("-cl-single-precision-constant");
  4989. }
  4990. if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
  4991. CmdArgs.push_back("-cl-finite-math-only");
  4992. }
  4993. if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
  4994. CmdArgs.push_back("-cl-kernel-arg-info");
  4995. }
  4996. if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
  4997. CmdArgs.push_back("-cl-unsafe-math-optimizations");
  4998. }
  4999. if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
  5000. CmdArgs.push_back("-cl-fast-relaxed-math");
  5001. }
  5002. if (Args.getLastArg(options::OPT_cl_mad_enable)) {
  5003. CmdArgs.push_back("-cl-mad-enable");
  5004. }
  5005. if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
  5006. CmdArgs.push_back("-cl-no-signed-zeros");
  5007. }
  5008. if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
  5009. std::string CLStdStr = "-cl-std=";
  5010. CLStdStr += A->getValue();
  5011. CmdArgs.push_back(Args.MakeArgString(CLStdStr));
  5012. }
  5013. if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
  5014. CmdArgs.push_back("-cl-denorms-are-zero");
  5015. }
  5016. if (Args.getLastArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt)) {
  5017. CmdArgs.push_back("-cl-fp32-correctly-rounded-divide-sqrt");
  5018. }
  5019. // Forward -f options with positive and negative forms; we translate
  5020. // these by hand.
  5021. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  5022. StringRef fname = A->getValue();
  5023. if (!llvm::sys::fs::exists(fname))
  5024. D.Diag(diag::err_drv_no_such_file) << fname;
  5025. else
  5026. A->render(Args, CmdArgs);
  5027. }
  5028. if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
  5029. options::OPT_fno_debug_info_for_profiling, false))
  5030. CmdArgs.push_back("-fdebug-info-for-profiling");
  5031. // -fbuiltin is default unless -mkernel is used.
  5032. bool UseBuiltins =
  5033. Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  5034. !Args.hasArg(options::OPT_mkernel));
  5035. if (!UseBuiltins)
  5036. CmdArgs.push_back("-fno-builtin");
  5037. // -ffreestanding implies -fno-builtin.
  5038. if (Args.hasArg(options::OPT_ffreestanding))
  5039. UseBuiltins = false;
  5040. // Process the -fno-builtin-* options.
  5041. for (const auto &Arg : Args) {
  5042. const Option &O = Arg->getOption();
  5043. if (!O.matches(options::OPT_fno_builtin_))
  5044. continue;
  5045. Arg->claim();
  5046. // If -fno-builtin is specified, then there's no need to pass the option to
  5047. // the frontend.
  5048. if (!UseBuiltins)
  5049. continue;
  5050. StringRef FuncName = Arg->getValue();
  5051. CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
  5052. }
  5053. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  5054. options::OPT_fno_assume_sane_operator_new))
  5055. CmdArgs.push_back("-fno-assume-sane-operator-new");
  5056. // -fblocks=0 is default.
  5057. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  5058. getToolChain().IsBlocksDefault()) ||
  5059. (Args.hasArg(options::OPT_fgnu_runtime) &&
  5060. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  5061. !Args.hasArg(options::OPT_fno_blocks))) {
  5062. CmdArgs.push_back("-fblocks");
  5063. if (!Args.hasArg(options::OPT_fgnu_runtime) &&
  5064. !getToolChain().hasBlocksRuntime())
  5065. CmdArgs.push_back("-fblocks-runtime-optional");
  5066. }
  5067. if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
  5068. false) &&
  5069. types::isCXX(InputType)) {
  5070. CmdArgs.push_back("-fcoroutines-ts");
  5071. }
  5072. // -fmodules enables the use of precompiled modules (off by default).
  5073. // Users can pass -fno-cxx-modules to turn off modules support for
  5074. // C++/Objective-C++ programs.
  5075. bool HaveClangModules = false;
  5076. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  5077. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  5078. options::OPT_fno_cxx_modules, true);
  5079. if (AllowedInCXX || !types::isCXX(InputType)) {
  5080. CmdArgs.push_back("-fmodules");
  5081. HaveClangModules = true;
  5082. }
  5083. }
  5084. bool HaveAnyModules = HaveClangModules;
  5085. if (Args.hasArg(options::OPT_fmodules_ts)) {
  5086. CmdArgs.push_back("-fmodules-ts");
  5087. HaveAnyModules = true;
  5088. }
  5089. // -fmodule-maps enables implicit reading of module map files. By default,
  5090. // this is enabled if we are using Clang's flavor of precompiled modules.
  5091. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  5092. options::OPT_fno_implicit_module_maps, HaveClangModules)) {
  5093. CmdArgs.push_back("-fimplicit-module-maps");
  5094. }
  5095. // -fmodules-decluse checks that modules used are declared so (off by
  5096. // default).
  5097. if (Args.hasFlag(options::OPT_fmodules_decluse,
  5098. options::OPT_fno_modules_decluse, false)) {
  5099. CmdArgs.push_back("-fmodules-decluse");
  5100. }
  5101. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  5102. // all #included headers are part of modules.
  5103. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  5104. options::OPT_fno_modules_strict_decluse, false)) {
  5105. CmdArgs.push_back("-fmodules-strict-decluse");
  5106. }
  5107. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  5108. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  5109. options::OPT_fno_implicit_modules, HaveClangModules)) {
  5110. if (HaveAnyModules)
  5111. CmdArgs.push_back("-fno-implicit-modules");
  5112. } else if (HaveAnyModules) {
  5113. // -fmodule-cache-path specifies where our implicitly-built module files
  5114. // should be written.
  5115. SmallString<128> Path;
  5116. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  5117. Path = A->getValue();
  5118. if (C.isForDiagnostics()) {
  5119. // When generating crash reports, we want to emit the modules along with
  5120. // the reproduction sources, so we ignore any provided module path.
  5121. Path = Output.getFilename();
  5122. llvm::sys::path::replace_extension(Path, ".cache");
  5123. llvm::sys::path::append(Path, "modules");
  5124. } else if (Path.empty()) {
  5125. // No module path was provided: use the default.
  5126. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
  5127. llvm::sys::path::append(Path, "org.llvm.clang.");
  5128. appendUserToPath(Path);
  5129. llvm::sys::path::append(Path, "ModuleCache");
  5130. }
  5131. const char Arg[] = "-fmodules-cache-path=";
  5132. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  5133. CmdArgs.push_back(Args.MakeArgString(Path));
  5134. }
  5135. if (HaveAnyModules) {
  5136. // -fprebuilt-module-path specifies where to load the prebuilt module files.
  5137. for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path))
  5138. CmdArgs.push_back(Args.MakeArgString(
  5139. std::string("-fprebuilt-module-path=") + A->getValue()));
  5140. }
  5141. // -fmodule-name specifies the module that is currently being built (or
  5142. // used for header checking by -fmodule-maps).
  5143. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
  5144. // -fmodule-map-file can be used to specify files containing module
  5145. // definitions.
  5146. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  5147. // -fbuiltin-module-map can be used to load the clang
  5148. // builtin headers modulemap file.
  5149. if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
  5150. SmallString<128> BuiltinModuleMap(getToolChain().getDriver().ResourceDir);
  5151. llvm::sys::path::append(BuiltinModuleMap, "include");
  5152. llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
  5153. if (llvm::sys::fs::exists(BuiltinModuleMap)) {
  5154. CmdArgs.push_back(Args.MakeArgString("-fmodule-map-file=" +
  5155. BuiltinModuleMap));
  5156. }
  5157. }
  5158. // -fmodule-file can be used to specify files containing precompiled modules.
  5159. if (HaveAnyModules)
  5160. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  5161. else
  5162. Args.ClaimAllArgs(options::OPT_fmodule_file);
  5163. // When building modules and generating crashdumps, we need to dump a module
  5164. // dependency VFS alongside the output.
  5165. if (HaveClangModules && C.isForDiagnostics()) {
  5166. SmallString<128> VFSDir(Output.getFilename());
  5167. llvm::sys::path::replace_extension(VFSDir, ".cache");
  5168. // Add the cache directory as a temp so the crash diagnostics pick it up.
  5169. C.addTempFile(Args.MakeArgString(VFSDir));
  5170. llvm::sys::path::append(VFSDir, "vfs");
  5171. CmdArgs.push_back("-module-dependency-dir");
  5172. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  5173. }
  5174. if (HaveClangModules)
  5175. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  5176. // Pass through all -fmodules-ignore-macro arguments.
  5177. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  5178. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  5179. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  5180. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  5181. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  5182. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  5183. D.Diag(diag::err_drv_argument_not_allowed_with)
  5184. << A->getAsString(Args) << "-fbuild-session-timestamp";
  5185. llvm::sys::fs::file_status Status;
  5186. if (llvm::sys::fs::status(A->getValue(), Status))
  5187. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  5188. CmdArgs.push_back(
  5189. Args.MakeArgString("-fbuild-session-timestamp=" +
  5190. Twine((uint64_t)Status.getLastModificationTime()
  5191. .time_since_epoch()
  5192. .count())));
  5193. }
  5194. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  5195. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  5196. options::OPT_fbuild_session_file))
  5197. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  5198. Args.AddLastArg(CmdArgs,
  5199. options::OPT_fmodules_validate_once_per_build_session);
  5200. }
  5201. Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
  5202. Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
  5203. // -faccess-control is default.
  5204. if (Args.hasFlag(options::OPT_fno_access_control,
  5205. options::OPT_faccess_control, false))
  5206. CmdArgs.push_back("-fno-access-control");
  5207. // -felide-constructors is the default.
  5208. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  5209. options::OPT_felide_constructors, false))
  5210. CmdArgs.push_back("-fno-elide-constructors");
  5211. ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
  5212. if (KernelOrKext || (types::isCXX(InputType) &&
  5213. (RTTIMode == ToolChain::RM_DisabledExplicitly ||
  5214. RTTIMode == ToolChain::RM_DisabledImplicitly)))
  5215. CmdArgs.push_back("-fno-rtti");
  5216. // -fshort-enums=0 is default for all architectures except Hexagon.
  5217. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  5218. getToolChain().getArch() == llvm::Triple::hexagon))
  5219. CmdArgs.push_back("-fshort-enums");
  5220. // -fsigned-char is default.
  5221. if (Arg *A = Args.getLastArg(
  5222. options::OPT_fsigned_char, options::OPT_fno_signed_char,
  5223. options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
  5224. if (A->getOption().matches(options::OPT_funsigned_char) ||
  5225. A->getOption().matches(options::OPT_fno_signed_char)) {
  5226. CmdArgs.push_back("-fno-signed-char");
  5227. }
  5228. } else if (!isSignedCharDefault(getToolChain().getTriple())) {
  5229. CmdArgs.push_back("-fno-signed-char");
  5230. }
  5231. // -fuse-cxa-atexit is default.
  5232. if (!Args.hasFlag(
  5233. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  5234. !IsWindowsCygnus && !IsWindowsGNU &&
  5235. getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
  5236. getToolChain().getArch() != llvm::Triple::hexagon &&
  5237. getToolChain().getArch() != llvm::Triple::xcore &&
  5238. ((getToolChain().getTriple().getVendor() !=
  5239. llvm::Triple::MipsTechnologies) ||
  5240. getToolChain().getTriple().hasEnvironment())) ||
  5241. KernelOrKext)
  5242. CmdArgs.push_back("-fno-use-cxa-atexit");
  5243. // -fms-extensions=0 is default.
  5244. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  5245. IsWindowsMSVC))
  5246. CmdArgs.push_back("-fms-extensions");
  5247. // -fno-use-line-directives is default.
  5248. if (Args.hasFlag(options::OPT_fuse_line_directives,
  5249. options::OPT_fno_use_line_directives, false))
  5250. CmdArgs.push_back("-fuse-line-directives");
  5251. // -fms-compatibility=0 is default.
  5252. if (Args.hasFlag(options::OPT_fms_compatibility,
  5253. options::OPT_fno_ms_compatibility,
  5254. (IsWindowsMSVC &&
  5255. Args.hasFlag(options::OPT_fms_extensions,
  5256. options::OPT_fno_ms_extensions, true))))
  5257. CmdArgs.push_back("-fms-compatibility");
  5258. VersionTuple MSVT =
  5259. getToolChain().computeMSVCVersion(&getToolChain().getDriver(), Args);
  5260. if (!MSVT.empty())
  5261. CmdArgs.push_back(
  5262. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  5263. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  5264. if (ImplyVCPPCXXVer) {
  5265. StringRef LanguageStandard;
  5266. if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
  5267. LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
  5268. .Case("c++14", "-std=c++14")
  5269. .Case("c++latest", "-std=c++1z")
  5270. .Default("");
  5271. if (LanguageStandard.empty())
  5272. D.Diag(clang::diag::warn_drv_unused_argument)
  5273. << StdArg->getAsString(Args);
  5274. }
  5275. if (LanguageStandard.empty()) {
  5276. if (IsMSVC2015Compatible)
  5277. LanguageStandard = "-std=c++14";
  5278. else
  5279. LanguageStandard = "-std=c++11";
  5280. }
  5281. CmdArgs.push_back(LanguageStandard.data());
  5282. }
  5283. // -fno-borland-extensions is default.
  5284. if (Args.hasFlag(options::OPT_fborland_extensions,
  5285. options::OPT_fno_borland_extensions, false))
  5286. CmdArgs.push_back("-fborland-extensions");
  5287. // -fno-declspec is default, except for PS4.
  5288. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  5289. getToolChain().getTriple().isPS4()))
  5290. CmdArgs.push_back("-fdeclspec");
  5291. else if (Args.hasArg(options::OPT_fno_declspec))
  5292. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  5293. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  5294. // than 19.
  5295. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  5296. options::OPT_fno_threadsafe_statics,
  5297. !IsWindowsMSVC || IsMSVC2015Compatible))
  5298. CmdArgs.push_back("-fno-threadsafe-statics");
  5299. // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
  5300. // needs it.
  5301. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  5302. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  5303. CmdArgs.push_back("-fdelayed-template-parsing");
  5304. // -fgnu-keywords default varies depending on language; only pass if
  5305. // specified.
  5306. if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
  5307. options::OPT_fno_gnu_keywords))
  5308. A->render(Args, CmdArgs);
  5309. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  5310. false))
  5311. CmdArgs.push_back("-fgnu89-inline");
  5312. if (Args.hasArg(options::OPT_fno_inline))
  5313. CmdArgs.push_back("-fno-inline");
  5314. if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
  5315. options::OPT_finline_hint_functions,
  5316. options::OPT_fno_inline_functions))
  5317. InlineArg->render(Args, CmdArgs);
  5318. Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
  5319. options::OPT_fno_experimental_new_pass_manager);
  5320. ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  5321. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
  5322. // legacy is the default. Except for deployment target of 10.5,
  5323. // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
  5324. // gets ignored silently.
  5325. if (objcRuntime.isNonFragile()) {
  5326. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  5327. options::OPT_fno_objc_legacy_dispatch,
  5328. objcRuntime.isLegacyDispatchDefaultForArch(
  5329. getToolChain().getArch()))) {
  5330. if (getToolChain().UseObjCMixedDispatch())
  5331. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  5332. else
  5333. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  5334. }
  5335. }
  5336. // When ObjectiveC legacy runtime is in effect on MacOSX,
  5337. // turn on the option to do Array/Dictionary subscripting
  5338. // by default.
  5339. if (getToolChain().getArch() == llvm::Triple::x86 &&
  5340. getToolChain().getTriple().isMacOSX() &&
  5341. !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
  5342. objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
  5343. objcRuntime.isNeXTFamily())
  5344. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  5345. // -fencode-extended-block-signature=1 is default.
  5346. if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
  5347. CmdArgs.push_back("-fencode-extended-block-signature");
  5348. }
  5349. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  5350. // NOTE: This logic is duplicated in ToolChains.cpp.
  5351. bool ARC = isObjCAutoRefCount(Args);
  5352. if (ARC) {
  5353. getToolChain().CheckObjCARC();
  5354. CmdArgs.push_back("-fobjc-arc");
  5355. // FIXME: It seems like this entire block, and several around it should be
  5356. // wrapped in isObjC, but for now we just use it here as this is where it
  5357. // was being used previously.
  5358. if (types::isCXX(InputType) && types::isObjC(InputType)) {
  5359. if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  5360. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  5361. else
  5362. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  5363. }
  5364. // Allow the user to enable full exceptions code emission.
  5365. // We define off for Objective-CC, on for Objective-C++.
  5366. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  5367. options::OPT_fno_objc_arc_exceptions,
  5368. /*default*/ types::isCXX(InputType)))
  5369. CmdArgs.push_back("-fobjc-arc-exceptions");
  5370. }
  5371. // Silence warning for full exception code emission options when explicitly
  5372. // set to use no ARC.
  5373. if (Args.hasArg(options::OPT_fno_objc_arc)) {
  5374. Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
  5375. Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
  5376. }
  5377. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  5378. // rewriter.
  5379. if (rewriteKind != RK_None)
  5380. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  5381. // Pass down -fobjc-weak or -fno-objc-weak if present.
  5382. if (types::isObjC(InputType)) {
  5383. auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
  5384. options::OPT_fno_objc_weak);
  5385. if (!WeakArg) {
  5386. // nothing to do
  5387. } else if (!objcRuntime.allowsWeak()) {
  5388. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  5389. D.Diag(diag::err_objc_weak_unsupported);
  5390. } else {
  5391. WeakArg->render(Args, CmdArgs);
  5392. }
  5393. }
  5394. if (Args.hasFlag(options::OPT_fapplication_extension,
  5395. options::OPT_fno_application_extension, false))
  5396. CmdArgs.push_back("-fapplication-extension");
  5397. // Handle GCC-style exception args.
  5398. if (!C.getDriver().IsCLMode())
  5399. addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
  5400. CmdArgs);
  5401. if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
  5402. getToolChain().UseSjLjExceptions(Args))
  5403. CmdArgs.push_back("-fsjlj-exceptions");
  5404. // C++ "sane" operator new.
  5405. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  5406. options::OPT_fno_assume_sane_operator_new))
  5407. CmdArgs.push_back("-fno-assume-sane-operator-new");
  5408. // -frelaxed-template-template-args is off by default, as it is a severe
  5409. // breaking change until a corresponding change to template partial ordering
  5410. // is provided.
  5411. if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
  5412. options::OPT_fno_relaxed_template_template_args, false))
  5413. CmdArgs.push_back("-frelaxed-template-template-args");
  5414. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  5415. // most platforms.
  5416. if (Args.hasFlag(options::OPT_fsized_deallocation,
  5417. options::OPT_fno_sized_deallocation, false))
  5418. CmdArgs.push_back("-fsized-deallocation");
  5419. // -faligned-allocation is on by default in C++17 onwards and otherwise off
  5420. // by default.
  5421. if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
  5422. options::OPT_fno_aligned_allocation,
  5423. options::OPT_faligned_new_EQ)) {
  5424. if (A->getOption().matches(options::OPT_fno_aligned_allocation))
  5425. CmdArgs.push_back("-fno-aligned-allocation");
  5426. else
  5427. CmdArgs.push_back("-faligned-allocation");
  5428. }
  5429. // The default new alignment can be specified using a dedicated option or via
  5430. // a GCC-compatible option that also turns on aligned allocation.
  5431. if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
  5432. options::OPT_faligned_new_EQ))
  5433. CmdArgs.push_back(
  5434. Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
  5435. // -fconstant-cfstrings is default, and may be subject to argument translation
  5436. // on Darwin.
  5437. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  5438. options::OPT_fno_constant_cfstrings) ||
  5439. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  5440. options::OPT_mno_constant_cfstrings))
  5441. CmdArgs.push_back("-fno-constant-cfstrings");
  5442. // -fshort-wchar default varies depending on platform; only
  5443. // pass if specified.
  5444. if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  5445. options::OPT_fno_short_wchar))
  5446. A->render(Args, CmdArgs);
  5447. // -fno-pascal-strings is default, only pass non-default.
  5448. if (Args.hasFlag(options::OPT_fpascal_strings,
  5449. options::OPT_fno_pascal_strings, false))
  5450. CmdArgs.push_back("-fpascal-strings");
  5451. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  5452. // -fno-pack-struct doesn't apply to -fpack-struct=.
  5453. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  5454. std::string PackStructStr = "-fpack-struct=";
  5455. PackStructStr += A->getValue();
  5456. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  5457. } else if (Args.hasFlag(options::OPT_fpack_struct,
  5458. options::OPT_fno_pack_struct, false)) {
  5459. CmdArgs.push_back("-fpack-struct=1");
  5460. }
  5461. // Handle -fmax-type-align=N and -fno-type-align
  5462. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  5463. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  5464. if (!SkipMaxTypeAlign) {
  5465. std::string MaxTypeAlignStr = "-fmax-type-align=";
  5466. MaxTypeAlignStr += A->getValue();
  5467. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  5468. }
  5469. } else if (getToolChain().getTriple().isOSDarwin()) {
  5470. if (!SkipMaxTypeAlign) {
  5471. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  5472. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  5473. }
  5474. }
  5475. // -fcommon is the default unless compiling kernel code or the target says so
  5476. bool NoCommonDefault =
  5477. KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
  5478. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  5479. !NoCommonDefault))
  5480. CmdArgs.push_back("-fno-common");
  5481. // -fsigned-bitfields is default, and clang doesn't yet support
  5482. // -funsigned-bitfields.
  5483. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  5484. options::OPT_funsigned_bitfields))
  5485. D.Diag(diag::warn_drv_clang_unsupported)
  5486. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  5487. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  5488. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  5489. D.Diag(diag::err_drv_clang_unsupported)
  5490. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  5491. // -finput_charset=UTF-8 is default. Reject others
  5492. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  5493. StringRef value = inputCharset->getValue();
  5494. if (!value.equals_lower("utf-8"))
  5495. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  5496. << value;
  5497. }
  5498. // -fexec_charset=UTF-8 is default. Reject others
  5499. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  5500. StringRef value = execCharset->getValue();
  5501. if (!value.equals_lower("utf-8"))
  5502. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  5503. << value;
  5504. }
  5505. // -fcaret-diagnostics is default.
  5506. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  5507. options::OPT_fno_caret_diagnostics, true))
  5508. CmdArgs.push_back("-fno-caret-diagnostics");
  5509. // -fdiagnostics-fixit-info is default, only pass non-default.
  5510. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  5511. options::OPT_fno_diagnostics_fixit_info))
  5512. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  5513. // Enable -fdiagnostics-show-option by default.
  5514. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  5515. options::OPT_fno_diagnostics_show_option))
  5516. CmdArgs.push_back("-fdiagnostics-show-option");
  5517. if (const Arg *A =
  5518. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  5519. CmdArgs.push_back("-fdiagnostics-show-category");
  5520. CmdArgs.push_back(A->getValue());
  5521. }
  5522. if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
  5523. options::OPT_fno_diagnostics_show_hotness, false))
  5524. CmdArgs.push_back("-fdiagnostics-show-hotness");
  5525. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  5526. CmdArgs.push_back("-fdiagnostics-format");
  5527. CmdArgs.push_back(A->getValue());
  5528. }
  5529. if (Arg *A = Args.getLastArg(
  5530. options::OPT_fdiagnostics_show_note_include_stack,
  5531. options::OPT_fno_diagnostics_show_note_include_stack)) {
  5532. if (A->getOption().matches(
  5533. options::OPT_fdiagnostics_show_note_include_stack))
  5534. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  5535. else
  5536. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  5537. }
  5538. // Color diagnostics are parsed by the driver directly from argv
  5539. // and later re-parsed to construct this job; claim any possible
  5540. // color diagnostic here to avoid warn_drv_unused_argument and
  5541. // diagnose bad OPT_fdiagnostics_color_EQ values.
  5542. for (Arg *A : Args) {
  5543. const Option &O = A->getOption();
  5544. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  5545. !O.matches(options::OPT_fdiagnostics_color) &&
  5546. !O.matches(options::OPT_fno_color_diagnostics) &&
  5547. !O.matches(options::OPT_fno_diagnostics_color) &&
  5548. !O.matches(options::OPT_fdiagnostics_color_EQ))
  5549. continue;
  5550. if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
  5551. StringRef Value(A->getValue());
  5552. if (Value != "always" && Value != "never" && Value != "auto")
  5553. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  5554. << ("-fdiagnostics-color=" + Value).str();
  5555. }
  5556. A->claim();
  5557. }
  5558. if (D.getDiags().getDiagnosticOptions().ShowColors)
  5559. CmdArgs.push_back("-fcolor-diagnostics");
  5560. if (Args.hasArg(options::OPT_fansi_escape_codes))
  5561. CmdArgs.push_back("-fansi-escape-codes");
  5562. if (!Args.hasFlag(options::OPT_fshow_source_location,
  5563. options::OPT_fno_show_source_location))
  5564. CmdArgs.push_back("-fno-show-source-location");
  5565. if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
  5566. CmdArgs.push_back("-fdiagnostics-absolute-paths");
  5567. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  5568. true))
  5569. CmdArgs.push_back("-fno-show-column");
  5570. if (!Args.hasFlag(options::OPT_fspell_checking,
  5571. options::OPT_fno_spell_checking))
  5572. CmdArgs.push_back("-fno-spell-checking");
  5573. // -fno-asm-blocks is default.
  5574. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  5575. false))
  5576. CmdArgs.push_back("-fasm-blocks");
  5577. // -fgnu-inline-asm is default.
  5578. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  5579. options::OPT_fno_gnu_inline_asm, true))
  5580. CmdArgs.push_back("-fno-gnu-inline-asm");
  5581. // Enable vectorization per default according to the optimization level
  5582. // selected. For optimization levels that want vectorization we use the alias
  5583. // option to simplify the hasFlag logic.
  5584. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  5585. OptSpecifier VectorizeAliasOption =
  5586. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  5587. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  5588. options::OPT_fno_vectorize, EnableVec))
  5589. CmdArgs.push_back("-vectorize-loops");
  5590. // -fslp-vectorize is enabled based on the optimization level selected.
  5591. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  5592. OptSpecifier SLPVectAliasOption =
  5593. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  5594. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  5595. options::OPT_fno_slp_vectorize, EnableSLPVec))
  5596. CmdArgs.push_back("-vectorize-slp");
  5597. // -fno-slp-vectorize-aggressive is default.
  5598. if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
  5599. options::OPT_fno_slp_vectorize_aggressive, false))
  5600. CmdArgs.push_back("-vectorize-slp-aggressive");
  5601. if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
  5602. A->render(Args, CmdArgs);
  5603. if (Arg *A = Args.getLastArg(
  5604. options::OPT_fsanitize_undefined_strip_path_components_EQ))
  5605. A->render(Args, CmdArgs);
  5606. // -fdollars-in-identifiers default varies depending on platform and
  5607. // language; only pass if specified.
  5608. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  5609. options::OPT_fno_dollars_in_identifiers)) {
  5610. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  5611. CmdArgs.push_back("-fdollars-in-identifiers");
  5612. else
  5613. CmdArgs.push_back("-fno-dollars-in-identifiers");
  5614. }
  5615. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  5616. // practical purposes.
  5617. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  5618. options::OPT_fno_unit_at_a_time)) {
  5619. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  5620. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  5621. }
  5622. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  5623. options::OPT_fno_apple_pragma_pack, false))
  5624. CmdArgs.push_back("-fapple-pragma-pack");
  5625. // le32-specific flags:
  5626. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  5627. // by default.
  5628. if (getToolChain().getArch() == llvm::Triple::le32) {
  5629. CmdArgs.push_back("-fno-math-builtin");
  5630. }
  5631. if (Args.hasFlag(options::OPT_fsave_optimization_record,
  5632. options::OPT_fno_save_optimization_record, false)) {
  5633. CmdArgs.push_back("-opt-record-file");
  5634. const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
  5635. if (A) {
  5636. CmdArgs.push_back(A->getValue());
  5637. } else {
  5638. SmallString<128> F;
  5639. if (Output.isFilename() && (Args.hasArg(options::OPT_c) ||
  5640. Args.hasArg(options::OPT_S))) {
  5641. F = Output.getFilename();
  5642. } else {
  5643. // Use the input filename.
  5644. F = llvm::sys::path::stem(Input.getBaseInput());
  5645. // If we're compiling for an offload architecture (i.e. a CUDA device),
  5646. // we need to make the file name for the device compilation different
  5647. // from the host compilation.
  5648. if (!JA.isDeviceOffloading(Action::OFK_None) &&
  5649. !JA.isDeviceOffloading(Action::OFK_Host)) {
  5650. llvm::sys::path::replace_extension(F, "");
  5651. F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
  5652. Triple.normalize());
  5653. F += "-";
  5654. F += JA.getOffloadingArch();
  5655. }
  5656. }
  5657. llvm::sys::path::replace_extension(F, "opt.yaml");
  5658. CmdArgs.push_back(Args.MakeArgString(F));
  5659. }
  5660. }
  5661. // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
  5662. //
  5663. // FIXME: Now that PR4941 has been fixed this can be enabled.
  5664. #if 0
  5665. if (getToolChain().getTriple().isOSDarwin() &&
  5666. (getToolChain().getArch() == llvm::Triple::arm ||
  5667. getToolChain().getArch() == llvm::Triple::thumb)) {
  5668. if (!Args.hasArg(options::OPT_fbuiltin_strcat))
  5669. CmdArgs.push_back("-fno-builtin-strcat");
  5670. if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
  5671. CmdArgs.push_back("-fno-builtin-strcpy");
  5672. }
  5673. #endif
  5674. // Enable rewrite includes if the user's asked for it or if we're generating
  5675. // diagnostics.
  5676. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  5677. // nice to enable this when doing a crashdump for modules as well.
  5678. if (Args.hasFlag(options::OPT_frewrite_includes,
  5679. options::OPT_fno_rewrite_includes, false) ||
  5680. (C.isForDiagnostics() && !HaveAnyModules))
  5681. CmdArgs.push_back("-frewrite-includes");
  5682. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  5683. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  5684. options::OPT_traditional_cpp)) {
  5685. if (isa<PreprocessJobAction>(JA))
  5686. CmdArgs.push_back("-traditional-cpp");
  5687. else
  5688. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  5689. }
  5690. Args.AddLastArg(CmdArgs, options::OPT_dM);
  5691. Args.AddLastArg(CmdArgs, options::OPT_dD);
  5692. // Handle serialized diagnostics.
  5693. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  5694. CmdArgs.push_back("-serialize-diagnostic-file");
  5695. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  5696. }
  5697. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  5698. CmdArgs.push_back("-fretain-comments-from-system-headers");
  5699. // Forward -fcomment-block-commands to -cc1.
  5700. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  5701. // Forward -fparse-all-comments to -cc1.
  5702. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  5703. // Turn -fplugin=name.so into -load name.so
  5704. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  5705. CmdArgs.push_back("-load");
  5706. CmdArgs.push_back(A->getValue());
  5707. A->claim();
  5708. }
  5709. // Setup statistics file output.
  5710. if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
  5711. StringRef SaveStats = A->getValue();
  5712. SmallString<128> StatsFile;
  5713. bool DoSaveStats = false;
  5714. if (SaveStats == "obj") {
  5715. if (Output.isFilename()) {
  5716. StatsFile.assign(Output.getFilename());
  5717. llvm::sys::path::remove_filename(StatsFile);
  5718. }
  5719. DoSaveStats = true;
  5720. } else if (SaveStats == "cwd") {
  5721. DoSaveStats = true;
  5722. } else {
  5723. D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
  5724. }
  5725. if (DoSaveStats) {
  5726. StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
  5727. llvm::sys::path::append(StatsFile, BaseName);
  5728. llvm::sys::path::replace_extension(StatsFile, "stats");
  5729. CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
  5730. StatsFile));
  5731. }
  5732. }
  5733. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  5734. // parser.
  5735. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  5736. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  5737. A->claim();
  5738. // We translate this by hand to the -cc1 argument, since nightly test uses
  5739. // it and developers have been trained to spell it with -mllvm. Both
  5740. // spellings are now deprecated and should be removed.
  5741. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  5742. CmdArgs.push_back("-disable-llvm-optzns");
  5743. } else {
  5744. A->render(Args, CmdArgs);
  5745. }
  5746. }
  5747. // With -save-temps, we want to save the unoptimized bitcode output from the
  5748. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  5749. // by the frontend.
  5750. // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
  5751. // has slightly different breakdown between stages.
  5752. // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
  5753. // pristine IR generated by the frontend. Ideally, a new compile action should
  5754. // be added so both IR can be captured.
  5755. if (C.getDriver().isSaveTempsEnabled() &&
  5756. !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
  5757. isa<CompileJobAction>(JA))
  5758. CmdArgs.push_back("-disable-llvm-passes");
  5759. if (Output.getType() == types::TY_Dependencies) {
  5760. // Handled with other dependency code.
  5761. } else if (Output.isFilename()) {
  5762. CmdArgs.push_back("-o");
  5763. CmdArgs.push_back(Output.getFilename());
  5764. } else {
  5765. assert(Output.isNothing() && "Invalid output.");
  5766. }
  5767. addDashXForInput(Args, Input, CmdArgs);
  5768. if (Input.isFilename())
  5769. CmdArgs.push_back(Input.getFilename());
  5770. else
  5771. Input.getInputArg().renderAsInput(Args, CmdArgs);
  5772. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  5773. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5774. // Optionally embed the -cc1 level arguments into the debug info, for build
  5775. // analysis.
  5776. if (getToolChain().UseDwarfDebugFlags()) {
  5777. ArgStringList OriginalArgs;
  5778. for (const auto &Arg : Args)
  5779. Arg->render(Args, OriginalArgs);
  5780. SmallString<256> Flags;
  5781. Flags += Exec;
  5782. for (const char *OriginalArg : OriginalArgs) {
  5783. SmallString<128> EscapedArg;
  5784. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5785. Flags += " ";
  5786. Flags += EscapedArg;
  5787. }
  5788. CmdArgs.push_back("-dwarf-debug-flags");
  5789. CmdArgs.push_back(Args.MakeArgString(Flags));
  5790. }
  5791. // Add the split debug info name to the command lines here so we
  5792. // can propagate it to the backend.
  5793. bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
  5794. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  5795. isa<BackendJobAction>(JA));
  5796. const char *SplitDwarfOut;
  5797. if (SplitDwarf) {
  5798. CmdArgs.push_back("-split-dwarf-file");
  5799. SplitDwarfOut = SplitDebugName(Args, Input);
  5800. CmdArgs.push_back(SplitDwarfOut);
  5801. }
  5802. // Host-side cuda compilation receives device-side outputs as Inputs[1...].
  5803. // Include them with -fcuda-include-gpubinary.
  5804. if (IsCuda && Inputs.size() > 1)
  5805. for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
  5806. CmdArgs.push_back("-fcuda-include-gpubinary");
  5807. CmdArgs.push_back(I->getFilename());
  5808. }
  5809. // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
  5810. // to specify the result of the compile phase on the host, so the meaningful
  5811. // device declarations can be identified. Also, -fopenmp-is-device is passed
  5812. // along to tell the frontend that it is generating code for a device, so that
  5813. // only the relevant declarations are emitted.
  5814. if (IsOpenMPDevice && Inputs.size() == 2) {
  5815. CmdArgs.push_back("-fopenmp-is-device");
  5816. CmdArgs.push_back("-fopenmp-host-ir-file-path");
  5817. CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
  5818. }
  5819. // For all the host OpenMP offloading compile jobs we need to pass the targets
  5820. // information using -fopenmp-targets= option.
  5821. if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
  5822. SmallString<128> TargetInfo("-fopenmp-targets=");
  5823. Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
  5824. assert(Tgts && Tgts->getNumValues() &&
  5825. "OpenMP offloading has to have targets specified.");
  5826. for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
  5827. if (i)
  5828. TargetInfo += ',';
  5829. // We need to get the string from the triple because it may be not exactly
  5830. // the same as the one we get directly from the arguments.
  5831. llvm::Triple T(Tgts->getValue(i));
  5832. TargetInfo += T.getTriple();
  5833. }
  5834. CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
  5835. }
  5836. bool WholeProgramVTables =
  5837. Args.hasFlag(options::OPT_fwhole_program_vtables,
  5838. options::OPT_fno_whole_program_vtables, false);
  5839. if (WholeProgramVTables) {
  5840. if (!D.isUsingLTO())
  5841. D.Diag(diag::err_drv_argument_only_allowed_with)
  5842. << "-fwhole-program-vtables"
  5843. << "-flto";
  5844. CmdArgs.push_back("-fwhole-program-vtables");
  5845. }
  5846. // Finally add the compile command to the compilation.
  5847. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5848. Output.getType() == types::TY_Object &&
  5849. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  5850. auto CLCommand =
  5851. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  5852. C.addCommand(llvm::make_unique<FallbackCommand>(
  5853. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  5854. } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5855. isa<PrecompileJobAction>(JA)) {
  5856. // In /fallback builds, run the main compilation even if the pch generation
  5857. // fails, so that the main compilation's fallback to cl.exe runs.
  5858. C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
  5859. CmdArgs, Inputs));
  5860. } else {
  5861. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5862. }
  5863. // Handle the debug info splitting at object creation time if we're
  5864. // creating an object.
  5865. // TODO: Currently only works on linux with newer objcopy.
  5866. if (SplitDwarf && Output.getType() == types::TY_Object)
  5867. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
  5868. if (Arg *A = Args.getLastArg(options::OPT_pg))
  5869. if (Args.hasArg(options::OPT_fomit_frame_pointer))
  5870. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  5871. << A->getAsString(Args);
  5872. // Claim some arguments which clang supports automatically.
  5873. // -fpch-preprocess is used with gcc to add a special marker in the output to
  5874. // include the PCH file. Clang's PTH solution is completely transparent, so we
  5875. // do not need to deal with it at all.
  5876. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  5877. // Claim some arguments which clang doesn't support, but we don't
  5878. // care to warn the user about.
  5879. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  5880. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  5881. // Disable warnings for clang -E -emit-llvm foo.c
  5882. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5883. }
  5884. /// Add options related to the Objective-C runtime/ABI.
  5885. ///
  5886. /// Returns true if the runtime is non-fragile.
  5887. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  5888. ArgStringList &cmdArgs,
  5889. RewriteKind rewriteKind) const {
  5890. // Look for the controlling runtime option.
  5891. Arg *runtimeArg =
  5892. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  5893. options::OPT_fobjc_runtime_EQ);
  5894. // Just forward -fobjc-runtime= to the frontend. This supercedes
  5895. // options about fragility.
  5896. if (runtimeArg &&
  5897. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  5898. ObjCRuntime runtime;
  5899. StringRef value = runtimeArg->getValue();
  5900. if (runtime.tryParse(value)) {
  5901. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  5902. << value;
  5903. }
  5904. runtimeArg->render(args, cmdArgs);
  5905. return runtime;
  5906. }
  5907. // Otherwise, we'll need the ABI "version". Version numbers are
  5908. // slightly confusing for historical reasons:
  5909. // 1 - Traditional "fragile" ABI
  5910. // 2 - Non-fragile ABI, version 1
  5911. // 3 - Non-fragile ABI, version 2
  5912. unsigned objcABIVersion = 1;
  5913. // If -fobjc-abi-version= is present, use that to set the version.
  5914. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  5915. StringRef value = abiArg->getValue();
  5916. if (value == "1")
  5917. objcABIVersion = 1;
  5918. else if (value == "2")
  5919. objcABIVersion = 2;
  5920. else if (value == "3")
  5921. objcABIVersion = 3;
  5922. else
  5923. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  5924. } else {
  5925. // Otherwise, determine if we are using the non-fragile ABI.
  5926. bool nonFragileABIIsDefault =
  5927. (rewriteKind == RK_NonFragile ||
  5928. (rewriteKind == RK_None &&
  5929. getToolChain().IsObjCNonFragileABIDefault()));
  5930. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  5931. options::OPT_fno_objc_nonfragile_abi,
  5932. nonFragileABIIsDefault)) {
  5933. // Determine the non-fragile ABI version to use.
  5934. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  5935. unsigned nonFragileABIVersion = 1;
  5936. #else
  5937. unsigned nonFragileABIVersion = 2;
  5938. #endif
  5939. if (Arg *abiArg =
  5940. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  5941. StringRef value = abiArg->getValue();
  5942. if (value == "1")
  5943. nonFragileABIVersion = 1;
  5944. else if (value == "2")
  5945. nonFragileABIVersion = 2;
  5946. else
  5947. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  5948. << value;
  5949. }
  5950. objcABIVersion = 1 + nonFragileABIVersion;
  5951. } else {
  5952. objcABIVersion = 1;
  5953. }
  5954. }
  5955. // We don't actually care about the ABI version other than whether
  5956. // it's non-fragile.
  5957. bool isNonFragile = objcABIVersion != 1;
  5958. // If we have no runtime argument, ask the toolchain for its default runtime.
  5959. // However, the rewriter only really supports the Mac runtime, so assume that.
  5960. ObjCRuntime runtime;
  5961. if (!runtimeArg) {
  5962. switch (rewriteKind) {
  5963. case RK_None:
  5964. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5965. break;
  5966. case RK_Fragile:
  5967. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  5968. break;
  5969. case RK_NonFragile:
  5970. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5971. break;
  5972. }
  5973. // -fnext-runtime
  5974. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  5975. // On Darwin, make this use the default behavior for the toolchain.
  5976. if (getToolChain().getTriple().isOSDarwin()) {
  5977. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5978. // Otherwise, build for a generic macosx port.
  5979. } else {
  5980. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5981. }
  5982. // -fgnu-runtime
  5983. } else {
  5984. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  5985. // Legacy behaviour is to target the gnustep runtime if we are in
  5986. // non-fragile mode or the GCC runtime in fragile mode.
  5987. if (isNonFragile)
  5988. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
  5989. else
  5990. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  5991. }
  5992. cmdArgs.push_back(
  5993. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  5994. return runtime;
  5995. }
  5996. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  5997. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  5998. I += HaveDash;
  5999. return !HaveDash;
  6000. }
  6001. namespace {
  6002. struct EHFlags {
  6003. bool Synch = false;
  6004. bool Asynch = false;
  6005. bool NoUnwindC = false;
  6006. };
  6007. } // end anonymous namespace
  6008. /// /EH controls whether to run destructor cleanups when exceptions are
  6009. /// thrown. There are three modifiers:
  6010. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  6011. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  6012. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  6013. /// - c: Assume that extern "C" functions are implicitly nounwind.
  6014. /// The default is /EHs-c-, meaning cleanups are disabled.
  6015. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  6016. EHFlags EH;
  6017. std::vector<std::string> EHArgs =
  6018. Args.getAllArgValues(options::OPT__SLASH_EH);
  6019. for (auto EHVal : EHArgs) {
  6020. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  6021. switch (EHVal[I]) {
  6022. case 'a':
  6023. EH.Asynch = maybeConsumeDash(EHVal, I);
  6024. if (EH.Asynch)
  6025. EH.Synch = false;
  6026. continue;
  6027. case 'c':
  6028. EH.NoUnwindC = maybeConsumeDash(EHVal, I);
  6029. continue;
  6030. case 's':
  6031. EH.Synch = maybeConsumeDash(EHVal, I);
  6032. if (EH.Synch)
  6033. EH.Asynch = false;
  6034. continue;
  6035. default:
  6036. break;
  6037. }
  6038. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  6039. break;
  6040. }
  6041. }
  6042. // The /GX, /GX- flags are only processed if there are not /EH flags.
  6043. // The default is that /GX is not specified.
  6044. if (EHArgs.empty() &&
  6045. Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
  6046. /*default=*/false)) {
  6047. EH.Synch = true;
  6048. EH.NoUnwindC = true;
  6049. }
  6050. return EH;
  6051. }
  6052. void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
  6053. ArgStringList &CmdArgs,
  6054. codegenoptions::DebugInfoKind *DebugInfoKind,
  6055. bool *EmitCodeView) const {
  6056. unsigned RTOptionID = options::OPT__SLASH_MT;
  6057. if (Args.hasArg(options::OPT__SLASH_LDd))
  6058. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  6059. // but defining _DEBUG is sticky.
  6060. RTOptionID = options::OPT__SLASH_MTd;
  6061. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  6062. RTOptionID = A->getOption().getID();
  6063. StringRef FlagForCRT;
  6064. switch (RTOptionID) {
  6065. case options::OPT__SLASH_MD:
  6066. if (Args.hasArg(options::OPT__SLASH_LDd))
  6067. CmdArgs.push_back("-D_DEBUG");
  6068. CmdArgs.push_back("-D_MT");
  6069. CmdArgs.push_back("-D_DLL");
  6070. FlagForCRT = "--dependent-lib=msvcrt";
  6071. break;
  6072. case options::OPT__SLASH_MDd:
  6073. CmdArgs.push_back("-D_DEBUG");
  6074. CmdArgs.push_back("-D_MT");
  6075. CmdArgs.push_back("-D_DLL");
  6076. FlagForCRT = "--dependent-lib=msvcrtd";
  6077. break;
  6078. case options::OPT__SLASH_MT:
  6079. if (Args.hasArg(options::OPT__SLASH_LDd))
  6080. CmdArgs.push_back("-D_DEBUG");
  6081. CmdArgs.push_back("-D_MT");
  6082. CmdArgs.push_back("-flto-visibility-public-std");
  6083. FlagForCRT = "--dependent-lib=libcmt";
  6084. break;
  6085. case options::OPT__SLASH_MTd:
  6086. CmdArgs.push_back("-D_DEBUG");
  6087. CmdArgs.push_back("-D_MT");
  6088. CmdArgs.push_back("-flto-visibility-public-std");
  6089. FlagForCRT = "--dependent-lib=libcmtd";
  6090. break;
  6091. default:
  6092. llvm_unreachable("Unexpected option ID.");
  6093. }
  6094. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  6095. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  6096. } else {
  6097. CmdArgs.push_back(FlagForCRT.data());
  6098. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  6099. // users want. The /Za flag to cl.exe turns this off, but it's not
  6100. // implemented in clang.
  6101. CmdArgs.push_back("--dependent-lib=oldnames");
  6102. }
  6103. // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
  6104. // would produce interleaved output, so ignore /showIncludes in such cases.
  6105. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
  6106. if (Arg *A = Args.getLastArg(options::OPT_show_includes))
  6107. A->render(Args, CmdArgs);
  6108. // This controls whether or not we emit RTTI data for polymorphic types.
  6109. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  6110. /*default=*/false))
  6111. CmdArgs.push_back("-fno-rtti-data");
  6112. // This controls whether or not we emit stack-protector instrumentation.
  6113. // In MSVC, Buffer Security Check (/GS) is on by default.
  6114. if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
  6115. /*default=*/true)) {
  6116. CmdArgs.push_back("-stack-protector");
  6117. CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
  6118. }
  6119. // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
  6120. if (Arg *DebugInfoArg =
  6121. Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
  6122. options::OPT_gline_tables_only)) {
  6123. *EmitCodeView = true;
  6124. if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
  6125. *DebugInfoKind = codegenoptions::LimitedDebugInfo;
  6126. else
  6127. *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
  6128. CmdArgs.push_back("-gcodeview");
  6129. } else {
  6130. *EmitCodeView = false;
  6131. }
  6132. const Driver &D = getToolChain().getDriver();
  6133. EHFlags EH = parseClangCLEHFlags(D, Args);
  6134. if (EH.Synch || EH.Asynch) {
  6135. if (types::isCXX(InputType))
  6136. CmdArgs.push_back("-fcxx-exceptions");
  6137. CmdArgs.push_back("-fexceptions");
  6138. }
  6139. if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
  6140. CmdArgs.push_back("-fexternc-nounwind");
  6141. // /EP should expand to -E -P.
  6142. if (Args.hasArg(options::OPT__SLASH_EP)) {
  6143. CmdArgs.push_back("-E");
  6144. CmdArgs.push_back("-P");
  6145. }
  6146. unsigned VolatileOptionID;
  6147. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  6148. getToolChain().getArch() == llvm::Triple::x86)
  6149. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  6150. else
  6151. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  6152. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  6153. VolatileOptionID = A->getOption().getID();
  6154. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  6155. CmdArgs.push_back("-fms-volatile");
  6156. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  6157. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  6158. if (MostGeneralArg && BestCaseArg)
  6159. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  6160. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  6161. if (MostGeneralArg) {
  6162. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  6163. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  6164. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  6165. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  6166. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  6167. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  6168. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  6169. << FirstConflict->getAsString(Args)
  6170. << SecondConflict->getAsString(Args);
  6171. if (SingleArg)
  6172. CmdArgs.push_back("-fms-memptr-rep=single");
  6173. else if (MultipleArg)
  6174. CmdArgs.push_back("-fms-memptr-rep=multiple");
  6175. else
  6176. CmdArgs.push_back("-fms-memptr-rep=virtual");
  6177. }
  6178. if (Args.getLastArg(options::OPT__SLASH_Gd))
  6179. CmdArgs.push_back("-fdefault-calling-conv=cdecl");
  6180. else if (Args.getLastArg(options::OPT__SLASH_Gr))
  6181. CmdArgs.push_back("-fdefault-calling-conv=fastcall");
  6182. else if (Args.getLastArg(options::OPT__SLASH_Gz))
  6183. CmdArgs.push_back("-fdefault-calling-conv=stdcall");
  6184. else if (Args.getLastArg(options::OPT__SLASH_Gv))
  6185. CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
  6186. if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
  6187. A->render(Args, CmdArgs);
  6188. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  6189. CmdArgs.push_back("-fdiagnostics-format");
  6190. if (Args.hasArg(options::OPT__SLASH_fallback))
  6191. CmdArgs.push_back("msvc-fallback");
  6192. else
  6193. CmdArgs.push_back("msvc");
  6194. }
  6195. }
  6196. visualstudio::Compiler *Clang::getCLFallback() const {
  6197. if (!CLFallback)
  6198. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  6199. return CLFallback.get();
  6200. }
  6201. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  6202. ArgStringList &CmdArgs) const {
  6203. StringRef CPUName;
  6204. StringRef ABIName;
  6205. const llvm::Triple &Triple = getToolChain().getTriple();
  6206. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  6207. CmdArgs.push_back("-target-abi");
  6208. CmdArgs.push_back(ABIName.data());
  6209. }
  6210. void ClangAs::AddX86TargetArgs(const ArgList &Args,
  6211. ArgStringList &CmdArgs) const {
  6212. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  6213. StringRef Value = A->getValue();
  6214. if (Value == "intel" || Value == "att") {
  6215. CmdArgs.push_back("-mllvm");
  6216. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  6217. } else {
  6218. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  6219. << A->getOption().getName() << Value;
  6220. }
  6221. }
  6222. }
  6223. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  6224. const InputInfo &Output, const InputInfoList &Inputs,
  6225. const ArgList &Args,
  6226. const char *LinkingOutput) const {
  6227. ArgStringList CmdArgs;
  6228. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  6229. const InputInfo &Input = Inputs[0];
  6230. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  6231. const std::string &TripleStr = Triple.getTriple();
  6232. // Don't warn about "clang -w -c foo.s"
  6233. Args.ClaimAllArgs(options::OPT_w);
  6234. // and "clang -emit-llvm -c foo.s"
  6235. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6236. claimNoWarnArgs(Args);
  6237. // Invoke ourselves in -cc1as mode.
  6238. //
  6239. // FIXME: Implement custom jobs for internal actions.
  6240. CmdArgs.push_back("-cc1as");
  6241. // Add the "effective" target triple.
  6242. CmdArgs.push_back("-triple");
  6243. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  6244. // Set the output mode, we currently only expect to be used as a real
  6245. // assembler.
  6246. CmdArgs.push_back("-filetype");
  6247. CmdArgs.push_back("obj");
  6248. // Set the main file name, so that debug info works even with
  6249. // -save-temps or preprocessed assembly.
  6250. CmdArgs.push_back("-main-file-name");
  6251. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  6252. // Add the target cpu
  6253. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  6254. if (!CPU.empty()) {
  6255. CmdArgs.push_back("-target-cpu");
  6256. CmdArgs.push_back(Args.MakeArgString(CPU));
  6257. }
  6258. // Add the target features
  6259. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  6260. // Ignore explicit -force_cpusubtype_ALL option.
  6261. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  6262. // Pass along any -I options so we get proper .include search paths.
  6263. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  6264. // Determine the original source input.
  6265. const Action *SourceAction = &JA;
  6266. while (SourceAction->getKind() != Action::InputClass) {
  6267. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  6268. SourceAction = SourceAction->getInputs()[0];
  6269. }
  6270. // Forward -g and handle debug info related flags, assuming we are dealing
  6271. // with an actual assembly file.
  6272. bool WantDebug = false;
  6273. unsigned DwarfVersion = 0;
  6274. Args.ClaimAllArgs(options::OPT_g_Group);
  6275. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  6276. WantDebug = !A->getOption().matches(options::OPT_g0) &&
  6277. !A->getOption().matches(options::OPT_ggdb0);
  6278. if (WantDebug)
  6279. DwarfVersion = DwarfVersionNum(A->getSpelling());
  6280. }
  6281. if (DwarfVersion == 0)
  6282. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  6283. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  6284. if (SourceAction->getType() == types::TY_Asm ||
  6285. SourceAction->getType() == types::TY_PP_Asm) {
  6286. // You might think that it would be ok to set DebugInfoKind outside of
  6287. // the guard for source type, however there is a test which asserts
  6288. // that some assembler invocation receives no -debug-info-kind,
  6289. // and it's not clear whether that test is just overly restrictive.
  6290. DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
  6291. : codegenoptions::NoDebugInfo);
  6292. // Add the -fdebug-compilation-dir flag if needed.
  6293. addDebugCompDirArg(Args, CmdArgs);
  6294. // Set the AT_producer to the clang version when using the integrated
  6295. // assembler on assembly source files.
  6296. CmdArgs.push_back("-dwarf-debug-producer");
  6297. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  6298. // And pass along -I options
  6299. Args.AddAllArgs(CmdArgs, options::OPT_I);
  6300. }
  6301. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  6302. llvm::DebuggerKind::Default);
  6303. // Handle -fPIC et al -- the relocation-model affects the assembler
  6304. // for some targets.
  6305. llvm::Reloc::Model RelocationModel;
  6306. unsigned PICLevel;
  6307. bool IsPIE;
  6308. std::tie(RelocationModel, PICLevel, IsPIE) =
  6309. ParsePICArgs(getToolChain(), Args);
  6310. const char *RMName = RelocationModelName(RelocationModel);
  6311. if (RMName) {
  6312. CmdArgs.push_back("-mrelocation-model");
  6313. CmdArgs.push_back(RMName);
  6314. }
  6315. // Optionally embed the -cc1as level arguments into the debug info, for build
  6316. // analysis.
  6317. if (getToolChain().UseDwarfDebugFlags()) {
  6318. ArgStringList OriginalArgs;
  6319. for (const auto &Arg : Args)
  6320. Arg->render(Args, OriginalArgs);
  6321. SmallString<256> Flags;
  6322. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  6323. Flags += Exec;
  6324. for (const char *OriginalArg : OriginalArgs) {
  6325. SmallString<128> EscapedArg;
  6326. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  6327. Flags += " ";
  6328. Flags += EscapedArg;
  6329. }
  6330. CmdArgs.push_back("-dwarf-debug-flags");
  6331. CmdArgs.push_back(Args.MakeArgString(Flags));
  6332. }
  6333. // FIXME: Add -static support, once we have it.
  6334. // Add target specific flags.
  6335. switch (getToolChain().getArch()) {
  6336. default:
  6337. break;
  6338. case llvm::Triple::mips:
  6339. case llvm::Triple::mipsel:
  6340. case llvm::Triple::mips64:
  6341. case llvm::Triple::mips64el:
  6342. AddMIPSTargetArgs(Args, CmdArgs);
  6343. break;
  6344. case llvm::Triple::x86:
  6345. case llvm::Triple::x86_64:
  6346. AddX86TargetArgs(Args, CmdArgs);
  6347. break;
  6348. }
  6349. // Consume all the warning flags. Usually this would be handled more
  6350. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  6351. // doesn't handle that so rather than warning about unused flags that are
  6352. // actually used, we'll lie by omission instead.
  6353. // FIXME: Stop lying and consume only the appropriate driver flags
  6354. Args.ClaimAllArgs(options::OPT_W_Group);
  6355. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  6356. getToolChain().getDriver());
  6357. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  6358. assert(Output.isFilename() && "Unexpected lipo output.");
  6359. CmdArgs.push_back("-o");
  6360. CmdArgs.push_back(Output.getFilename());
  6361. assert(Input.isFilename() && "Invalid input.");
  6362. CmdArgs.push_back(Input.getFilename());
  6363. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  6364. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6365. // Handle the debug info splitting at object creation time if we're
  6366. // creating an object.
  6367. // TODO: Currently only works on linux with newer objcopy.
  6368. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  6369. getToolChain().getTriple().isOSLinux())
  6370. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  6371. SplitDebugName(Args, Input));
  6372. }
  6373. void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
  6374. const InputInfo &Output,
  6375. const InputInfoList &Inputs,
  6376. const llvm::opt::ArgList &TCArgs,
  6377. const char *LinkingOutput) const {
  6378. // The version with only one output is expected to refer to a bundling job.
  6379. assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
  6380. // The bundling command looks like this:
  6381. // clang-offload-bundler -type=bc
  6382. // -targets=host-triple,openmp-triple1,openmp-triple2
  6383. // -outputs=input_file
  6384. // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
  6385. ArgStringList CmdArgs;
  6386. // Get the type.
  6387. CmdArgs.push_back(TCArgs.MakeArgString(
  6388. Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
  6389. assert(JA.getInputs().size() == Inputs.size() &&
  6390. "Not have inputs for all dependence actions??");
  6391. // Get the targets.
  6392. SmallString<128> Triples;
  6393. Triples += "-targets=";
  6394. for (unsigned I = 0; I < Inputs.size(); ++I) {
  6395. if (I)
  6396. Triples += ',';
  6397. Action::OffloadKind CurKind = Action::OFK_Host;
  6398. const ToolChain *CurTC = &getToolChain();
  6399. const Action *CurDep = JA.getInputs()[I];
  6400. if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
  6401. OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
  6402. CurKind = A->getOffloadingDeviceKind();
  6403. CurTC = TC;
  6404. });
  6405. }
  6406. Triples += Action::GetOffloadKindName(CurKind);
  6407. Triples += '-';
  6408. Triples += CurTC->getTriple().normalize();
  6409. }
  6410. CmdArgs.push_back(TCArgs.MakeArgString(Triples));
  6411. // Get bundled file command.
  6412. CmdArgs.push_back(
  6413. TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
  6414. // Get unbundled files command.
  6415. SmallString<128> UB;
  6416. UB += "-inputs=";
  6417. for (unsigned I = 0; I < Inputs.size(); ++I) {
  6418. if (I)
  6419. UB += ',';
  6420. UB += Inputs[I].getFilename();
  6421. }
  6422. CmdArgs.push_back(TCArgs.MakeArgString(UB));
  6423. // All the inputs are encoded as commands.
  6424. C.addCommand(llvm::make_unique<Command>(
  6425. JA, *this,
  6426. TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
  6427. CmdArgs, None));
  6428. }
  6429. void OffloadBundler::ConstructJobMultipleOutputs(
  6430. Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
  6431. const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
  6432. const char *LinkingOutput) const {
  6433. // The version with multiple outputs is expected to refer to a unbundling job.
  6434. auto &UA = cast<OffloadUnbundlingJobAction>(JA);
  6435. // The unbundling command looks like this:
  6436. // clang-offload-bundler -type=bc
  6437. // -targets=host-triple,openmp-triple1,openmp-triple2
  6438. // -inputs=input_file
  6439. // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
  6440. // -unbundle
  6441. ArgStringList CmdArgs;
  6442. assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
  6443. InputInfo Input = Inputs.front();
  6444. // Get the type.
  6445. CmdArgs.push_back(TCArgs.MakeArgString(
  6446. Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
  6447. // Get the targets.
  6448. SmallString<128> Triples;
  6449. Triples += "-targets=";
  6450. auto DepInfo = UA.getDependentActionsInfo();
  6451. for (unsigned I = 0; I < DepInfo.size(); ++I) {
  6452. if (I)
  6453. Triples += ',';
  6454. auto &Dep = DepInfo[I];
  6455. Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
  6456. Triples += '-';
  6457. Triples += Dep.DependentToolChain->getTriple().normalize();
  6458. }
  6459. CmdArgs.push_back(TCArgs.MakeArgString(Triples));
  6460. // Get bundled file command.
  6461. CmdArgs.push_back(
  6462. TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
  6463. // Get unbundled files command.
  6464. SmallString<128> UB;
  6465. UB += "-outputs=";
  6466. for (unsigned I = 0; I < Outputs.size(); ++I) {
  6467. if (I)
  6468. UB += ',';
  6469. UB += Outputs[I].getFilename();
  6470. }
  6471. CmdArgs.push_back(TCArgs.MakeArgString(UB));
  6472. CmdArgs.push_back("-unbundle");
  6473. // All the inputs are encoded as commands.
  6474. C.addCommand(llvm::make_unique<Command>(
  6475. JA, *this,
  6476. TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
  6477. CmdArgs, None));
  6478. }
  6479. void GnuTool::anchor() {}
  6480. void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  6481. const InputInfo &Output,
  6482. const InputInfoList &Inputs, const ArgList &Args,
  6483. const char *LinkingOutput) const {
  6484. const Driver &D = getToolChain().getDriver();
  6485. ArgStringList CmdArgs;
  6486. for (const auto &A : Args) {
  6487. if (forwardToGCC(A->getOption())) {
  6488. // It is unfortunate that we have to claim here, as this means
  6489. // we will basically never report anything interesting for
  6490. // platforms using a generic gcc, even if we are just using gcc
  6491. // to get to the assembler.
  6492. A->claim();
  6493. // Don't forward any -g arguments to assembly steps.
  6494. if (isa<AssembleJobAction>(JA) &&
  6495. A->getOption().matches(options::OPT_g_Group))
  6496. continue;
  6497. // Don't forward any -W arguments to assembly and link steps.
  6498. if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
  6499. A->getOption().matches(options::OPT_W_Group))
  6500. continue;
  6501. A->render(Args, CmdArgs);
  6502. }
  6503. }
  6504. RenderExtraToolArgs(JA, CmdArgs);
  6505. // If using a driver driver, force the arch.
  6506. if (getToolChain().getTriple().isOSDarwin()) {
  6507. CmdArgs.push_back("-arch");
  6508. CmdArgs.push_back(
  6509. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  6510. }
  6511. // Try to force gcc to match the tool chain we want, if we recognize
  6512. // the arch.
  6513. //
  6514. // FIXME: The triple class should directly provide the information we want
  6515. // here.
  6516. switch (getToolChain().getArch()) {
  6517. default:
  6518. break;
  6519. case llvm::Triple::x86:
  6520. case llvm::Triple::ppc:
  6521. CmdArgs.push_back("-m32");
  6522. break;
  6523. case llvm::Triple::x86_64:
  6524. case llvm::Triple::ppc64:
  6525. case llvm::Triple::ppc64le:
  6526. CmdArgs.push_back("-m64");
  6527. break;
  6528. case llvm::Triple::sparcel:
  6529. CmdArgs.push_back("-EL");
  6530. break;
  6531. }
  6532. if (Output.isFilename()) {
  6533. CmdArgs.push_back("-o");
  6534. CmdArgs.push_back(Output.getFilename());
  6535. } else {
  6536. assert(Output.isNothing() && "Unexpected output");
  6537. CmdArgs.push_back("-fsyntax-only");
  6538. }
  6539. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6540. // Only pass -x if gcc will understand it; otherwise hope gcc
  6541. // understands the suffix correctly. The main use case this would go
  6542. // wrong in is for linker inputs if they happened to have an odd
  6543. // suffix; really the only way to get this to happen is a command
  6544. // like '-x foobar a.c' which will treat a.c like a linker input.
  6545. //
  6546. // FIXME: For the linker case specifically, can we safely convert
  6547. // inputs into '-Wl,' options?
  6548. for (const auto &II : Inputs) {
  6549. // Don't try to pass LLVM or AST inputs to a generic gcc.
  6550. if (types::isLLVMIR(II.getType()))
  6551. D.Diag(diag::err_drv_no_linker_llvm_support)
  6552. << getToolChain().getTripleString();
  6553. else if (II.getType() == types::TY_AST)
  6554. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  6555. else if (II.getType() == types::TY_ModuleFile)
  6556. D.Diag(diag::err_drv_no_module_support)
  6557. << getToolChain().getTripleString();
  6558. if (types::canTypeBeUserSpecified(II.getType())) {
  6559. CmdArgs.push_back("-x");
  6560. CmdArgs.push_back(types::getTypeName(II.getType()));
  6561. }
  6562. if (II.isFilename())
  6563. CmdArgs.push_back(II.getFilename());
  6564. else {
  6565. const Arg &A = II.getInputArg();
  6566. // Reverse translate some rewritten options.
  6567. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  6568. CmdArgs.push_back("-lstdc++");
  6569. continue;
  6570. }
  6571. // Don't render as input, we need gcc to do the translations.
  6572. A.render(Args, CmdArgs);
  6573. }
  6574. }
  6575. const std::string &customGCCName = D.getCCCGenericGCCName();
  6576. const char *GCCName;
  6577. if (!customGCCName.empty())
  6578. GCCName = customGCCName.c_str();
  6579. else if (D.CCCIsCXX()) {
  6580. GCCName = "g++";
  6581. } else
  6582. GCCName = "gcc";
  6583. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  6584. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6585. }
  6586. void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
  6587. ArgStringList &CmdArgs) const {
  6588. CmdArgs.push_back("-E");
  6589. }
  6590. void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  6591. ArgStringList &CmdArgs) const {
  6592. const Driver &D = getToolChain().getDriver();
  6593. switch (JA.getType()) {
  6594. // If -flto, etc. are present then make sure not to force assembly output.
  6595. case types::TY_LLVM_IR:
  6596. case types::TY_LTO_IR:
  6597. case types::TY_LLVM_BC:
  6598. case types::TY_LTO_BC:
  6599. CmdArgs.push_back("-c");
  6600. break;
  6601. // We assume we've got an "integrated" assembler in that gcc will produce an
  6602. // object file itself.
  6603. case types::TY_Object:
  6604. CmdArgs.push_back("-c");
  6605. break;
  6606. case types::TY_PP_Asm:
  6607. CmdArgs.push_back("-S");
  6608. break;
  6609. case types::TY_Nothing:
  6610. CmdArgs.push_back("-fsyntax-only");
  6611. break;
  6612. default:
  6613. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  6614. }
  6615. }
  6616. void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  6617. ArgStringList &CmdArgs) const {
  6618. // The types are (hopefully) good enough.
  6619. }
  6620. // Hexagon tools start.
  6621. void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
  6622. ArgStringList &CmdArgs) const {
  6623. }
  6624. void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6625. const InputInfo &Output,
  6626. const InputInfoList &Inputs,
  6627. const ArgList &Args,
  6628. const char *LinkingOutput) const {
  6629. claimNoWarnArgs(Args);
  6630. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  6631. const Driver &D = HTC.getDriver();
  6632. ArgStringList CmdArgs;
  6633. std::string MArchString = "-march=hexagon";
  6634. CmdArgs.push_back(Args.MakeArgString(MArchString));
  6635. RenderExtraToolArgs(JA, CmdArgs);
  6636. std::string AsName = "hexagon-llvm-mc";
  6637. std::string MCpuString = "-mcpu=hexagon" +
  6638. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  6639. CmdArgs.push_back("-filetype=obj");
  6640. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  6641. if (Output.isFilename()) {
  6642. CmdArgs.push_back("-o");
  6643. CmdArgs.push_back(Output.getFilename());
  6644. } else {
  6645. assert(Output.isNothing() && "Unexpected output");
  6646. CmdArgs.push_back("-fsyntax-only");
  6647. }
  6648. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  6649. std::string N = llvm::utostr(G.getValue());
  6650. CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
  6651. }
  6652. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6653. // Only pass -x if gcc will understand it; otherwise hope gcc
  6654. // understands the suffix correctly. The main use case this would go
  6655. // wrong in is for linker inputs if they happened to have an odd
  6656. // suffix; really the only way to get this to happen is a command
  6657. // like '-x foobar a.c' which will treat a.c like a linker input.
  6658. //
  6659. // FIXME: For the linker case specifically, can we safely convert
  6660. // inputs into '-Wl,' options?
  6661. for (const auto &II : Inputs) {
  6662. // Don't try to pass LLVM or AST inputs to a generic gcc.
  6663. if (types::isLLVMIR(II.getType()))
  6664. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  6665. << HTC.getTripleString();
  6666. else if (II.getType() == types::TY_AST)
  6667. D.Diag(clang::diag::err_drv_no_ast_support)
  6668. << HTC.getTripleString();
  6669. else if (II.getType() == types::TY_ModuleFile)
  6670. D.Diag(diag::err_drv_no_module_support)
  6671. << HTC.getTripleString();
  6672. if (II.isFilename())
  6673. CmdArgs.push_back(II.getFilename());
  6674. else
  6675. // Don't render as input, we need gcc to do the translations.
  6676. // FIXME: What is this?
  6677. II.getInputArg().render(Args, CmdArgs);
  6678. }
  6679. auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
  6680. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6681. }
  6682. void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
  6683. ArgStringList &CmdArgs) const {
  6684. }
  6685. static void
  6686. constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
  6687. const toolchains::HexagonToolChain &HTC,
  6688. const InputInfo &Output, const InputInfoList &Inputs,
  6689. const ArgList &Args, ArgStringList &CmdArgs,
  6690. const char *LinkingOutput) {
  6691. const Driver &D = HTC.getDriver();
  6692. //----------------------------------------------------------------------------
  6693. //
  6694. //----------------------------------------------------------------------------
  6695. bool IsStatic = Args.hasArg(options::OPT_static);
  6696. bool IsShared = Args.hasArg(options::OPT_shared);
  6697. bool IsPIE = Args.hasArg(options::OPT_pie);
  6698. bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
  6699. bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
  6700. bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
  6701. bool UseG0 = false;
  6702. bool UseShared = IsShared && !IsStatic;
  6703. //----------------------------------------------------------------------------
  6704. // Silence warnings for various options
  6705. //----------------------------------------------------------------------------
  6706. Args.ClaimAllArgs(options::OPT_g_Group);
  6707. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6708. Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
  6709. // handled somewhere else.
  6710. Args.ClaimAllArgs(options::OPT_static_libgcc);
  6711. //----------------------------------------------------------------------------
  6712. //
  6713. //----------------------------------------------------------------------------
  6714. if (Args.hasArg(options::OPT_s))
  6715. CmdArgs.push_back("-s");
  6716. if (Args.hasArg(options::OPT_r))
  6717. CmdArgs.push_back("-r");
  6718. for (const auto &Opt : HTC.ExtraOpts)
  6719. CmdArgs.push_back(Opt.c_str());
  6720. CmdArgs.push_back("-march=hexagon");
  6721. std::string CpuVer =
  6722. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  6723. std::string MCpuString = "-mcpu=hexagon" + CpuVer;
  6724. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  6725. if (IsShared) {
  6726. CmdArgs.push_back("-shared");
  6727. // The following should be the default, but doing as hexagon-gcc does.
  6728. CmdArgs.push_back("-call_shared");
  6729. }
  6730. if (IsStatic)
  6731. CmdArgs.push_back("-static");
  6732. if (IsPIE && !IsShared)
  6733. CmdArgs.push_back("-pie");
  6734. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  6735. std::string N = llvm::utostr(G.getValue());
  6736. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
  6737. UseG0 = G.getValue() == 0;
  6738. }
  6739. //----------------------------------------------------------------------------
  6740. //
  6741. //----------------------------------------------------------------------------
  6742. CmdArgs.push_back("-o");
  6743. CmdArgs.push_back(Output.getFilename());
  6744. //----------------------------------------------------------------------------
  6745. // moslib
  6746. //----------------------------------------------------------------------------
  6747. std::vector<std::string> OsLibs;
  6748. bool HasStandalone = false;
  6749. for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
  6750. A->claim();
  6751. OsLibs.emplace_back(A->getValue());
  6752. HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
  6753. }
  6754. if (OsLibs.empty()) {
  6755. OsLibs.push_back("standalone");
  6756. HasStandalone = true;
  6757. }
  6758. //----------------------------------------------------------------------------
  6759. // Start Files
  6760. //----------------------------------------------------------------------------
  6761. const std::string MCpuSuffix = "/" + CpuVer;
  6762. const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
  6763. const std::string RootDir =
  6764. HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
  6765. const std::string StartSubDir =
  6766. "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
  6767. auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
  6768. const char *Name) -> std::string {
  6769. std::string RelName = SubDir + Name;
  6770. std::string P = HTC.GetFilePath(RelName.c_str());
  6771. if (llvm::sys::fs::exists(P))
  6772. return P;
  6773. return RootDir + RelName;
  6774. };
  6775. if (IncStdLib && IncStartFiles) {
  6776. if (!IsShared) {
  6777. if (HasStandalone) {
  6778. std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
  6779. CmdArgs.push_back(Args.MakeArgString(Crt0SA));
  6780. }
  6781. std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
  6782. CmdArgs.push_back(Args.MakeArgString(Crt0));
  6783. }
  6784. std::string Init = UseShared
  6785. ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
  6786. : Find(RootDir, StartSubDir, "/init.o");
  6787. CmdArgs.push_back(Args.MakeArgString(Init));
  6788. }
  6789. //----------------------------------------------------------------------------
  6790. // Library Search Paths
  6791. //----------------------------------------------------------------------------
  6792. const ToolChain::path_list &LibPaths = HTC.getFilePaths();
  6793. for (const auto &LibPath : LibPaths)
  6794. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  6795. //----------------------------------------------------------------------------
  6796. //
  6797. //----------------------------------------------------------------------------
  6798. Args.AddAllArgs(CmdArgs,
  6799. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  6800. options::OPT_t, options::OPT_u_Group});
  6801. AddLinkerInputs(HTC, Inputs, Args, CmdArgs, JA);
  6802. //----------------------------------------------------------------------------
  6803. // Libraries
  6804. //----------------------------------------------------------------------------
  6805. if (IncStdLib && IncDefLibs) {
  6806. if (D.CCCIsCXX()) {
  6807. HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
  6808. CmdArgs.push_back("-lm");
  6809. }
  6810. CmdArgs.push_back("--start-group");
  6811. if (!IsShared) {
  6812. for (const std::string &Lib : OsLibs)
  6813. CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
  6814. CmdArgs.push_back("-lc");
  6815. }
  6816. CmdArgs.push_back("-lgcc");
  6817. CmdArgs.push_back("--end-group");
  6818. }
  6819. //----------------------------------------------------------------------------
  6820. // End files
  6821. //----------------------------------------------------------------------------
  6822. if (IncStdLib && IncStartFiles) {
  6823. std::string Fini = UseShared
  6824. ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
  6825. : Find(RootDir, StartSubDir, "/fini.o");
  6826. CmdArgs.push_back(Args.MakeArgString(Fini));
  6827. }
  6828. }
  6829. void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6830. const InputInfo &Output,
  6831. const InputInfoList &Inputs,
  6832. const ArgList &Args,
  6833. const char *LinkingOutput) const {
  6834. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  6835. ArgStringList CmdArgs;
  6836. constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
  6837. LinkingOutput);
  6838. std::string Linker = HTC.GetProgramPath("hexagon-link");
  6839. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  6840. CmdArgs, Inputs));
  6841. }
  6842. // Hexagon tools end.
  6843. void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6844. const InputInfo &Output,
  6845. const InputInfoList &Inputs,
  6846. const ArgList &Args,
  6847. const char *LinkingOutput) const {
  6848. std::string Linker = getToolChain().GetProgramPath(getShortName());
  6849. ArgStringList CmdArgs;
  6850. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  6851. CmdArgs.push_back("-shared");
  6852. CmdArgs.push_back("-o");
  6853. CmdArgs.push_back(Output.getFilename());
  6854. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  6855. CmdArgs, Inputs));
  6856. }
  6857. // AMDGPU tools end.
  6858. wasm::Linker::Linker(const ToolChain &TC)
  6859. : GnuTool("wasm::Linker", "lld", TC) {}
  6860. bool wasm::Linker::isLinkJob() const {
  6861. return true;
  6862. }
  6863. bool wasm::Linker::hasIntegratedCPP() const {
  6864. return false;
  6865. }
  6866. void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6867. const InputInfo &Output,
  6868. const InputInfoList &Inputs,
  6869. const ArgList &Args,
  6870. const char *LinkingOutput) const {
  6871. const ToolChain &ToolChain = getToolChain();
  6872. const Driver &D = ToolChain.getDriver();
  6873. const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
  6874. ArgStringList CmdArgs;
  6875. CmdArgs.push_back("-flavor");
  6876. CmdArgs.push_back("ld");
  6877. // Enable garbage collection of unused input sections by default, since code
  6878. // size is of particular importance. This is significantly facilitated by
  6879. // the enabling of -ffunction-sections and -fdata-sections in
  6880. // Clang::ConstructJob.
  6881. if (areOptimizationsEnabled(Args))
  6882. CmdArgs.push_back("--gc-sections");
  6883. if (Args.hasArg(options::OPT_rdynamic))
  6884. CmdArgs.push_back("-export-dynamic");
  6885. if (Args.hasArg(options::OPT_s))
  6886. CmdArgs.push_back("--strip-all");
  6887. if (Args.hasArg(options::OPT_shared))
  6888. CmdArgs.push_back("-shared");
  6889. if (Args.hasArg(options::OPT_static))
  6890. CmdArgs.push_back("-Bstatic");
  6891. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6892. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6893. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6894. if (Args.hasArg(options::OPT_shared))
  6895. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
  6896. else if (Args.hasArg(options::OPT_pie))
  6897. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
  6898. else
  6899. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  6900. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  6901. }
  6902. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  6903. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6904. if (D.CCCIsCXX())
  6905. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6906. if (Args.hasArg(options::OPT_pthread))
  6907. CmdArgs.push_back("-lpthread");
  6908. CmdArgs.push_back("-lc");
  6909. CmdArgs.push_back("-lcompiler_rt");
  6910. }
  6911. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6912. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  6913. CmdArgs.push_back("-o");
  6914. CmdArgs.push_back(Output.getFilename());
  6915. C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
  6916. }
  6917. const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  6918. std::string MArch;
  6919. if (!Arch.empty())
  6920. MArch = Arch;
  6921. else
  6922. MArch = Triple.getArchName();
  6923. MArch = StringRef(MArch).split("+").first.lower();
  6924. // Handle -march=native.
  6925. if (MArch == "native") {
  6926. std::string CPU = llvm::sys::getHostCPUName();
  6927. if (CPU != "generic") {
  6928. // Translate the native cpu into the architecture suffix for that CPU.
  6929. StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  6930. // If there is no valid architecture suffix for this CPU we don't know how
  6931. // to handle it, so return no architecture.
  6932. if (Suffix.empty())
  6933. MArch = "";
  6934. else
  6935. MArch = std::string("arm") + Suffix.str();
  6936. }
  6937. }
  6938. return MArch;
  6939. }
  6940. /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
  6941. StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  6942. std::string MArch = getARMArch(Arch, Triple);
  6943. // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  6944. // here means an -march=native that we can't handle, so instead return no CPU.
  6945. if (MArch.empty())
  6946. return StringRef();
  6947. // We need to return an empty string here on invalid MArch values as the
  6948. // various places that call this function can't cope with a null result.
  6949. return Triple.getARMCPUForArch(MArch);
  6950. }
  6951. /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
  6952. std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
  6953. const llvm::Triple &Triple) {
  6954. // FIXME: Warn on inconsistent use of -mcpu and -march.
  6955. // If we have -mcpu=, use that.
  6956. if (!CPU.empty()) {
  6957. std::string MCPU = StringRef(CPU).split("+").first.lower();
  6958. // Handle -mcpu=native.
  6959. if (MCPU == "native")
  6960. return llvm::sys::getHostCPUName();
  6961. else
  6962. return MCPU;
  6963. }
  6964. return getARMCPUForMArch(Arch, Triple);
  6965. }
  6966. /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
  6967. /// CPU (or Arch, if CPU is generic).
  6968. // FIXME: This is redundant with -mcpu, why does LLVM use this.
  6969. StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
  6970. const llvm::Triple &Triple) {
  6971. unsigned ArchKind;
  6972. if (CPU == "generic") {
  6973. std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
  6974. ArchKind = llvm::ARM::parseArch(ARMArch);
  6975. if (ArchKind == llvm::ARM::AK_INVALID)
  6976. // In case of generic Arch, i.e. "arm",
  6977. // extract arch from default cpu of the Triple
  6978. ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  6979. } else {
  6980. // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
  6981. // armv7k triple if it's actually been specified via "-arch armv7k".
  6982. ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
  6983. ? (unsigned)llvm::ARM::AK_ARMV7K
  6984. : llvm::ARM::parseCPUArch(CPU);
  6985. }
  6986. if (ArchKind == llvm::ARM::AK_INVALID)
  6987. return "";
  6988. return llvm::ARM::getSubArch(ArchKind);
  6989. }
  6990. void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
  6991. const llvm::Triple &Triple) {
  6992. if (Args.hasArg(options::OPT_r))
  6993. return;
  6994. // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  6995. // to generate BE-8 executables.
  6996. if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
  6997. CmdArgs.push_back("--be8");
  6998. }
  6999. mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
  7000. // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
  7001. // was first introduced in Release 3. However, other compilers have
  7002. // traditionally allowed it for Release 2 so we should do the same.
  7003. return (NanEncoding)llvm::StringSwitch<int>(CPU)
  7004. .Case("mips1", NanLegacy)
  7005. .Case("mips2", NanLegacy)
  7006. .Case("mips3", NanLegacy)
  7007. .Case("mips4", NanLegacy)
  7008. .Case("mips5", NanLegacy)
  7009. .Case("mips32", NanLegacy)
  7010. .Case("mips32r2", NanLegacy | Nan2008)
  7011. .Case("mips32r3", NanLegacy | Nan2008)
  7012. .Case("mips32r5", NanLegacy | Nan2008)
  7013. .Case("mips32r6", Nan2008)
  7014. .Case("mips64", NanLegacy)
  7015. .Case("mips64r2", NanLegacy | Nan2008)
  7016. .Case("mips64r3", NanLegacy | Nan2008)
  7017. .Case("mips64r5", NanLegacy | Nan2008)
  7018. .Case("mips64r6", Nan2008)
  7019. .Default(NanLegacy);
  7020. }
  7021. bool mips::hasCompactBranches(StringRef &CPU) {
  7022. // mips32r6 and mips64r6 have compact branches.
  7023. return llvm::StringSwitch<bool>(CPU)
  7024. .Case("mips32r6", true)
  7025. .Case("mips64r6", true)
  7026. .Default(false);
  7027. }
  7028. bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
  7029. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  7030. return A && (A->getValue() == StringRef(Value));
  7031. }
  7032. bool mips::isUCLibc(const ArgList &Args) {
  7033. Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
  7034. return A && A->getOption().matches(options::OPT_muclibc);
  7035. }
  7036. bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
  7037. if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
  7038. return llvm::StringSwitch<bool>(NaNArg->getValue())
  7039. .Case("2008", true)
  7040. .Case("legacy", false)
  7041. .Default(false);
  7042. // NaN2008 is the default for MIPS32r6/MIPS64r6.
  7043. return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
  7044. .Cases("mips32r6", "mips64r6", true)
  7045. .Default(false);
  7046. return false;
  7047. }
  7048. bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
  7049. if (!Triple.isAndroid())
  7050. return false;
  7051. // Android MIPS32R6 defaults to FP64A.
  7052. return llvm::StringSwitch<bool>(CPUName)
  7053. .Case("mips32r6", true)
  7054. .Default(false);
  7055. }
  7056. bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
  7057. StringRef ABIName, mips::FloatABI FloatABI) {
  7058. if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
  7059. Triple.getVendor() != llvm::Triple::MipsTechnologies &&
  7060. !Triple.isAndroid())
  7061. return false;
  7062. if (ABIName != "32")
  7063. return false;
  7064. // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
  7065. // present.
  7066. if (FloatABI == mips::FloatABI::Soft)
  7067. return false;
  7068. return llvm::StringSwitch<bool>(CPUName)
  7069. .Cases("mips2", "mips3", "mips4", "mips5", true)
  7070. .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
  7071. .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
  7072. .Default(false);
  7073. }
  7074. bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
  7075. StringRef CPUName, StringRef ABIName,
  7076. mips::FloatABI FloatABI) {
  7077. bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
  7078. // FPXX shouldn't be used if -msingle-float is present.
  7079. if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
  7080. options::OPT_mdouble_float))
  7081. if (A->getOption().matches(options::OPT_msingle_float))
  7082. UseFPXX = false;
  7083. return UseFPXX;
  7084. }
  7085. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  7086. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  7087. // archs which Darwin doesn't use.
  7088. // The matching this routine does is fairly pointless, since it is neither the
  7089. // complete architecture list, nor a reasonable subset. The problem is that
  7090. // historically the driver driver accepts this and also ties its -march=
  7091. // handling to the architecture name, so we need to be careful before removing
  7092. // support for it.
  7093. // This code must be kept in sync with Clang's Darwin specific argument
  7094. // translation.
  7095. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  7096. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  7097. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  7098. .Case("ppc64", llvm::Triple::ppc64)
  7099. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  7100. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  7101. llvm::Triple::x86)
  7102. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  7103. // This is derived from the driver driver.
  7104. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  7105. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  7106. .Cases("armv7s", "xscale", llvm::Triple::arm)
  7107. .Case("arm64", llvm::Triple::aarch64)
  7108. .Case("r600", llvm::Triple::r600)
  7109. .Case("amdgcn", llvm::Triple::amdgcn)
  7110. .Case("nvptx", llvm::Triple::nvptx)
  7111. .Case("nvptx64", llvm::Triple::nvptx64)
  7112. .Case("amdil", llvm::Triple::amdil)
  7113. .Case("spir", llvm::Triple::spir)
  7114. .Default(llvm::Triple::UnknownArch);
  7115. }
  7116. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  7117. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  7118. unsigned ArchKind = llvm::ARM::parseArch(Str);
  7119. T.setArch(Arch);
  7120. if (Str == "x86_64h")
  7121. T.setArchName(Str);
  7122. else if (ArchKind == llvm::ARM::AK_ARMV6M ||
  7123. ArchKind == llvm::ARM::AK_ARMV7M ||
  7124. ArchKind == llvm::ARM::AK_ARMV7EM) {
  7125. T.setOS(llvm::Triple::UnknownOS);
  7126. T.setObjectFormat(llvm::Triple::MachO);
  7127. }
  7128. }
  7129. const char *Clang::getBaseInputName(const ArgList &Args,
  7130. const InputInfo &Input) {
  7131. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  7132. }
  7133. const char *Clang::getBaseInputStem(const ArgList &Args,
  7134. const InputInfoList &Inputs) {
  7135. const char *Str = getBaseInputName(Args, Inputs[0]);
  7136. if (const char *End = strrchr(Str, '.'))
  7137. return Args.MakeArgString(std::string(Str, End));
  7138. return Str;
  7139. }
  7140. const char *Clang::getDependencyFileName(const ArgList &Args,
  7141. const InputInfoList &Inputs) {
  7142. // FIXME: Think about this more.
  7143. std::string Res;
  7144. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  7145. std::string Str(OutputOpt->getValue());
  7146. Res = Str.substr(0, Str.rfind('.'));
  7147. } else {
  7148. Res = getBaseInputStem(Args, Inputs);
  7149. }
  7150. return Args.MakeArgString(Res + ".d");
  7151. }
  7152. void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7153. const InputInfo &Output,
  7154. const InputInfoList &Inputs,
  7155. const ArgList &Args,
  7156. const char *LinkingOutput) const {
  7157. const ToolChain &ToolChain = getToolChain();
  7158. const Driver &D = ToolChain.getDriver();
  7159. ArgStringList CmdArgs;
  7160. // Silence warning for "clang -g foo.o -o foo"
  7161. Args.ClaimAllArgs(options::OPT_g_Group);
  7162. // and "clang -emit-llvm foo.o -o foo"
  7163. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7164. // and for "clang -w foo.o -o foo". Other warning options are already
  7165. // handled somewhere else.
  7166. Args.ClaimAllArgs(options::OPT_w);
  7167. if (!D.SysRoot.empty())
  7168. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7169. // CloudABI only supports static linkage.
  7170. CmdArgs.push_back("-Bstatic");
  7171. CmdArgs.push_back("--no-dynamic-linker");
  7172. // Provide PIE linker flags in case PIE is default for the architecture.
  7173. if (ToolChain.isPIEDefault()) {
  7174. CmdArgs.push_back("-pie");
  7175. CmdArgs.push_back("-zrelro");
  7176. }
  7177. CmdArgs.push_back("--eh-frame-hdr");
  7178. CmdArgs.push_back("--gc-sections");
  7179. if (Output.isFilename()) {
  7180. CmdArgs.push_back("-o");
  7181. CmdArgs.push_back(Output.getFilename());
  7182. } else {
  7183. assert(Output.isNothing() && "Invalid output.");
  7184. }
  7185. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7186. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  7187. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
  7188. }
  7189. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7190. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7191. Args.AddAllArgs(CmdArgs,
  7192. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  7193. options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
  7194. if (D.isUsingLTO())
  7195. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin, D);
  7196. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  7197. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7198. if (D.CCCIsCXX())
  7199. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7200. CmdArgs.push_back("-lc");
  7201. CmdArgs.push_back("-lcompiler_rt");
  7202. }
  7203. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  7204. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  7205. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  7206. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7207. }
  7208. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7209. const InputInfo &Output,
  7210. const InputInfoList &Inputs,
  7211. const ArgList &Args,
  7212. const char *LinkingOutput) const {
  7213. ArgStringList CmdArgs;
  7214. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  7215. const InputInfo &Input = Inputs[0];
  7216. // Determine the original source input.
  7217. const Action *SourceAction = &JA;
  7218. while (SourceAction->getKind() != Action::InputClass) {
  7219. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  7220. SourceAction = SourceAction->getInputs()[0];
  7221. }
  7222. // If -fno-integrated-as is used add -Q to the darwin assember driver to make
  7223. // sure it runs its system assembler not clang's integrated assembler.
  7224. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  7225. // FIXME: at run-time detect assembler capabilities or rely on version
  7226. // information forwarded by -target-assembler-version.
  7227. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  7228. const llvm::Triple &T(getToolChain().getTriple());
  7229. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  7230. CmdArgs.push_back("-Q");
  7231. }
  7232. // Forward -g, assuming we are dealing with an actual assembly file.
  7233. if (SourceAction->getType() == types::TY_Asm ||
  7234. SourceAction->getType() == types::TY_PP_Asm) {
  7235. if (Args.hasArg(options::OPT_gstabs))
  7236. CmdArgs.push_back("--gstabs");
  7237. else if (Args.hasArg(options::OPT_g_Group))
  7238. CmdArgs.push_back("-g");
  7239. }
  7240. // Derived from asm spec.
  7241. AddMachOArch(Args, CmdArgs);
  7242. // Use -force_cpusubtype_ALL on x86 by default.
  7243. if (getToolChain().getArch() == llvm::Triple::x86 ||
  7244. getToolChain().getArch() == llvm::Triple::x86_64 ||
  7245. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  7246. CmdArgs.push_back("-force_cpusubtype_ALL");
  7247. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  7248. (((Args.hasArg(options::OPT_mkernel) ||
  7249. Args.hasArg(options::OPT_fapple_kext)) &&
  7250. getMachOToolChain().isKernelStatic()) ||
  7251. Args.hasArg(options::OPT_static)))
  7252. CmdArgs.push_back("-static");
  7253. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7254. assert(Output.isFilename() && "Unexpected lipo output.");
  7255. CmdArgs.push_back("-o");
  7256. CmdArgs.push_back(Output.getFilename());
  7257. assert(Input.isFilename() && "Invalid input.");
  7258. CmdArgs.push_back(Input.getFilename());
  7259. // asm_final spec is empty.
  7260. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7261. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7262. }
  7263. void darwin::MachOTool::anchor() {}
  7264. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  7265. ArgStringList &CmdArgs) const {
  7266. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  7267. // Derived from darwin_arch spec.
  7268. CmdArgs.push_back("-arch");
  7269. CmdArgs.push_back(Args.MakeArgString(ArchName));
  7270. // FIXME: Is this needed anymore?
  7271. if (ArchName == "arm")
  7272. CmdArgs.push_back("-force_cpusubtype_ALL");
  7273. }
  7274. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  7275. // We only need to generate a temp path for LTO if we aren't compiling object
  7276. // files. When compiling source files, we run 'dsymutil' after linking. We
  7277. // don't run 'dsymutil' when compiling object files.
  7278. for (const auto &Input : Inputs)
  7279. if (Input.getType() != types::TY_Object)
  7280. return true;
  7281. return false;
  7282. }
  7283. /// \brief Pass -no_deduplicate to ld64 under certain conditions:
  7284. ///
  7285. /// - Either -O0 or -O1 is explicitly specified
  7286. /// - No -O option is specified *and* this is a compile+link (implicit -O0)
  7287. ///
  7288. /// Also do *not* add -no_deduplicate when no -O option is specified and this
  7289. /// is just a link (we can't imply -O0)
  7290. static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
  7291. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  7292. if (A->getOption().matches(options::OPT_O0))
  7293. return true;
  7294. if (A->getOption().matches(options::OPT_O))
  7295. return llvm::StringSwitch<bool>(A->getValue())
  7296. .Case("1", true)
  7297. .Default(false);
  7298. return false; // OPT_Ofast & OPT_O4
  7299. }
  7300. if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
  7301. return true;
  7302. return false;
  7303. }
  7304. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  7305. ArgStringList &CmdArgs,
  7306. const InputInfoList &Inputs) const {
  7307. const Driver &D = getToolChain().getDriver();
  7308. const toolchains::MachO &MachOTC = getMachOToolChain();
  7309. unsigned Version[5] = {0, 0, 0, 0, 0};
  7310. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  7311. if (!Driver::GetReleaseVersion(A->getValue(), Version))
  7312. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  7313. }
  7314. // Newer linkers support -demangle. Pass it if supported and not disabled by
  7315. // the user.
  7316. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  7317. CmdArgs.push_back("-demangle");
  7318. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  7319. CmdArgs.push_back("-export_dynamic");
  7320. // If we are using App Extension restrictions, pass a flag to the linker
  7321. // telling it that the compiled code has been audited.
  7322. if (Args.hasFlag(options::OPT_fapplication_extension,
  7323. options::OPT_fno_application_extension, false))
  7324. CmdArgs.push_back("-application_extension");
  7325. if (D.isUsingLTO()) {
  7326. // If we are using LTO, then automatically create a temporary file path for
  7327. // the linker to use, so that it's lifetime will extend past a possible
  7328. // dsymutil step.
  7329. if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
  7330. const char *TmpPath = C.getArgs().MakeArgString(
  7331. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
  7332. C.addTempFile(TmpPath);
  7333. CmdArgs.push_back("-object_path_lto");
  7334. CmdArgs.push_back(TmpPath);
  7335. }
  7336. }
  7337. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  7338. // it in clang installed libraries. ld64 will only look at this argument
  7339. // when it actually uses LTO, so libLTO.dylib only needs to exist at link
  7340. // time if ld64 decides that it needs to use LTO.
  7341. // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
  7342. // next to it. That's ok since ld64 using a libLTO.dylib not matching the
  7343. // clang version won't work anyways.
  7344. if (Version[0] >= 133) {
  7345. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  7346. StringRef P = llvm::sys::path::parent_path(D.Dir);
  7347. SmallString<128> LibLTOPath(P);
  7348. llvm::sys::path::append(LibLTOPath, "lib");
  7349. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  7350. CmdArgs.push_back("-lto_library");
  7351. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  7352. }
  7353. // ld64 version 262 and above run the deduplicate pass by default.
  7354. if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args))
  7355. CmdArgs.push_back("-no_deduplicate");
  7356. // Derived from the "link" spec.
  7357. Args.AddAllArgs(CmdArgs, options::OPT_static);
  7358. if (!Args.hasArg(options::OPT_static))
  7359. CmdArgs.push_back("-dynamic");
  7360. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  7361. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  7362. // here. How do we wish to handle such things?
  7363. }
  7364. if (!Args.hasArg(options::OPT_dynamiclib)) {
  7365. AddMachOArch(Args, CmdArgs);
  7366. // FIXME: Why do this only on this path?
  7367. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  7368. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  7369. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  7370. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  7371. Arg *A;
  7372. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  7373. (A = Args.getLastArg(options::OPT_current__version)) ||
  7374. (A = Args.getLastArg(options::OPT_install__name)))
  7375. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  7376. << "-dynamiclib";
  7377. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  7378. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  7379. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  7380. } else {
  7381. CmdArgs.push_back("-dylib");
  7382. Arg *A;
  7383. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  7384. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  7385. (A = Args.getLastArg(options::OPT_client__name)) ||
  7386. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  7387. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  7388. (A = Args.getLastArg(options::OPT_private__bundle)))
  7389. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  7390. << "-dynamiclib";
  7391. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  7392. "-dylib_compatibility_version");
  7393. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  7394. "-dylib_current_version");
  7395. AddMachOArch(Args, CmdArgs);
  7396. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  7397. "-dylib_install_name");
  7398. }
  7399. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  7400. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  7401. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  7402. if (MachOTC.isTargetIOSBased())
  7403. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  7404. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  7405. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  7406. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  7407. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  7408. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  7409. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  7410. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  7411. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  7412. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  7413. Args.AddAllArgs(CmdArgs, options::OPT_init);
  7414. // Add the deployment target.
  7415. MachOTC.addMinVersionArgs(Args, CmdArgs);
  7416. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  7417. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  7418. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  7419. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  7420. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  7421. if (const Arg *A =
  7422. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  7423. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  7424. if (A->getOption().matches(options::OPT_fpie) ||
  7425. A->getOption().matches(options::OPT_fPIE))
  7426. CmdArgs.push_back("-pie");
  7427. else
  7428. CmdArgs.push_back("-no_pie");
  7429. }
  7430. // for embed-bitcode, use -bitcode_bundle in linker command
  7431. if (C.getDriver().embedBitcodeEnabled()) {
  7432. // Check if the toolchain supports bitcode build flow.
  7433. if (MachOTC.SupportsEmbeddedBitcode()) {
  7434. CmdArgs.push_back("-bitcode_bundle");
  7435. if (C.getDriver().embedBitcodeMarkerOnly() && Version[0] >= 278) {
  7436. CmdArgs.push_back("-bitcode_process_mode");
  7437. CmdArgs.push_back("marker");
  7438. }
  7439. } else
  7440. D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
  7441. }
  7442. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  7443. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  7444. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  7445. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  7446. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  7447. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  7448. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  7449. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  7450. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  7451. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  7452. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  7453. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  7454. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  7455. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  7456. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  7457. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  7458. // Give --sysroot= preference, over the Apple specific behavior to also use
  7459. // --isysroot as the syslibroot.
  7460. StringRef sysroot = C.getSysRoot();
  7461. if (sysroot != "") {
  7462. CmdArgs.push_back("-syslibroot");
  7463. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  7464. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  7465. CmdArgs.push_back("-syslibroot");
  7466. CmdArgs.push_back(A->getValue());
  7467. }
  7468. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  7469. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  7470. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  7471. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  7472. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  7473. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  7474. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  7475. Args.AddAllArgs(CmdArgs, options::OPT_y);
  7476. Args.AddLastArg(CmdArgs, options::OPT_w);
  7477. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  7478. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  7479. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  7480. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  7481. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  7482. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  7483. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  7484. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  7485. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  7486. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  7487. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  7488. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  7489. }
  7490. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7491. const InputInfo &Output,
  7492. const InputInfoList &Inputs,
  7493. const ArgList &Args,
  7494. const char *LinkingOutput) const {
  7495. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  7496. // If the number of arguments surpasses the system limits, we will encode the
  7497. // input files in a separate file, shortening the command line. To this end,
  7498. // build a list of input file names that can be passed via a file with the
  7499. // -filelist linker option.
  7500. llvm::opt::ArgStringList InputFileList;
  7501. // The logic here is derived from gcc's behavior; most of which
  7502. // comes from specs (starting with link_command). Consult gcc for
  7503. // more information.
  7504. ArgStringList CmdArgs;
  7505. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  7506. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  7507. options::OPT_ccc_arcmt_migrate)) {
  7508. for (const auto &Arg : Args)
  7509. Arg->claim();
  7510. const char *Exec =
  7511. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  7512. CmdArgs.push_back(Output.getFilename());
  7513. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  7514. return;
  7515. }
  7516. // I'm not sure why this particular decomposition exists in gcc, but
  7517. // we follow suite for ease of comparison.
  7518. AddLinkArgs(C, Args, CmdArgs, Inputs);
  7519. // For LTO, pass the name of the optimization record file.
  7520. if (Args.hasFlag(options::OPT_fsave_optimization_record,
  7521. options::OPT_fno_save_optimization_record, false)) {
  7522. CmdArgs.push_back("-mllvm");
  7523. CmdArgs.push_back("-lto-pass-remarks-output");
  7524. CmdArgs.push_back("-mllvm");
  7525. SmallString<128> F;
  7526. F = Output.getFilename();
  7527. F += ".opt.yaml";
  7528. CmdArgs.push_back(Args.MakeArgString(F));
  7529. if (getLastProfileUseArg(Args)) {
  7530. CmdArgs.push_back("-mllvm");
  7531. CmdArgs.push_back("-lto-pass-remarks-with-hotness");
  7532. }
  7533. }
  7534. // It seems that the 'e' option is completely ignored for dynamic executables
  7535. // (the default), and with static executables, the last one wins, as expected.
  7536. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  7537. options::OPT_Z_Flag, options::OPT_u_Group,
  7538. options::OPT_e, options::OPT_r});
  7539. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  7540. // members of static archive libraries which implement Objective-C classes or
  7541. // categories.
  7542. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  7543. CmdArgs.push_back("-ObjC");
  7544. CmdArgs.push_back("-o");
  7545. CmdArgs.push_back(Output.getFilename());
  7546. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  7547. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  7548. // SafeStack requires its own runtime libraries
  7549. // These libraries should be linked first, to make sure the
  7550. // __safestack_init constructor executes before everything else
  7551. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  7552. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
  7553. "libclang_rt.safestack_osx.a",
  7554. /*AlwaysLink=*/true);
  7555. }
  7556. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7557. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  7558. // Build the input file for -filelist (list of linker input files) in case we
  7559. // need it later
  7560. for (const auto &II : Inputs) {
  7561. if (!II.isFilename()) {
  7562. // This is a linker input argument.
  7563. // We cannot mix input arguments and file names in a -filelist input, thus
  7564. // we prematurely stop our list (remaining files shall be passed as
  7565. // arguments).
  7566. if (InputFileList.size() > 0)
  7567. break;
  7568. continue;
  7569. }
  7570. InputFileList.push_back(II.getFilename());
  7571. }
  7572. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  7573. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  7574. if (isObjCRuntimeLinked(Args) &&
  7575. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7576. // We use arclite library for both ARC and subscripting support.
  7577. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  7578. CmdArgs.push_back("-framework");
  7579. CmdArgs.push_back("Foundation");
  7580. // Link libobj.
  7581. CmdArgs.push_back("-lobjc");
  7582. }
  7583. if (LinkingOutput) {
  7584. CmdArgs.push_back("-arch_multiple");
  7585. CmdArgs.push_back("-final_output");
  7586. CmdArgs.push_back(LinkingOutput);
  7587. }
  7588. if (Args.hasArg(options::OPT_fnested_functions))
  7589. CmdArgs.push_back("-allow_stack_execute");
  7590. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  7591. if (unsigned Parallelism =
  7592. getLTOParallelism(Args, getToolChain().getDriver())) {
  7593. CmdArgs.push_back("-mllvm");
  7594. CmdArgs.push_back(
  7595. Args.MakeArgString(Twine("-threads=") + llvm::to_string(Parallelism)));
  7596. }
  7597. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7598. if (getToolChain().getDriver().CCCIsCXX())
  7599. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7600. // link_ssp spec is empty.
  7601. // Let the tool chain choose which runtime library to link.
  7602. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  7603. // No need to do anything for pthreads. Claim argument to avoid warning.
  7604. Args.ClaimAllArgs(options::OPT_pthread);
  7605. Args.ClaimAllArgs(options::OPT_pthreads);
  7606. }
  7607. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7608. // endfile_spec is empty.
  7609. }
  7610. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7611. Args.AddAllArgs(CmdArgs, options::OPT_F);
  7612. // -iframework should be forwarded as -F.
  7613. for (const Arg *A : Args.filtered(options::OPT_iframework))
  7614. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  7615. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7616. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  7617. if (A->getValue() == StringRef("Accelerate")) {
  7618. CmdArgs.push_back("-framework");
  7619. CmdArgs.push_back("Accelerate");
  7620. }
  7621. }
  7622. }
  7623. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7624. std::unique_ptr<Command> Cmd =
  7625. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  7626. Cmd->setInputFileList(std::move(InputFileList));
  7627. C.addCommand(std::move(Cmd));
  7628. }
  7629. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  7630. const InputInfo &Output,
  7631. const InputInfoList &Inputs,
  7632. const ArgList &Args,
  7633. const char *LinkingOutput) const {
  7634. ArgStringList CmdArgs;
  7635. CmdArgs.push_back("-create");
  7636. assert(Output.isFilename() && "Unexpected lipo output.");
  7637. CmdArgs.push_back("-output");
  7638. CmdArgs.push_back(Output.getFilename());
  7639. for (const auto &II : Inputs) {
  7640. assert(II.isFilename() && "Unexpected lipo input.");
  7641. CmdArgs.push_back(II.getFilename());
  7642. }
  7643. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  7644. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7645. }
  7646. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  7647. const InputInfo &Output,
  7648. const InputInfoList &Inputs,
  7649. const ArgList &Args,
  7650. const char *LinkingOutput) const {
  7651. ArgStringList CmdArgs;
  7652. CmdArgs.push_back("-o");
  7653. CmdArgs.push_back(Output.getFilename());
  7654. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  7655. const InputInfo &Input = Inputs[0];
  7656. assert(Input.isFilename() && "Unexpected dsymutil input.");
  7657. CmdArgs.push_back(Input.getFilename());
  7658. const char *Exec =
  7659. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  7660. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7661. }
  7662. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  7663. const InputInfo &Output,
  7664. const InputInfoList &Inputs,
  7665. const ArgList &Args,
  7666. const char *LinkingOutput) const {
  7667. ArgStringList CmdArgs;
  7668. CmdArgs.push_back("--verify");
  7669. CmdArgs.push_back("--debug-info");
  7670. CmdArgs.push_back("--eh-frame");
  7671. CmdArgs.push_back("--quiet");
  7672. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  7673. const InputInfo &Input = Inputs[0];
  7674. assert(Input.isFilename() && "Unexpected verify input");
  7675. // Grabbing the output of the earlier dsymutil run.
  7676. CmdArgs.push_back(Input.getFilename());
  7677. const char *Exec =
  7678. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  7679. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7680. }
  7681. void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7682. const InputInfo &Output,
  7683. const InputInfoList &Inputs,
  7684. const ArgList &Args,
  7685. const char *LinkingOutput) const {
  7686. claimNoWarnArgs(Args);
  7687. ArgStringList CmdArgs;
  7688. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7689. CmdArgs.push_back("-o");
  7690. CmdArgs.push_back(Output.getFilename());
  7691. for (const auto &II : Inputs)
  7692. CmdArgs.push_back(II.getFilename());
  7693. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7694. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7695. }
  7696. void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7697. const InputInfo &Output,
  7698. const InputInfoList &Inputs,
  7699. const ArgList &Args,
  7700. const char *LinkingOutput) const {
  7701. ArgStringList CmdArgs;
  7702. // Demangle C++ names in errors
  7703. CmdArgs.push_back("-C");
  7704. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  7705. CmdArgs.push_back("-e");
  7706. CmdArgs.push_back("_start");
  7707. }
  7708. if (Args.hasArg(options::OPT_static)) {
  7709. CmdArgs.push_back("-Bstatic");
  7710. CmdArgs.push_back("-dn");
  7711. } else {
  7712. CmdArgs.push_back("-Bdynamic");
  7713. if (Args.hasArg(options::OPT_shared)) {
  7714. CmdArgs.push_back("-shared");
  7715. } else {
  7716. CmdArgs.push_back("--dynamic-linker");
  7717. CmdArgs.push_back(
  7718. Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
  7719. }
  7720. }
  7721. if (Output.isFilename()) {
  7722. CmdArgs.push_back("-o");
  7723. CmdArgs.push_back(Output.getFilename());
  7724. } else {
  7725. assert(Output.isNothing() && "Invalid output.");
  7726. }
  7727. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7728. if (!Args.hasArg(options::OPT_shared))
  7729. CmdArgs.push_back(
  7730. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  7731. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7732. CmdArgs.push_back(
  7733. Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
  7734. CmdArgs.push_back(
  7735. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7736. }
  7737. getToolChain().AddFilePathLibArgs(Args, CmdArgs);
  7738. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  7739. options::OPT_e, options::OPT_r});
  7740. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  7741. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7742. if (getToolChain().getDriver().CCCIsCXX())
  7743. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7744. CmdArgs.push_back("-lgcc_s");
  7745. CmdArgs.push_back("-lc");
  7746. if (!Args.hasArg(options::OPT_shared)) {
  7747. CmdArgs.push_back("-lgcc");
  7748. CmdArgs.push_back("-lm");
  7749. }
  7750. }
  7751. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7752. CmdArgs.push_back(
  7753. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7754. }
  7755. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7756. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7757. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7758. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7759. }
  7760. void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7761. const InputInfo &Output,
  7762. const InputInfoList &Inputs,
  7763. const ArgList &Args,
  7764. const char *LinkingOutput) const {
  7765. claimNoWarnArgs(Args);
  7766. ArgStringList CmdArgs;
  7767. switch (getToolChain().getArch()) {
  7768. case llvm::Triple::x86:
  7769. // When building 32-bit code on OpenBSD/amd64, we have to explicitly
  7770. // instruct as in the base system to assemble 32-bit code.
  7771. CmdArgs.push_back("--32");
  7772. break;
  7773. case llvm::Triple::ppc:
  7774. CmdArgs.push_back("-mppc");
  7775. CmdArgs.push_back("-many");
  7776. break;
  7777. case llvm::Triple::sparc:
  7778. case llvm::Triple::sparcel: {
  7779. CmdArgs.push_back("-32");
  7780. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7781. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7782. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7783. break;
  7784. }
  7785. case llvm::Triple::sparcv9: {
  7786. CmdArgs.push_back("-64");
  7787. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7788. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7789. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7790. break;
  7791. }
  7792. case llvm::Triple::mips64:
  7793. case llvm::Triple::mips64el: {
  7794. StringRef CPUName;
  7795. StringRef ABIName;
  7796. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7797. CmdArgs.push_back("-mabi");
  7798. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7799. if (getToolChain().getArch() == llvm::Triple::mips64)
  7800. CmdArgs.push_back("-EB");
  7801. else
  7802. CmdArgs.push_back("-EL");
  7803. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7804. break;
  7805. }
  7806. default:
  7807. break;
  7808. }
  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 openbsd::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. // Silence warning for "clang -g foo.o -o foo"
  7825. Args.ClaimAllArgs(options::OPT_g_Group);
  7826. // and "clang -emit-llvm foo.o -o foo"
  7827. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7828. // and for "clang -w foo.o -o foo". Other warning options are already
  7829. // handled somewhere else.
  7830. Args.ClaimAllArgs(options::OPT_w);
  7831. if (getToolChain().getArch() == llvm::Triple::mips64)
  7832. CmdArgs.push_back("-EB");
  7833. else if (getToolChain().getArch() == llvm::Triple::mips64el)
  7834. CmdArgs.push_back("-EL");
  7835. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  7836. CmdArgs.push_back("-e");
  7837. CmdArgs.push_back("__start");
  7838. }
  7839. if (Args.hasArg(options::OPT_static)) {
  7840. CmdArgs.push_back("-Bstatic");
  7841. } else {
  7842. if (Args.hasArg(options::OPT_rdynamic))
  7843. CmdArgs.push_back("-export-dynamic");
  7844. CmdArgs.push_back("--eh-frame-hdr");
  7845. CmdArgs.push_back("-Bdynamic");
  7846. if (Args.hasArg(options::OPT_shared)) {
  7847. CmdArgs.push_back("-shared");
  7848. } else {
  7849. CmdArgs.push_back("-dynamic-linker");
  7850. CmdArgs.push_back("/usr/libexec/ld.so");
  7851. }
  7852. }
  7853. if (Args.hasArg(options::OPT_nopie))
  7854. CmdArgs.push_back("-nopie");
  7855. if (Output.isFilename()) {
  7856. CmdArgs.push_back("-o");
  7857. CmdArgs.push_back(Output.getFilename());
  7858. } else {
  7859. assert(Output.isNothing() && "Invalid output.");
  7860. }
  7861. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7862. if (!Args.hasArg(options::OPT_shared)) {
  7863. if (Args.hasArg(options::OPT_pg))
  7864. CmdArgs.push_back(
  7865. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  7866. else
  7867. CmdArgs.push_back(
  7868. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7869. CmdArgs.push_back(
  7870. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7871. } else {
  7872. CmdArgs.push_back(
  7873. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7874. }
  7875. }
  7876. std::string Triple = getToolChain().getTripleString();
  7877. if (Triple.substr(0, 6) == "x86_64")
  7878. Triple.replace(0, 6, "amd64");
  7879. CmdArgs.push_back(
  7880. Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
  7881. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  7882. options::OPT_e, options::OPT_s, options::OPT_t,
  7883. options::OPT_Z_Flag, options::OPT_r});
  7884. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  7885. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7886. if (D.CCCIsCXX()) {
  7887. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7888. if (Args.hasArg(options::OPT_pg))
  7889. CmdArgs.push_back("-lm_p");
  7890. else
  7891. CmdArgs.push_back("-lm");
  7892. }
  7893. // FIXME: For some reason GCC passes -lgcc before adding
  7894. // the default system libraries. Just mimic this for now.
  7895. CmdArgs.push_back("-lgcc");
  7896. if (Args.hasArg(options::OPT_pthread)) {
  7897. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  7898. CmdArgs.push_back("-lpthread_p");
  7899. else
  7900. CmdArgs.push_back("-lpthread");
  7901. }
  7902. if (!Args.hasArg(options::OPT_shared)) {
  7903. if (Args.hasArg(options::OPT_pg))
  7904. CmdArgs.push_back("-lc_p");
  7905. else
  7906. CmdArgs.push_back("-lc");
  7907. }
  7908. CmdArgs.push_back("-lgcc");
  7909. }
  7910. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7911. if (!Args.hasArg(options::OPT_shared))
  7912. CmdArgs.push_back(
  7913. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7914. else
  7915. CmdArgs.push_back(
  7916. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7917. }
  7918. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7919. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7920. }
  7921. void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7922. const InputInfo &Output,
  7923. const InputInfoList &Inputs,
  7924. const ArgList &Args,
  7925. const char *LinkingOutput) const {
  7926. claimNoWarnArgs(Args);
  7927. ArgStringList CmdArgs;
  7928. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7929. CmdArgs.push_back("-o");
  7930. CmdArgs.push_back(Output.getFilename());
  7931. for (const auto &II : Inputs)
  7932. CmdArgs.push_back(II.getFilename());
  7933. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7934. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7935. }
  7936. void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7937. const InputInfo &Output,
  7938. const InputInfoList &Inputs,
  7939. const ArgList &Args,
  7940. const char *LinkingOutput) const {
  7941. const Driver &D = getToolChain().getDriver();
  7942. ArgStringList CmdArgs;
  7943. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  7944. CmdArgs.push_back("-e");
  7945. CmdArgs.push_back("__start");
  7946. }
  7947. if (Args.hasArg(options::OPT_static)) {
  7948. CmdArgs.push_back("-Bstatic");
  7949. } else {
  7950. if (Args.hasArg(options::OPT_rdynamic))
  7951. CmdArgs.push_back("-export-dynamic");
  7952. CmdArgs.push_back("--eh-frame-hdr");
  7953. CmdArgs.push_back("-Bdynamic");
  7954. if (Args.hasArg(options::OPT_shared)) {
  7955. CmdArgs.push_back("-shared");
  7956. } else {
  7957. CmdArgs.push_back("-dynamic-linker");
  7958. CmdArgs.push_back("/usr/libexec/ld.so");
  7959. }
  7960. }
  7961. if (Output.isFilename()) {
  7962. CmdArgs.push_back("-o");
  7963. CmdArgs.push_back(Output.getFilename());
  7964. } else {
  7965. assert(Output.isNothing() && "Invalid output.");
  7966. }
  7967. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7968. if (!Args.hasArg(options::OPT_shared)) {
  7969. if (Args.hasArg(options::OPT_pg))
  7970. CmdArgs.push_back(
  7971. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  7972. else
  7973. CmdArgs.push_back(
  7974. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7975. CmdArgs.push_back(
  7976. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7977. } else {
  7978. CmdArgs.push_back(
  7979. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7980. }
  7981. }
  7982. Args.AddAllArgs(CmdArgs,
  7983. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7984. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  7985. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7986. if (D.CCCIsCXX()) {
  7987. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7988. if (Args.hasArg(options::OPT_pg))
  7989. CmdArgs.push_back("-lm_p");
  7990. else
  7991. CmdArgs.push_back("-lm");
  7992. }
  7993. if (Args.hasArg(options::OPT_pthread)) {
  7994. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  7995. CmdArgs.push_back("-lpthread_p");
  7996. else
  7997. CmdArgs.push_back("-lpthread");
  7998. }
  7999. if (!Args.hasArg(options::OPT_shared)) {
  8000. if (Args.hasArg(options::OPT_pg))
  8001. CmdArgs.push_back("-lc_p");
  8002. else
  8003. CmdArgs.push_back("-lc");
  8004. }
  8005. StringRef MyArch;
  8006. switch (getToolChain().getArch()) {
  8007. case llvm::Triple::arm:
  8008. MyArch = "arm";
  8009. break;
  8010. case llvm::Triple::x86:
  8011. MyArch = "i386";
  8012. break;
  8013. case llvm::Triple::x86_64:
  8014. MyArch = "amd64";
  8015. break;
  8016. default:
  8017. llvm_unreachable("Unsupported architecture");
  8018. }
  8019. CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
  8020. }
  8021. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8022. if (!Args.hasArg(options::OPT_shared))
  8023. CmdArgs.push_back(
  8024. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8025. else
  8026. CmdArgs.push_back(
  8027. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  8028. }
  8029. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8030. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8031. }
  8032. void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8033. const InputInfo &Output,
  8034. const InputInfoList &Inputs,
  8035. const ArgList &Args,
  8036. const char *LinkingOutput) const {
  8037. claimNoWarnArgs(Args);
  8038. ArgStringList CmdArgs;
  8039. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  8040. // instruct as in the base system to assemble 32-bit code.
  8041. switch (getToolChain().getArch()) {
  8042. default:
  8043. break;
  8044. case llvm::Triple::x86:
  8045. CmdArgs.push_back("--32");
  8046. break;
  8047. case llvm::Triple::ppc:
  8048. CmdArgs.push_back("-a32");
  8049. break;
  8050. case llvm::Triple::mips:
  8051. case llvm::Triple::mipsel:
  8052. case llvm::Triple::mips64:
  8053. case llvm::Triple::mips64el: {
  8054. StringRef CPUName;
  8055. StringRef ABIName;
  8056. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  8057. CmdArgs.push_back("-march");
  8058. CmdArgs.push_back(CPUName.data());
  8059. CmdArgs.push_back("-mabi");
  8060. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  8061. if (getToolChain().getArch() == llvm::Triple::mips ||
  8062. getToolChain().getArch() == llvm::Triple::mips64)
  8063. CmdArgs.push_back("-EB");
  8064. else
  8065. CmdArgs.push_back("-EL");
  8066. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  8067. StringRef v = A->getValue();
  8068. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  8069. A->claim();
  8070. }
  8071. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8072. break;
  8073. }
  8074. case llvm::Triple::arm:
  8075. case llvm::Triple::armeb:
  8076. case llvm::Triple::thumb:
  8077. case llvm::Triple::thumbeb: {
  8078. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  8079. if (ABI == arm::FloatABI::Hard)
  8080. CmdArgs.push_back("-mfpu=vfp");
  8081. else
  8082. CmdArgs.push_back("-mfpu=softvfp");
  8083. switch (getToolChain().getTriple().getEnvironment()) {
  8084. case llvm::Triple::GNUEABIHF:
  8085. case llvm::Triple::GNUEABI:
  8086. case llvm::Triple::EABI:
  8087. CmdArgs.push_back("-meabi=5");
  8088. break;
  8089. default:
  8090. CmdArgs.push_back("-matpcs");
  8091. }
  8092. break;
  8093. }
  8094. case llvm::Triple::sparc:
  8095. case llvm::Triple::sparcel:
  8096. case llvm::Triple::sparcv9: {
  8097. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  8098. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  8099. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8100. break;
  8101. }
  8102. }
  8103. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8104. CmdArgs.push_back("-o");
  8105. CmdArgs.push_back(Output.getFilename());
  8106. for (const auto &II : Inputs)
  8107. CmdArgs.push_back(II.getFilename());
  8108. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8109. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8110. }
  8111. void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8112. const InputInfo &Output,
  8113. const InputInfoList &Inputs,
  8114. const ArgList &Args,
  8115. const char *LinkingOutput) const {
  8116. const toolchains::FreeBSD &ToolChain =
  8117. static_cast<const toolchains::FreeBSD &>(getToolChain());
  8118. const Driver &D = ToolChain.getDriver();
  8119. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  8120. const bool IsPIE =
  8121. !Args.hasArg(options::OPT_shared) &&
  8122. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  8123. ArgStringList CmdArgs;
  8124. // Silence warning for "clang -g foo.o -o foo"
  8125. Args.ClaimAllArgs(options::OPT_g_Group);
  8126. // and "clang -emit-llvm foo.o -o foo"
  8127. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8128. // and for "clang -w foo.o -o foo". Other warning options are already
  8129. // handled somewhere else.
  8130. Args.ClaimAllArgs(options::OPT_w);
  8131. if (!D.SysRoot.empty())
  8132. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8133. if (IsPIE)
  8134. CmdArgs.push_back("-pie");
  8135. CmdArgs.push_back("--eh-frame-hdr");
  8136. if (Args.hasArg(options::OPT_static)) {
  8137. CmdArgs.push_back("-Bstatic");
  8138. } else {
  8139. if (Args.hasArg(options::OPT_rdynamic))
  8140. CmdArgs.push_back("-export-dynamic");
  8141. if (Args.hasArg(options::OPT_shared)) {
  8142. CmdArgs.push_back("-Bshareable");
  8143. } else {
  8144. CmdArgs.push_back("-dynamic-linker");
  8145. CmdArgs.push_back("/libexec/ld-elf.so.1");
  8146. }
  8147. if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
  8148. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
  8149. Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  8150. CmdArgs.push_back("--hash-style=both");
  8151. }
  8152. }
  8153. CmdArgs.push_back("--enable-new-dtags");
  8154. }
  8155. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  8156. // instruct ld in the base system to link 32-bit code.
  8157. if (Arch == llvm::Triple::x86) {
  8158. CmdArgs.push_back("-m");
  8159. CmdArgs.push_back("elf_i386_fbsd");
  8160. }
  8161. if (Arch == llvm::Triple::ppc) {
  8162. CmdArgs.push_back("-m");
  8163. CmdArgs.push_back("elf32ppc_fbsd");
  8164. }
  8165. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  8166. if (ToolChain.getArch() == llvm::Triple::mips ||
  8167. ToolChain.getArch() == llvm::Triple::mipsel ||
  8168. ToolChain.getArch() == llvm::Triple::mips64 ||
  8169. ToolChain.getArch() == llvm::Triple::mips64el) {
  8170. StringRef v = A->getValue();
  8171. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  8172. A->claim();
  8173. }
  8174. }
  8175. if (Output.isFilename()) {
  8176. CmdArgs.push_back("-o");
  8177. CmdArgs.push_back(Output.getFilename());
  8178. } else {
  8179. assert(Output.isNothing() && "Invalid output.");
  8180. }
  8181. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8182. const char *crt1 = nullptr;
  8183. if (!Args.hasArg(options::OPT_shared)) {
  8184. if (Args.hasArg(options::OPT_pg))
  8185. crt1 = "gcrt1.o";
  8186. else if (IsPIE)
  8187. crt1 = "Scrt1.o";
  8188. else
  8189. crt1 = "crt1.o";
  8190. }
  8191. if (crt1)
  8192. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  8193. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8194. const char *crtbegin = nullptr;
  8195. if (Args.hasArg(options::OPT_static))
  8196. crtbegin = "crtbeginT.o";
  8197. else if (Args.hasArg(options::OPT_shared) || IsPIE)
  8198. crtbegin = "crtbeginS.o";
  8199. else
  8200. crtbegin = "crtbegin.o";
  8201. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8202. }
  8203. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8204. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8205. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  8206. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8207. Args.AddAllArgs(CmdArgs, options::OPT_s);
  8208. Args.AddAllArgs(CmdArgs, options::OPT_t);
  8209. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  8210. Args.AddAllArgs(CmdArgs, options::OPT_r);
  8211. if (D.isUsingLTO())
  8212. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin, D);
  8213. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  8214. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  8215. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8216. addOpenMPRuntime(CmdArgs, ToolChain, Args);
  8217. if (D.CCCIsCXX()) {
  8218. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8219. if (Args.hasArg(options::OPT_pg))
  8220. CmdArgs.push_back("-lm_p");
  8221. else
  8222. CmdArgs.push_back("-lm");
  8223. }
  8224. if (NeedsSanitizerDeps)
  8225. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  8226. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  8227. // the default system libraries. Just mimic this for now.
  8228. if (Args.hasArg(options::OPT_pg))
  8229. CmdArgs.push_back("-lgcc_p");
  8230. else
  8231. CmdArgs.push_back("-lgcc");
  8232. if (Args.hasArg(options::OPT_static)) {
  8233. CmdArgs.push_back("-lgcc_eh");
  8234. } else if (Args.hasArg(options::OPT_pg)) {
  8235. CmdArgs.push_back("-lgcc_eh_p");
  8236. } else {
  8237. CmdArgs.push_back("--as-needed");
  8238. CmdArgs.push_back("-lgcc_s");
  8239. CmdArgs.push_back("--no-as-needed");
  8240. }
  8241. if (Args.hasArg(options::OPT_pthread)) {
  8242. if (Args.hasArg(options::OPT_pg))
  8243. CmdArgs.push_back("-lpthread_p");
  8244. else
  8245. CmdArgs.push_back("-lpthread");
  8246. }
  8247. if (Args.hasArg(options::OPT_pg)) {
  8248. if (Args.hasArg(options::OPT_shared))
  8249. CmdArgs.push_back("-lc");
  8250. else
  8251. CmdArgs.push_back("-lc_p");
  8252. CmdArgs.push_back("-lgcc_p");
  8253. } else {
  8254. CmdArgs.push_back("-lc");
  8255. CmdArgs.push_back("-lgcc");
  8256. }
  8257. if (Args.hasArg(options::OPT_static)) {
  8258. CmdArgs.push_back("-lgcc_eh");
  8259. } else if (Args.hasArg(options::OPT_pg)) {
  8260. CmdArgs.push_back("-lgcc_eh_p");
  8261. } else {
  8262. CmdArgs.push_back("--as-needed");
  8263. CmdArgs.push_back("-lgcc_s");
  8264. CmdArgs.push_back("--no-as-needed");
  8265. }
  8266. }
  8267. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8268. if (Args.hasArg(options::OPT_shared) || IsPIE)
  8269. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  8270. else
  8271. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  8272. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8273. }
  8274. ToolChain.addProfileRTLibs(Args, CmdArgs);
  8275. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8276. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8277. }
  8278. void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8279. const InputInfo &Output,
  8280. const InputInfoList &Inputs,
  8281. const ArgList &Args,
  8282. const char *LinkingOutput) const {
  8283. claimNoWarnArgs(Args);
  8284. ArgStringList CmdArgs;
  8285. // GNU as needs different flags for creating the correct output format
  8286. // on architectures with different ABIs or optional feature sets.
  8287. switch (getToolChain().getArch()) {
  8288. case llvm::Triple::x86:
  8289. CmdArgs.push_back("--32");
  8290. break;
  8291. case llvm::Triple::arm:
  8292. case llvm::Triple::armeb:
  8293. case llvm::Triple::thumb:
  8294. case llvm::Triple::thumbeb: {
  8295. StringRef MArch, MCPU;
  8296. getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
  8297. std::string Arch =
  8298. arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
  8299. CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
  8300. break;
  8301. }
  8302. case llvm::Triple::mips:
  8303. case llvm::Triple::mipsel:
  8304. case llvm::Triple::mips64:
  8305. case llvm::Triple::mips64el: {
  8306. StringRef CPUName;
  8307. StringRef ABIName;
  8308. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  8309. CmdArgs.push_back("-march");
  8310. CmdArgs.push_back(CPUName.data());
  8311. CmdArgs.push_back("-mabi");
  8312. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  8313. if (getToolChain().getArch() == llvm::Triple::mips ||
  8314. getToolChain().getArch() == llvm::Triple::mips64)
  8315. CmdArgs.push_back("-EB");
  8316. else
  8317. CmdArgs.push_back("-EL");
  8318. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8319. break;
  8320. }
  8321. case llvm::Triple::sparc:
  8322. case llvm::Triple::sparcel: {
  8323. CmdArgs.push_back("-32");
  8324. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  8325. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  8326. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8327. break;
  8328. }
  8329. case llvm::Triple::sparcv9: {
  8330. CmdArgs.push_back("-64");
  8331. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  8332. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  8333. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8334. break;
  8335. }
  8336. default:
  8337. break;
  8338. }
  8339. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8340. CmdArgs.push_back("-o");
  8341. CmdArgs.push_back(Output.getFilename());
  8342. for (const auto &II : Inputs)
  8343. CmdArgs.push_back(II.getFilename());
  8344. const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
  8345. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8346. }
  8347. void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8348. const InputInfo &Output,
  8349. const InputInfoList &Inputs,
  8350. const ArgList &Args,
  8351. const char *LinkingOutput) const {
  8352. const Driver &D = getToolChain().getDriver();
  8353. ArgStringList CmdArgs;
  8354. if (!D.SysRoot.empty())
  8355. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8356. CmdArgs.push_back("--eh-frame-hdr");
  8357. if (Args.hasArg(options::OPT_static)) {
  8358. CmdArgs.push_back("-Bstatic");
  8359. } else {
  8360. if (Args.hasArg(options::OPT_rdynamic))
  8361. CmdArgs.push_back("-export-dynamic");
  8362. if (Args.hasArg(options::OPT_shared)) {
  8363. CmdArgs.push_back("-Bshareable");
  8364. } else {
  8365. Args.AddAllArgs(CmdArgs, options::OPT_pie);
  8366. CmdArgs.push_back("-dynamic-linker");
  8367. CmdArgs.push_back("/libexec/ld.elf_so");
  8368. }
  8369. }
  8370. // Many NetBSD architectures support more than one ABI.
  8371. // Determine the correct emulation for ld.
  8372. switch (getToolChain().getArch()) {
  8373. case llvm::Triple::x86:
  8374. CmdArgs.push_back("-m");
  8375. CmdArgs.push_back("elf_i386");
  8376. break;
  8377. case llvm::Triple::arm:
  8378. case llvm::Triple::thumb:
  8379. CmdArgs.push_back("-m");
  8380. switch (getToolChain().getTriple().getEnvironment()) {
  8381. case llvm::Triple::EABI:
  8382. case llvm::Triple::GNUEABI:
  8383. CmdArgs.push_back("armelf_nbsd_eabi");
  8384. break;
  8385. case llvm::Triple::EABIHF:
  8386. case llvm::Triple::GNUEABIHF:
  8387. CmdArgs.push_back("armelf_nbsd_eabihf");
  8388. break;
  8389. default:
  8390. CmdArgs.push_back("armelf_nbsd");
  8391. break;
  8392. }
  8393. break;
  8394. case llvm::Triple::armeb:
  8395. case llvm::Triple::thumbeb:
  8396. arm::appendEBLinkFlags(Args, CmdArgs, getToolChain().getEffectiveTriple());
  8397. CmdArgs.push_back("-m");
  8398. switch (getToolChain().getTriple().getEnvironment()) {
  8399. case llvm::Triple::EABI:
  8400. case llvm::Triple::GNUEABI:
  8401. CmdArgs.push_back("armelfb_nbsd_eabi");
  8402. break;
  8403. case llvm::Triple::EABIHF:
  8404. case llvm::Triple::GNUEABIHF:
  8405. CmdArgs.push_back("armelfb_nbsd_eabihf");
  8406. break;
  8407. default:
  8408. CmdArgs.push_back("armelfb_nbsd");
  8409. break;
  8410. }
  8411. break;
  8412. case llvm::Triple::mips64:
  8413. case llvm::Triple::mips64el:
  8414. if (mips::hasMipsAbiArg(Args, "32")) {
  8415. CmdArgs.push_back("-m");
  8416. if (getToolChain().getArch() == llvm::Triple::mips64)
  8417. CmdArgs.push_back("elf32btsmip");
  8418. else
  8419. CmdArgs.push_back("elf32ltsmip");
  8420. } else if (mips::hasMipsAbiArg(Args, "64")) {
  8421. CmdArgs.push_back("-m");
  8422. if (getToolChain().getArch() == llvm::Triple::mips64)
  8423. CmdArgs.push_back("elf64btsmip");
  8424. else
  8425. CmdArgs.push_back("elf64ltsmip");
  8426. }
  8427. break;
  8428. case llvm::Triple::ppc:
  8429. CmdArgs.push_back("-m");
  8430. CmdArgs.push_back("elf32ppc_nbsd");
  8431. break;
  8432. case llvm::Triple::ppc64:
  8433. case llvm::Triple::ppc64le:
  8434. CmdArgs.push_back("-m");
  8435. CmdArgs.push_back("elf64ppc");
  8436. break;
  8437. case llvm::Triple::sparc:
  8438. CmdArgs.push_back("-m");
  8439. CmdArgs.push_back("elf32_sparc");
  8440. break;
  8441. case llvm::Triple::sparcv9:
  8442. CmdArgs.push_back("-m");
  8443. CmdArgs.push_back("elf64_sparc");
  8444. break;
  8445. default:
  8446. break;
  8447. }
  8448. if (Output.isFilename()) {
  8449. CmdArgs.push_back("-o");
  8450. CmdArgs.push_back(Output.getFilename());
  8451. } else {
  8452. assert(Output.isNothing() && "Invalid output.");
  8453. }
  8454. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8455. if (!Args.hasArg(options::OPT_shared)) {
  8456. CmdArgs.push_back(
  8457. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  8458. }
  8459. CmdArgs.push_back(
  8460. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8461. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
  8462. CmdArgs.push_back(
  8463. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  8464. } else {
  8465. CmdArgs.push_back(
  8466. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8467. }
  8468. }
  8469. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8470. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  8471. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8472. Args.AddAllArgs(CmdArgs, options::OPT_s);
  8473. Args.AddAllArgs(CmdArgs, options::OPT_t);
  8474. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  8475. Args.AddAllArgs(CmdArgs, options::OPT_r);
  8476. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  8477. unsigned Major, Minor, Micro;
  8478. getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
  8479. bool useLibgcc = true;
  8480. if (Major >= 7 || Major == 0) {
  8481. switch (getToolChain().getArch()) {
  8482. case llvm::Triple::aarch64:
  8483. case llvm::Triple::aarch64_be:
  8484. case llvm::Triple::arm:
  8485. case llvm::Triple::armeb:
  8486. case llvm::Triple::thumb:
  8487. case llvm::Triple::thumbeb:
  8488. case llvm::Triple::ppc:
  8489. case llvm::Triple::ppc64:
  8490. case llvm::Triple::ppc64le:
  8491. case llvm::Triple::sparc:
  8492. case llvm::Triple::sparcv9:
  8493. case llvm::Triple::x86:
  8494. case llvm::Triple::x86_64:
  8495. useLibgcc = false;
  8496. break;
  8497. default:
  8498. break;
  8499. }
  8500. }
  8501. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8502. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  8503. if (D.CCCIsCXX()) {
  8504. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8505. CmdArgs.push_back("-lm");
  8506. }
  8507. if (Args.hasArg(options::OPT_pthread))
  8508. CmdArgs.push_back("-lpthread");
  8509. CmdArgs.push_back("-lc");
  8510. if (useLibgcc) {
  8511. if (Args.hasArg(options::OPT_static)) {
  8512. // libgcc_eh depends on libc, so resolve as much as possible,
  8513. // pull in any new requirements from libc and then get the rest
  8514. // of libgcc.
  8515. CmdArgs.push_back("-lgcc_eh");
  8516. CmdArgs.push_back("-lc");
  8517. CmdArgs.push_back("-lgcc");
  8518. } else {
  8519. CmdArgs.push_back("-lgcc");
  8520. CmdArgs.push_back("--as-needed");
  8521. CmdArgs.push_back("-lgcc_s");
  8522. CmdArgs.push_back("--no-as-needed");
  8523. }
  8524. }
  8525. }
  8526. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8527. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8528. CmdArgs.push_back(
  8529. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  8530. else
  8531. CmdArgs.push_back(
  8532. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8533. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8534. }
  8535. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8536. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8537. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8538. }
  8539. void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8540. const InputInfo &Output,
  8541. const InputInfoList &Inputs,
  8542. const ArgList &Args,
  8543. const char *LinkingOutput) const {
  8544. claimNoWarnArgs(Args);
  8545. ArgStringList CmdArgs;
  8546. llvm::Reloc::Model RelocationModel;
  8547. unsigned PICLevel;
  8548. bool IsPIE;
  8549. std::tie(RelocationModel, PICLevel, IsPIE) =
  8550. ParsePICArgs(getToolChain(), Args);
  8551. switch (getToolChain().getArch()) {
  8552. default:
  8553. break;
  8554. // Add --32/--64 to make sure we get the format we want.
  8555. // This is incomplete
  8556. case llvm::Triple::x86:
  8557. CmdArgs.push_back("--32");
  8558. break;
  8559. case llvm::Triple::x86_64:
  8560. if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
  8561. CmdArgs.push_back("--x32");
  8562. else
  8563. CmdArgs.push_back("--64");
  8564. break;
  8565. case llvm::Triple::ppc:
  8566. CmdArgs.push_back("-a32");
  8567. CmdArgs.push_back("-mppc");
  8568. CmdArgs.push_back("-many");
  8569. break;
  8570. case llvm::Triple::ppc64:
  8571. CmdArgs.push_back("-a64");
  8572. CmdArgs.push_back("-mppc64");
  8573. CmdArgs.push_back("-many");
  8574. break;
  8575. case llvm::Triple::ppc64le:
  8576. CmdArgs.push_back("-a64");
  8577. CmdArgs.push_back("-mppc64");
  8578. CmdArgs.push_back("-many");
  8579. CmdArgs.push_back("-mlittle-endian");
  8580. break;
  8581. case llvm::Triple::sparc:
  8582. case llvm::Triple::sparcel: {
  8583. CmdArgs.push_back("-32");
  8584. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  8585. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  8586. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8587. break;
  8588. }
  8589. case llvm::Triple::sparcv9: {
  8590. CmdArgs.push_back("-64");
  8591. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  8592. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  8593. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8594. break;
  8595. }
  8596. case llvm::Triple::arm:
  8597. case llvm::Triple::armeb:
  8598. case llvm::Triple::thumb:
  8599. case llvm::Triple::thumbeb: {
  8600. const llvm::Triple &Triple2 = getToolChain().getTriple();
  8601. switch (Triple2.getSubArch()) {
  8602. case llvm::Triple::ARMSubArch_v7:
  8603. CmdArgs.push_back("-mfpu=neon");
  8604. break;
  8605. case llvm::Triple::ARMSubArch_v8:
  8606. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  8607. break;
  8608. default:
  8609. break;
  8610. }
  8611. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  8612. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  8613. case arm::FloatABI::Soft:
  8614. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  8615. break;
  8616. case arm::FloatABI::SoftFP:
  8617. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  8618. break;
  8619. case arm::FloatABI::Hard:
  8620. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  8621. break;
  8622. }
  8623. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  8624. // FIXME: remove krait check when GNU tools support krait cpu
  8625. // for now replace it with -mcpu=cortex-a15 to avoid a lower
  8626. // march from being picked in the absence of a cpu flag.
  8627. Arg *A;
  8628. if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
  8629. StringRef(A->getValue()).equals_lower("krait"))
  8630. CmdArgs.push_back("-mcpu=cortex-a15");
  8631. else
  8632. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  8633. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  8634. break;
  8635. }
  8636. case llvm::Triple::mips:
  8637. case llvm::Triple::mipsel:
  8638. case llvm::Triple::mips64:
  8639. case llvm::Triple::mips64el: {
  8640. StringRef CPUName;
  8641. StringRef ABIName;
  8642. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  8643. ABIName = getGnuCompatibleMipsABIName(ABIName);
  8644. CmdArgs.push_back("-march");
  8645. CmdArgs.push_back(CPUName.data());
  8646. CmdArgs.push_back("-mabi");
  8647. CmdArgs.push_back(ABIName.data());
  8648. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  8649. // or -mshared (not implemented) is in effect.
  8650. if (RelocationModel == llvm::Reloc::Static)
  8651. CmdArgs.push_back("-mno-shared");
  8652. // LLVM doesn't support -mplt yet and acts as if it is always given.
  8653. // However, -mplt has no effect with the N64 ABI.
  8654. if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls))
  8655. CmdArgs.push_back("-call_nonpic");
  8656. if (getToolChain().getArch() == llvm::Triple::mips ||
  8657. getToolChain().getArch() == llvm::Triple::mips64)
  8658. CmdArgs.push_back("-EB");
  8659. else
  8660. CmdArgs.push_back("-EL");
  8661. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  8662. if (StringRef(A->getValue()) == "2008")
  8663. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  8664. }
  8665. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  8666. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  8667. options::OPT_mfp64)) {
  8668. A->claim();
  8669. A->render(Args, CmdArgs);
  8670. } else if (mips::shouldUseFPXX(
  8671. Args, getToolChain().getTriple(), CPUName, ABIName,
  8672. getMipsFloatABI(getToolChain().getDriver(), Args)))
  8673. CmdArgs.push_back("-mfpxx");
  8674. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  8675. // -mno-mips16 is actually -no-mips16.
  8676. if (Arg *A =
  8677. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  8678. if (A->getOption().matches(options::OPT_mips16)) {
  8679. A->claim();
  8680. A->render(Args, CmdArgs);
  8681. } else {
  8682. A->claim();
  8683. CmdArgs.push_back("-no-mips16");
  8684. }
  8685. }
  8686. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  8687. options::OPT_mno_micromips);
  8688. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  8689. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  8690. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  8691. // Do not use AddLastArg because not all versions of MIPS assembler
  8692. // support -mmsa / -mno-msa options.
  8693. if (A->getOption().matches(options::OPT_mmsa))
  8694. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  8695. }
  8696. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  8697. options::OPT_msoft_float);
  8698. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  8699. options::OPT_msingle_float);
  8700. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  8701. options::OPT_mno_odd_spreg);
  8702. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8703. break;
  8704. }
  8705. case llvm::Triple::systemz: {
  8706. // Always pass an -march option, since our default of z10 is later
  8707. // than the GNU assembler's default.
  8708. StringRef CPUName = getSystemZTargetCPU(Args);
  8709. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  8710. break;
  8711. }
  8712. }
  8713. Args.AddAllArgs(CmdArgs, options::OPT_I);
  8714. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8715. CmdArgs.push_back("-o");
  8716. CmdArgs.push_back(Output.getFilename());
  8717. for (const auto &II : Inputs)
  8718. CmdArgs.push_back(II.getFilename());
  8719. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8720. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8721. // Handle the debug info splitting at object creation time if we're
  8722. // creating an object.
  8723. // TODO: Currently only works on linux with newer objcopy.
  8724. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  8725. getToolChain().getTriple().isOSLinux())
  8726. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  8727. SplitDebugName(Args, Inputs[0]));
  8728. }
  8729. static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
  8730. ArgStringList &CmdArgs, const ArgList &Args) {
  8731. bool isAndroid = Triple.isAndroid();
  8732. bool isCygMing = Triple.isOSCygMing();
  8733. bool IsIAMCU = Triple.isOSIAMCU();
  8734. bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
  8735. Args.hasArg(options::OPT_static);
  8736. if (!D.CCCIsCXX())
  8737. CmdArgs.push_back("-lgcc");
  8738. if (StaticLibgcc || isAndroid) {
  8739. if (D.CCCIsCXX())
  8740. CmdArgs.push_back("-lgcc");
  8741. } else {
  8742. if (!D.CCCIsCXX() && !isCygMing)
  8743. CmdArgs.push_back("--as-needed");
  8744. CmdArgs.push_back("-lgcc_s");
  8745. if (!D.CCCIsCXX() && !isCygMing)
  8746. CmdArgs.push_back("--no-as-needed");
  8747. }
  8748. if (StaticLibgcc && !isAndroid && !IsIAMCU)
  8749. CmdArgs.push_back("-lgcc_eh");
  8750. else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
  8751. CmdArgs.push_back("-lgcc");
  8752. // According to Android ABI, we have to link with libdl if we are
  8753. // linking with non-static libgcc.
  8754. //
  8755. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  8756. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  8757. if (isAndroid && !StaticLibgcc)
  8758. CmdArgs.push_back("-ldl");
  8759. }
  8760. static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  8761. ArgStringList &CmdArgs, const ArgList &Args) {
  8762. // Make use of compiler-rt if --rtlib option is used
  8763. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  8764. switch (RLT) {
  8765. case ToolChain::RLT_CompilerRT:
  8766. switch (TC.getTriple().getOS()) {
  8767. default:
  8768. llvm_unreachable("unsupported OS");
  8769. case llvm::Triple::Win32:
  8770. case llvm::Triple::Linux:
  8771. case llvm::Triple::Fuchsia:
  8772. addClangRT(TC, Args, CmdArgs);
  8773. break;
  8774. }
  8775. break;
  8776. case ToolChain::RLT_Libgcc:
  8777. // Make sure libgcc is not used under MSVC environment by default
  8778. if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
  8779. // Issue error diagnostic if libgcc is explicitly specified
  8780. // through command line as --rtlib option argument.
  8781. if (Args.hasArg(options::OPT_rtlib_EQ)) {
  8782. TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
  8783. << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
  8784. }
  8785. } else
  8786. AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
  8787. break;
  8788. }
  8789. }
  8790. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  8791. switch (T.getArch()) {
  8792. case llvm::Triple::x86:
  8793. if (T.isOSIAMCU())
  8794. return "elf_iamcu";
  8795. return "elf_i386";
  8796. case llvm::Triple::aarch64:
  8797. return "aarch64linux";
  8798. case llvm::Triple::aarch64_be:
  8799. return "aarch64_be_linux";
  8800. case llvm::Triple::arm:
  8801. case llvm::Triple::thumb:
  8802. return "armelf_linux_eabi";
  8803. case llvm::Triple::armeb:
  8804. case llvm::Triple::thumbeb:
  8805. return "armelfb_linux_eabi";
  8806. case llvm::Triple::ppc:
  8807. return "elf32ppclinux";
  8808. case llvm::Triple::ppc64:
  8809. return "elf64ppc";
  8810. case llvm::Triple::ppc64le:
  8811. return "elf64lppc";
  8812. case llvm::Triple::sparc:
  8813. case llvm::Triple::sparcel:
  8814. return "elf32_sparc";
  8815. case llvm::Triple::sparcv9:
  8816. return "elf64_sparc";
  8817. case llvm::Triple::mips:
  8818. return "elf32btsmip";
  8819. case llvm::Triple::mipsel:
  8820. return "elf32ltsmip";
  8821. case llvm::Triple::mips64:
  8822. if (mips::hasMipsAbiArg(Args, "n32"))
  8823. return "elf32btsmipn32";
  8824. return "elf64btsmip";
  8825. case llvm::Triple::mips64el:
  8826. if (mips::hasMipsAbiArg(Args, "n32"))
  8827. return "elf32ltsmipn32";
  8828. return "elf64ltsmip";
  8829. case llvm::Triple::systemz:
  8830. return "elf64_s390";
  8831. case llvm::Triple::x86_64:
  8832. if (T.getEnvironment() == llvm::Triple::GNUX32)
  8833. return "elf32_x86_64";
  8834. return "elf_x86_64";
  8835. default:
  8836. return nullptr;
  8837. }
  8838. }
  8839. void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8840. const InputInfo &Output,
  8841. const InputInfoList &Inputs,
  8842. const ArgList &Args,
  8843. const char *LinkingOutput) const {
  8844. const toolchains::Linux &ToolChain =
  8845. static_cast<const toolchains::Linux &>(getToolChain());
  8846. const Driver &D = ToolChain.getDriver();
  8847. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  8848. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  8849. const bool isAndroid = ToolChain.getTriple().isAndroid();
  8850. const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
  8851. const bool IsPIE =
  8852. !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
  8853. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  8854. const bool HasCRTBeginEndFiles =
  8855. ToolChain.getTriple().hasEnvironment() ||
  8856. (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
  8857. ArgStringList CmdArgs;
  8858. // Silence warning for "clang -g foo.o -o foo"
  8859. Args.ClaimAllArgs(options::OPT_g_Group);
  8860. // and "clang -emit-llvm foo.o -o foo"
  8861. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8862. // and for "clang -w foo.o -o foo". Other warning options are already
  8863. // handled somewhere else.
  8864. Args.ClaimAllArgs(options::OPT_w);
  8865. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  8866. if (llvm::sys::path::filename(Exec) == "lld") {
  8867. CmdArgs.push_back("-flavor");
  8868. CmdArgs.push_back("old-gnu");
  8869. CmdArgs.push_back("-target");
  8870. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  8871. }
  8872. if (!D.SysRoot.empty())
  8873. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8874. if (IsPIE)
  8875. CmdArgs.push_back("-pie");
  8876. if (Args.hasArg(options::OPT_rdynamic))
  8877. CmdArgs.push_back("-export-dynamic");
  8878. if (Args.hasArg(options::OPT_s))
  8879. CmdArgs.push_back("-s");
  8880. if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
  8881. arm::appendEBLinkFlags(Args, CmdArgs, Triple);
  8882. // Most Android ARM64 targets should enable the linker fix for erratum
  8883. // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
  8884. if (Arch == llvm::Triple::aarch64 && isAndroid) {
  8885. std::string CPU = getCPUName(Args, Triple);
  8886. if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
  8887. CmdArgs.push_back("--fix-cortex-a53-843419");
  8888. }
  8889. for (const auto &Opt : ToolChain.ExtraOpts)
  8890. CmdArgs.push_back(Opt.c_str());
  8891. if (!Args.hasArg(options::OPT_static)) {
  8892. CmdArgs.push_back("--eh-frame-hdr");
  8893. }
  8894. if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
  8895. CmdArgs.push_back("-m");
  8896. CmdArgs.push_back(LDMOption);
  8897. } else {
  8898. D.Diag(diag::err_target_unknown_triple) << Triple.str();
  8899. return;
  8900. }
  8901. if (Args.hasArg(options::OPT_static)) {
  8902. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  8903. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
  8904. CmdArgs.push_back("-Bstatic");
  8905. else
  8906. CmdArgs.push_back("-static");
  8907. } else if (Args.hasArg(options::OPT_shared)) {
  8908. CmdArgs.push_back("-shared");
  8909. }
  8910. if (!Args.hasArg(options::OPT_static)) {
  8911. if (Args.hasArg(options::OPT_rdynamic))
  8912. CmdArgs.push_back("-export-dynamic");
  8913. if (!Args.hasArg(options::OPT_shared)) {
  8914. const std::string Loader =
  8915. D.DyldPrefix + ToolChain.getDynamicLinker(Args);
  8916. CmdArgs.push_back("-dynamic-linker");
  8917. CmdArgs.push_back(Args.MakeArgString(Loader));
  8918. }
  8919. }
  8920. CmdArgs.push_back("-o");
  8921. CmdArgs.push_back(Output.getFilename());
  8922. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8923. if (!isAndroid && !IsIAMCU) {
  8924. const char *crt1 = nullptr;
  8925. if (!Args.hasArg(options::OPT_shared)) {
  8926. if (Args.hasArg(options::OPT_pg))
  8927. crt1 = "gcrt1.o";
  8928. else if (IsPIE)
  8929. crt1 = "Scrt1.o";
  8930. else
  8931. crt1 = "crt1.o";
  8932. }
  8933. if (crt1)
  8934. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  8935. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8936. }
  8937. if (IsIAMCU)
  8938. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  8939. else {
  8940. const char *crtbegin;
  8941. if (Args.hasArg(options::OPT_static))
  8942. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  8943. else if (Args.hasArg(options::OPT_shared))
  8944. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  8945. else if (IsPIE)
  8946. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  8947. else
  8948. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  8949. if (HasCRTBeginEndFiles)
  8950. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8951. }
  8952. // Add crtfastmath.o if available and fast math is enabled.
  8953. ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8954. }
  8955. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8956. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8957. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8958. if (D.isUsingLTO())
  8959. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin, D);
  8960. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8961. CmdArgs.push_back("--no-demangle");
  8962. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  8963. bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
  8964. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  8965. // The profile runtime also needs access to system libraries.
  8966. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8967. if (D.CCCIsCXX() &&
  8968. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8969. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8970. !Args.hasArg(options::OPT_static);
  8971. if (OnlyLibstdcxxStatic)
  8972. CmdArgs.push_back("-Bstatic");
  8973. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8974. if (OnlyLibstdcxxStatic)
  8975. CmdArgs.push_back("-Bdynamic");
  8976. CmdArgs.push_back("-lm");
  8977. }
  8978. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  8979. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  8980. if (!Args.hasArg(options::OPT_nostdlib)) {
  8981. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8982. if (Args.hasArg(options::OPT_static))
  8983. CmdArgs.push_back("--start-group");
  8984. if (NeedsSanitizerDeps)
  8985. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  8986. if (NeedsXRayDeps)
  8987. linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
  8988. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  8989. Args.hasArg(options::OPT_pthreads);
  8990. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8991. options::OPT_fno_openmp, false)) {
  8992. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  8993. // FIXME: Does this really make sense for all GNU toolchains?
  8994. WantPthread = true;
  8995. // Also link the particular OpenMP runtimes.
  8996. switch (ToolChain.getDriver().getOpenMPRuntime(Args)) {
  8997. case Driver::OMPRT_OMP:
  8998. CmdArgs.push_back("-lomp");
  8999. break;
  9000. case Driver::OMPRT_GOMP:
  9001. CmdArgs.push_back("-lgomp");
  9002. // FIXME: Exclude this for platforms with libgomp that don't require
  9003. // librt. Most modern Linux platforms require it, but some may not.
  9004. CmdArgs.push_back("-lrt");
  9005. break;
  9006. case Driver::OMPRT_IOMP5:
  9007. CmdArgs.push_back("-liomp5");
  9008. break;
  9009. case Driver::OMPRT_Unknown:
  9010. // Already diagnosed.
  9011. break;
  9012. }
  9013. if (JA.isHostOffloading(Action::OFK_OpenMP))
  9014. CmdArgs.push_back("-lomptarget");
  9015. }
  9016. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  9017. if (WantPthread && !isAndroid)
  9018. CmdArgs.push_back("-lpthread");
  9019. if (Args.hasArg(options::OPT_fsplit_stack))
  9020. CmdArgs.push_back("--wrap=pthread_create");
  9021. CmdArgs.push_back("-lc");
  9022. // Add IAMCU specific libs, if needed.
  9023. if (IsIAMCU)
  9024. CmdArgs.push_back("-lgloss");
  9025. if (Args.hasArg(options::OPT_static))
  9026. CmdArgs.push_back("--end-group");
  9027. else
  9028. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  9029. // Add IAMCU specific libs (outside the group), if needed.
  9030. if (IsIAMCU) {
  9031. CmdArgs.push_back("--as-needed");
  9032. CmdArgs.push_back("-lsoftfp");
  9033. CmdArgs.push_back("--no-as-needed");
  9034. }
  9035. }
  9036. if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
  9037. const char *crtend;
  9038. if (Args.hasArg(options::OPT_shared))
  9039. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  9040. else if (IsPIE)
  9041. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  9042. else
  9043. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  9044. if (HasCRTBeginEndFiles)
  9045. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  9046. if (!isAndroid)
  9047. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  9048. }
  9049. }
  9050. // Add OpenMP offloading linker script args if required.
  9051. AddOpenMPLinkerScript(getToolChain(), C, Output, Inputs, Args, CmdArgs, JA);
  9052. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9053. }
  9054. // NaCl ARM assembly (inline or standalone) can be written with a set of macros
  9055. // for the various SFI requirements like register masking. The assembly tool
  9056. // inserts the file containing the macros as an input into all the assembly
  9057. // jobs.
  9058. void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
  9059. const InputInfo &Output,
  9060. const InputInfoList &Inputs,
  9061. const ArgList &Args,
  9062. const char *LinkingOutput) const {
  9063. const toolchains::NaClToolChain &ToolChain =
  9064. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  9065. InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
  9066. "nacl-arm-macros.s");
  9067. InputInfoList NewInputs;
  9068. NewInputs.push_back(NaClMacros);
  9069. NewInputs.append(Inputs.begin(), Inputs.end());
  9070. gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
  9071. LinkingOutput);
  9072. }
  9073. // This is quite similar to gnutools::Linker::ConstructJob with changes that
  9074. // we use static by default, do not yet support sanitizers or LTO, and a few
  9075. // others. Eventually we can support more of that and hopefully migrate back
  9076. // to gnutools::Linker.
  9077. void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9078. const InputInfo &Output,
  9079. const InputInfoList &Inputs,
  9080. const ArgList &Args,
  9081. const char *LinkingOutput) const {
  9082. const toolchains::NaClToolChain &ToolChain =
  9083. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  9084. const Driver &D = ToolChain.getDriver();
  9085. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  9086. const bool IsStatic =
  9087. !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
  9088. ArgStringList CmdArgs;
  9089. // Silence warning for "clang -g foo.o -o foo"
  9090. Args.ClaimAllArgs(options::OPT_g_Group);
  9091. // and "clang -emit-llvm foo.o -o foo"
  9092. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9093. // and for "clang -w foo.o -o foo". Other warning options are already
  9094. // handled somewhere else.
  9095. Args.ClaimAllArgs(options::OPT_w);
  9096. if (!D.SysRoot.empty())
  9097. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9098. if (Args.hasArg(options::OPT_rdynamic))
  9099. CmdArgs.push_back("-export-dynamic");
  9100. if (Args.hasArg(options::OPT_s))
  9101. CmdArgs.push_back("-s");
  9102. // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
  9103. // from there is --build-id, which we do want.
  9104. CmdArgs.push_back("--build-id");
  9105. if (!IsStatic)
  9106. CmdArgs.push_back("--eh-frame-hdr");
  9107. CmdArgs.push_back("-m");
  9108. if (Arch == llvm::Triple::x86)
  9109. CmdArgs.push_back("elf_i386_nacl");
  9110. else if (Arch == llvm::Triple::arm)
  9111. CmdArgs.push_back("armelf_nacl");
  9112. else if (Arch == llvm::Triple::x86_64)
  9113. CmdArgs.push_back("elf_x86_64_nacl");
  9114. else if (Arch == llvm::Triple::mipsel)
  9115. CmdArgs.push_back("mipselelf_nacl");
  9116. else
  9117. D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
  9118. << "Native Client";
  9119. if (IsStatic)
  9120. CmdArgs.push_back("-static");
  9121. else if (Args.hasArg(options::OPT_shared))
  9122. CmdArgs.push_back("-shared");
  9123. CmdArgs.push_back("-o");
  9124. CmdArgs.push_back(Output.getFilename());
  9125. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9126. if (!Args.hasArg(options::OPT_shared))
  9127. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  9128. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  9129. const char *crtbegin;
  9130. if (IsStatic)
  9131. crtbegin = "crtbeginT.o";
  9132. else if (Args.hasArg(options::OPT_shared))
  9133. crtbegin = "crtbeginS.o";
  9134. else
  9135. crtbegin = "crtbegin.o";
  9136. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  9137. }
  9138. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9139. Args.AddAllArgs(CmdArgs, options::OPT_u);
  9140. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  9141. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9142. CmdArgs.push_back("--no-demangle");
  9143. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  9144. if (D.CCCIsCXX() &&
  9145. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9146. bool OnlyLibstdcxxStatic =
  9147. Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
  9148. if (OnlyLibstdcxxStatic)
  9149. CmdArgs.push_back("-Bstatic");
  9150. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  9151. if (OnlyLibstdcxxStatic)
  9152. CmdArgs.push_back("-Bdynamic");
  9153. CmdArgs.push_back("-lm");
  9154. }
  9155. if (!Args.hasArg(options::OPT_nostdlib)) {
  9156. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  9157. // Always use groups, since it has no effect on dynamic libraries.
  9158. CmdArgs.push_back("--start-group");
  9159. CmdArgs.push_back("-lc");
  9160. // NaCl's libc++ currently requires libpthread, so just always include it
  9161. // in the group for C++.
  9162. if (Args.hasArg(options::OPT_pthread) ||
  9163. Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
  9164. // Gold, used by Mips, handles nested groups differently than ld, and
  9165. // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
  9166. // which is not a desired behaviour here.
  9167. // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
  9168. if (getToolChain().getArch() == llvm::Triple::mipsel)
  9169. CmdArgs.push_back("-lnacl");
  9170. CmdArgs.push_back("-lpthread");
  9171. }
  9172. CmdArgs.push_back("-lgcc");
  9173. CmdArgs.push_back("--as-needed");
  9174. if (IsStatic)
  9175. CmdArgs.push_back("-lgcc_eh");
  9176. else
  9177. CmdArgs.push_back("-lgcc_s");
  9178. CmdArgs.push_back("--no-as-needed");
  9179. // Mips needs to create and use pnacl_legacy library that contains
  9180. // definitions from bitcode/pnaclmm.c and definitions for
  9181. // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
  9182. if (getToolChain().getArch() == llvm::Triple::mipsel)
  9183. CmdArgs.push_back("-lpnacl_legacy");
  9184. CmdArgs.push_back("--end-group");
  9185. }
  9186. if (!Args.hasArg(options::OPT_nostartfiles)) {
  9187. const char *crtend;
  9188. if (Args.hasArg(options::OPT_shared))
  9189. crtend = "crtendS.o";
  9190. else
  9191. crtend = "crtend.o";
  9192. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  9193. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  9194. }
  9195. }
  9196. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  9197. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9198. }
  9199. void fuchsia::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9200. const InputInfo &Output,
  9201. const InputInfoList &Inputs,
  9202. const ArgList &Args,
  9203. const char *LinkingOutput) const {
  9204. const toolchains::Fuchsia &ToolChain =
  9205. static_cast<const toolchains::Fuchsia &>(getToolChain());
  9206. const Driver &D = ToolChain.getDriver();
  9207. ArgStringList CmdArgs;
  9208. // Silence warning for "clang -g foo.o -o foo"
  9209. Args.ClaimAllArgs(options::OPT_g_Group);
  9210. // and "clang -emit-llvm foo.o -o foo"
  9211. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9212. // and for "clang -w foo.o -o foo". Other warning options are already
  9213. // handled somewhere else.
  9214. Args.ClaimAllArgs(options::OPT_w);
  9215. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  9216. if (llvm::sys::path::stem(Exec).equals_lower("lld")) {
  9217. CmdArgs.push_back("-flavor");
  9218. CmdArgs.push_back("gnu");
  9219. }
  9220. if (!D.SysRoot.empty())
  9221. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9222. if (!Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_r))
  9223. CmdArgs.push_back("-pie");
  9224. if (Args.hasArg(options::OPT_rdynamic))
  9225. CmdArgs.push_back("-export-dynamic");
  9226. if (Args.hasArg(options::OPT_s))
  9227. CmdArgs.push_back("-s");
  9228. if (Args.hasArg(options::OPT_r))
  9229. CmdArgs.push_back("-r");
  9230. else
  9231. CmdArgs.push_back("--build-id");
  9232. if (!Args.hasArg(options::OPT_static))
  9233. CmdArgs.push_back("--eh-frame-hdr");
  9234. if (Args.hasArg(options::OPT_static))
  9235. CmdArgs.push_back("-Bstatic");
  9236. else if (Args.hasArg(options::OPT_shared))
  9237. CmdArgs.push_back("-shared");
  9238. if (!Args.hasArg(options::OPT_static)) {
  9239. if (Args.hasArg(options::OPT_rdynamic))
  9240. CmdArgs.push_back("-export-dynamic");
  9241. if (!Args.hasArg(options::OPT_shared)) {
  9242. CmdArgs.push_back("-dynamic-linker");
  9243. CmdArgs.push_back(Args.MakeArgString(D.DyldPrefix + "ld.so.1"));
  9244. }
  9245. }
  9246. CmdArgs.push_back("-o");
  9247. CmdArgs.push_back(Output.getFilename());
  9248. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9249. if (!Args.hasArg(options::OPT_shared)) {
  9250. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
  9251. }
  9252. }
  9253. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9254. Args.AddAllArgs(CmdArgs, options::OPT_u);
  9255. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  9256. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  9257. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9258. if (Args.hasArg(options::OPT_static))
  9259. CmdArgs.push_back("-Bdynamic");
  9260. if (D.CCCIsCXX()) {
  9261. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  9262. !Args.hasArg(options::OPT_static);
  9263. if (OnlyLibstdcxxStatic)
  9264. CmdArgs.push_back("-Bstatic");
  9265. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  9266. if (OnlyLibstdcxxStatic)
  9267. CmdArgs.push_back("-Bdynamic");
  9268. CmdArgs.push_back("-lm");
  9269. }
  9270. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  9271. if (Args.hasArg(options::OPT_pthread) ||
  9272. Args.hasArg(options::OPT_pthreads))
  9273. CmdArgs.push_back("-lpthread");
  9274. if (Args.hasArg(options::OPT_fsplit_stack))
  9275. CmdArgs.push_back("--wrap=pthread_create");
  9276. CmdArgs.push_back("-lc");
  9277. }
  9278. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9279. }
  9280. void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9281. const InputInfo &Output,
  9282. const InputInfoList &Inputs,
  9283. const ArgList &Args,
  9284. const char *LinkingOutput) const {
  9285. claimNoWarnArgs(Args);
  9286. ArgStringList CmdArgs;
  9287. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9288. CmdArgs.push_back("-o");
  9289. CmdArgs.push_back(Output.getFilename());
  9290. for (const auto &II : Inputs)
  9291. CmdArgs.push_back(II.getFilename());
  9292. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  9293. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9294. }
  9295. void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9296. const InputInfo &Output,
  9297. const InputInfoList &Inputs,
  9298. const ArgList &Args,
  9299. const char *LinkingOutput) const {
  9300. const Driver &D = getToolChain().getDriver();
  9301. ArgStringList CmdArgs;
  9302. if (Output.isFilename()) {
  9303. CmdArgs.push_back("-o");
  9304. CmdArgs.push_back(Output.getFilename());
  9305. } else {
  9306. assert(Output.isNothing() && "Invalid output.");
  9307. }
  9308. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9309. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  9310. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  9311. CmdArgs.push_back(
  9312. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  9313. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  9314. }
  9315. Args.AddAllArgs(CmdArgs,
  9316. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  9317. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  9318. getToolChain().addProfileRTLibs(Args, CmdArgs);
  9319. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9320. if (D.CCCIsCXX()) {
  9321. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  9322. CmdArgs.push_back("-lm");
  9323. }
  9324. }
  9325. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9326. if (Args.hasArg(options::OPT_pthread))
  9327. CmdArgs.push_back("-lpthread");
  9328. CmdArgs.push_back("-lc");
  9329. CmdArgs.push_back("-lCompilerRT-Generic");
  9330. CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
  9331. CmdArgs.push_back(
  9332. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  9333. }
  9334. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  9335. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9336. }
  9337. /// DragonFly Tools
  9338. // For now, DragonFly Assemble does just about the same as for
  9339. // FreeBSD, but this may change soon.
  9340. void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9341. const InputInfo &Output,
  9342. const InputInfoList &Inputs,
  9343. const ArgList &Args,
  9344. const char *LinkingOutput) const {
  9345. claimNoWarnArgs(Args);
  9346. ArgStringList CmdArgs;
  9347. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  9348. // instruct as in the base system to assemble 32-bit code.
  9349. if (getToolChain().getArch() == llvm::Triple::x86)
  9350. CmdArgs.push_back("--32");
  9351. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9352. CmdArgs.push_back("-o");
  9353. CmdArgs.push_back(Output.getFilename());
  9354. for (const auto &II : Inputs)
  9355. CmdArgs.push_back(II.getFilename());
  9356. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  9357. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9358. }
  9359. void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9360. const InputInfo &Output,
  9361. const InputInfoList &Inputs,
  9362. const ArgList &Args,
  9363. const char *LinkingOutput) const {
  9364. const Driver &D = getToolChain().getDriver();
  9365. ArgStringList CmdArgs;
  9366. if (!D.SysRoot.empty())
  9367. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9368. CmdArgs.push_back("--eh-frame-hdr");
  9369. if (Args.hasArg(options::OPT_static)) {
  9370. CmdArgs.push_back("-Bstatic");
  9371. } else {
  9372. if (Args.hasArg(options::OPT_rdynamic))
  9373. CmdArgs.push_back("-export-dynamic");
  9374. if (Args.hasArg(options::OPT_shared))
  9375. CmdArgs.push_back("-Bshareable");
  9376. else {
  9377. CmdArgs.push_back("-dynamic-linker");
  9378. CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
  9379. }
  9380. CmdArgs.push_back("--hash-style=gnu");
  9381. CmdArgs.push_back("--enable-new-dtags");
  9382. }
  9383. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  9384. // instruct ld in the base system to link 32-bit code.
  9385. if (getToolChain().getArch() == llvm::Triple::x86) {
  9386. CmdArgs.push_back("-m");
  9387. CmdArgs.push_back("elf_i386");
  9388. }
  9389. if (Output.isFilename()) {
  9390. CmdArgs.push_back("-o");
  9391. CmdArgs.push_back(Output.getFilename());
  9392. } else {
  9393. assert(Output.isNothing() && "Invalid output.");
  9394. }
  9395. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9396. if (!Args.hasArg(options::OPT_shared)) {
  9397. if (Args.hasArg(options::OPT_pg))
  9398. CmdArgs.push_back(
  9399. Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
  9400. else {
  9401. if (Args.hasArg(options::OPT_pie))
  9402. CmdArgs.push_back(
  9403. Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
  9404. else
  9405. CmdArgs.push_back(
  9406. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  9407. }
  9408. }
  9409. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  9410. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9411. CmdArgs.push_back(
  9412. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  9413. else
  9414. CmdArgs.push_back(
  9415. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  9416. }
  9417. Args.AddAllArgs(CmdArgs,
  9418. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  9419. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  9420. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9421. CmdArgs.push_back("-L/usr/lib/gcc50");
  9422. if (!Args.hasArg(options::OPT_static)) {
  9423. CmdArgs.push_back("-rpath");
  9424. CmdArgs.push_back("/usr/lib/gcc50");
  9425. }
  9426. if (D.CCCIsCXX()) {
  9427. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  9428. CmdArgs.push_back("-lm");
  9429. }
  9430. if (Args.hasArg(options::OPT_pthread))
  9431. CmdArgs.push_back("-lpthread");
  9432. if (!Args.hasArg(options::OPT_nolibc)) {
  9433. CmdArgs.push_back("-lc");
  9434. }
  9435. if (Args.hasArg(options::OPT_static) ||
  9436. Args.hasArg(options::OPT_static_libgcc)) {
  9437. CmdArgs.push_back("-lgcc");
  9438. CmdArgs.push_back("-lgcc_eh");
  9439. } else {
  9440. if (Args.hasArg(options::OPT_shared_libgcc)) {
  9441. CmdArgs.push_back("-lgcc_pic");
  9442. if (!Args.hasArg(options::OPT_shared))
  9443. CmdArgs.push_back("-lgcc");
  9444. } else {
  9445. CmdArgs.push_back("-lgcc");
  9446. CmdArgs.push_back("--as-needed");
  9447. CmdArgs.push_back("-lgcc_pic");
  9448. CmdArgs.push_back("--no-as-needed");
  9449. }
  9450. }
  9451. }
  9452. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9453. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9454. CmdArgs.push_back(
  9455. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  9456. else
  9457. CmdArgs.push_back(
  9458. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  9459. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  9460. }
  9461. getToolChain().addProfileRTLibs(Args, CmdArgs);
  9462. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  9463. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9464. }
  9465. // Try to find Exe from a Visual Studio distribution. This first tries to find
  9466. // an installed copy of Visual Studio and, failing that, looks in the PATH,
  9467. // making sure that whatever executable that's found is not a same-named exe
  9468. // from clang itself to prevent clang from falling back to itself.
  9469. static std::string FindVisualStudioExecutable(const ToolChain &TC,
  9470. const char *Exe,
  9471. const char *ClangProgramPath) {
  9472. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  9473. std::string visualStudioBinDir;
  9474. if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
  9475. visualStudioBinDir)) {
  9476. SmallString<128> FilePath(visualStudioBinDir);
  9477. llvm::sys::path::append(FilePath, Exe);
  9478. if (llvm::sys::fs::can_execute(FilePath.c_str()))
  9479. return FilePath.str();
  9480. }
  9481. return Exe;
  9482. }
  9483. void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9484. const InputInfo &Output,
  9485. const InputInfoList &Inputs,
  9486. const ArgList &Args,
  9487. const char *LinkingOutput) const {
  9488. ArgStringList CmdArgs;
  9489. const ToolChain &TC = getToolChain();
  9490. assert((Output.isFilename() || Output.isNothing()) && "invalid output");
  9491. if (Output.isFilename())
  9492. CmdArgs.push_back(
  9493. Args.MakeArgString(std::string("-out:") + Output.getFilename()));
  9494. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
  9495. !C.getDriver().IsCLMode())
  9496. CmdArgs.push_back("-defaultlib:libcmt");
  9497. if (!llvm::sys::Process::GetEnv("LIB")) {
  9498. // If the VC environment hasn't been configured (perhaps because the user
  9499. // did not run vcvarsall), try to build a consistent link environment. If
  9500. // the environment variable is set however, assume the user knows what
  9501. // they're doing.
  9502. std::string VisualStudioDir;
  9503. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  9504. if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
  9505. SmallString<128> LibDir(VisualStudioDir);
  9506. llvm::sys::path::append(LibDir, "VC", "lib");
  9507. switch (MSVC.getArch()) {
  9508. case llvm::Triple::x86:
  9509. // x86 just puts the libraries directly in lib
  9510. break;
  9511. case llvm::Triple::x86_64:
  9512. llvm::sys::path::append(LibDir, "amd64");
  9513. break;
  9514. case llvm::Triple::arm:
  9515. llvm::sys::path::append(LibDir, "arm");
  9516. break;
  9517. default:
  9518. break;
  9519. }
  9520. CmdArgs.push_back(
  9521. Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
  9522. if (MSVC.useUniversalCRT(VisualStudioDir)) {
  9523. std::string UniversalCRTLibPath;
  9524. if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
  9525. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  9526. UniversalCRTLibPath));
  9527. }
  9528. }
  9529. std::string WindowsSdkLibPath;
  9530. if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
  9531. CmdArgs.push_back(
  9532. Args.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath));
  9533. }
  9534. if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
  9535. for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
  9536. CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
  9537. CmdArgs.push_back("-nologo");
  9538. if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
  9539. options::OPT__SLASH_Zd))
  9540. CmdArgs.push_back("-debug");
  9541. bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
  9542. options::OPT_shared);
  9543. if (DLL) {
  9544. CmdArgs.push_back(Args.MakeArgString("-dll"));
  9545. SmallString<128> ImplibName(Output.getFilename());
  9546. llvm::sys::path::replace_extension(ImplibName, "lib");
  9547. CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
  9548. }
  9549. if (TC.getSanitizerArgs().needsAsanRt()) {
  9550. CmdArgs.push_back(Args.MakeArgString("-debug"));
  9551. CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
  9552. if (TC.getSanitizerArgs().needsSharedAsanRt() ||
  9553. Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
  9554. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  9555. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  9556. // Make sure the dynamic runtime thunk is not optimized out at link time
  9557. // to ensure proper SEH handling.
  9558. CmdArgs.push_back(Args.MakeArgString(
  9559. TC.getArch() == llvm::Triple::x86
  9560. ? "-include:___asan_seh_interceptor"
  9561. : "-include:__asan_seh_interceptor"));
  9562. // Make sure the linker consider all object files from the dynamic runtime
  9563. // thunk.
  9564. CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") +
  9565. TC.getCompilerRT(Args, "asan_dynamic_runtime_thunk")));
  9566. } else if (DLL) {
  9567. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  9568. } else {
  9569. for (const auto &Lib : {"asan", "asan_cxx"}) {
  9570. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  9571. // Make sure the linker consider all object files from the static lib.
  9572. // This is necessary because instrumented dlls need access to all the
  9573. // interface exported by the static lib in the main executable.
  9574. CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") +
  9575. TC.getCompilerRT(Args, Lib)));
  9576. }
  9577. }
  9578. }
  9579. Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
  9580. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  9581. options::OPT_fno_openmp, false)) {
  9582. CmdArgs.push_back("-nodefaultlib:vcomp.lib");
  9583. CmdArgs.push_back("-nodefaultlib:vcompd.lib");
  9584. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  9585. TC.getDriver().Dir + "/../lib"));
  9586. switch (TC.getDriver().getOpenMPRuntime(Args)) {
  9587. case Driver::OMPRT_OMP:
  9588. CmdArgs.push_back("-defaultlib:libomp.lib");
  9589. break;
  9590. case Driver::OMPRT_IOMP5:
  9591. CmdArgs.push_back("-defaultlib:libiomp5md.lib");
  9592. break;
  9593. case Driver::OMPRT_GOMP:
  9594. break;
  9595. case Driver::OMPRT_Unknown:
  9596. // Already diagnosed.
  9597. break;
  9598. }
  9599. }
  9600. // Add compiler-rt lib in case if it was explicitly
  9601. // specified as an argument for --rtlib option.
  9602. if (!Args.hasArg(options::OPT_nostdlib)) {
  9603. AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
  9604. }
  9605. // Add filenames, libraries, and other linker inputs.
  9606. for (const auto &Input : Inputs) {
  9607. if (Input.isFilename()) {
  9608. CmdArgs.push_back(Input.getFilename());
  9609. continue;
  9610. }
  9611. const Arg &A = Input.getInputArg();
  9612. // Render -l options differently for the MSVC linker.
  9613. if (A.getOption().matches(options::OPT_l)) {
  9614. StringRef Lib = A.getValue();
  9615. const char *LinkLibArg;
  9616. if (Lib.endswith(".lib"))
  9617. LinkLibArg = Args.MakeArgString(Lib);
  9618. else
  9619. LinkLibArg = Args.MakeArgString(Lib + ".lib");
  9620. CmdArgs.push_back(LinkLibArg);
  9621. continue;
  9622. }
  9623. // Otherwise, this is some other kind of linker input option like -Wl, -z,
  9624. // or -L. Render it, even if MSVC doesn't understand it.
  9625. A.renderAsInput(Args, CmdArgs);
  9626. }
  9627. TC.addProfileRTLibs(Args, CmdArgs);
  9628. // We need to special case some linker paths. In the case of lld, we need to
  9629. // translate 'lld' into 'lld-link', and in the case of the regular msvc
  9630. // linker, we need to use a special search algorithm.
  9631. llvm::SmallString<128> linkPath;
  9632. StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
  9633. if (Linker.equals_lower("lld"))
  9634. Linker = "lld-link";
  9635. if (Linker.equals_lower("link")) {
  9636. // If we're using the MSVC linker, it's not sufficient to just use link
  9637. // from the program PATH, because other environments like GnuWin32 install
  9638. // their own link.exe which may come first.
  9639. linkPath = FindVisualStudioExecutable(TC, "link.exe",
  9640. C.getDriver().getClangProgramPath());
  9641. } else {
  9642. linkPath = Linker;
  9643. llvm::sys::path::replace_extension(linkPath, "exe");
  9644. linkPath = TC.GetProgramPath(linkPath.c_str());
  9645. }
  9646. const char *Exec = Args.MakeArgString(linkPath);
  9647. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9648. }
  9649. void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  9650. const InputInfo &Output,
  9651. const InputInfoList &Inputs,
  9652. const ArgList &Args,
  9653. const char *LinkingOutput) const {
  9654. C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
  9655. }
  9656. std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
  9657. Compilation &C, const JobAction &JA, const InputInfo &Output,
  9658. const InputInfoList &Inputs, const ArgList &Args,
  9659. const char *LinkingOutput) const {
  9660. ArgStringList CmdArgs;
  9661. CmdArgs.push_back("/nologo");
  9662. CmdArgs.push_back("/c"); // Compile only.
  9663. CmdArgs.push_back("/W0"); // No warnings.
  9664. // The goal is to be able to invoke this tool correctly based on
  9665. // any flag accepted by clang-cl.
  9666. // These are spelled the same way in clang and cl.exe,.
  9667. Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
  9668. // Optimization level.
  9669. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
  9670. CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
  9671. : "/Oi-");
  9672. if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
  9673. if (A->getOption().getID() == options::OPT_O0) {
  9674. CmdArgs.push_back("/Od");
  9675. } else {
  9676. CmdArgs.push_back("/Og");
  9677. StringRef OptLevel = A->getValue();
  9678. if (OptLevel == "s" || OptLevel == "z")
  9679. CmdArgs.push_back("/Os");
  9680. else
  9681. CmdArgs.push_back("/Ot");
  9682. CmdArgs.push_back("/Ob2");
  9683. }
  9684. }
  9685. if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  9686. options::OPT_fno_omit_frame_pointer))
  9687. CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
  9688. ? "/Oy"
  9689. : "/Oy-");
  9690. if (!Args.hasArg(options::OPT_fwritable_strings))
  9691. CmdArgs.push_back("/GF");
  9692. // Flags for which clang-cl has an alias.
  9693. // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
  9694. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  9695. /*default=*/false))
  9696. CmdArgs.push_back("/GR-");
  9697. if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
  9698. /*default=*/false))
  9699. CmdArgs.push_back("/GS-");
  9700. if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
  9701. options::OPT_fno_function_sections))
  9702. CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
  9703. ? "/Gy"
  9704. : "/Gy-");
  9705. if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
  9706. options::OPT_fno_data_sections))
  9707. CmdArgs.push_back(
  9708. A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
  9709. if (Args.hasArg(options::OPT_fsyntax_only))
  9710. CmdArgs.push_back("/Zs");
  9711. if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
  9712. options::OPT__SLASH_Z7))
  9713. CmdArgs.push_back("/Z7");
  9714. std::vector<std::string> Includes =
  9715. Args.getAllArgValues(options::OPT_include);
  9716. for (const auto &Include : Includes)
  9717. CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
  9718. // Flags that can simply be passed through.
  9719. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
  9720. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
  9721. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
  9722. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
  9723. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
  9724. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
  9725. // The order of these flags is relevant, so pick the last one.
  9726. if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
  9727. options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
  9728. A->render(Args, CmdArgs);
  9729. // Use MSVC's default threadsafe statics behaviour unless there was a flag.
  9730. if (Arg *A = Args.getLastArg(options::OPT_fthreadsafe_statics,
  9731. options::OPT_fno_threadsafe_statics)) {
  9732. CmdArgs.push_back(A->getOption().getID() == options::OPT_fthreadsafe_statics
  9733. ? "/Zc:threadSafeInit"
  9734. : "/Zc:threadSafeInit-");
  9735. }
  9736. // Pass through all unknown arguments so that the fallback command can see
  9737. // them too.
  9738. Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
  9739. // Input filename.
  9740. assert(Inputs.size() == 1);
  9741. const InputInfo &II = Inputs[0];
  9742. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  9743. CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
  9744. if (II.isFilename())
  9745. CmdArgs.push_back(II.getFilename());
  9746. else
  9747. II.getInputArg().renderAsInput(Args, CmdArgs);
  9748. // Output filename.
  9749. assert(Output.getType() == types::TY_Object);
  9750. const char *Fo =
  9751. Args.MakeArgString(std::string("/Fo") + Output.getFilename());
  9752. CmdArgs.push_back(Fo);
  9753. const Driver &D = getToolChain().getDriver();
  9754. std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
  9755. D.getClangProgramPath());
  9756. return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9757. CmdArgs, Inputs);
  9758. }
  9759. /// MinGW Tools
  9760. void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9761. const InputInfo &Output,
  9762. const InputInfoList &Inputs,
  9763. const ArgList &Args,
  9764. const char *LinkingOutput) const {
  9765. claimNoWarnArgs(Args);
  9766. ArgStringList CmdArgs;
  9767. if (getToolChain().getArch() == llvm::Triple::x86) {
  9768. CmdArgs.push_back("--32");
  9769. } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
  9770. CmdArgs.push_back("--64");
  9771. }
  9772. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9773. CmdArgs.push_back("-o");
  9774. CmdArgs.push_back(Output.getFilename());
  9775. for (const auto &II : Inputs)
  9776. CmdArgs.push_back(II.getFilename());
  9777. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  9778. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9779. if (Args.hasArg(options::OPT_gsplit_dwarf))
  9780. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  9781. SplitDebugName(Args, Inputs[0]));
  9782. }
  9783. void MinGW::Linker::AddLibGCC(const ArgList &Args,
  9784. ArgStringList &CmdArgs) const {
  9785. if (Args.hasArg(options::OPT_mthreads))
  9786. CmdArgs.push_back("-lmingwthrd");
  9787. CmdArgs.push_back("-lmingw32");
  9788. // Make use of compiler-rt if --rtlib option is used
  9789. ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
  9790. if (RLT == ToolChain::RLT_Libgcc) {
  9791. bool Static = Args.hasArg(options::OPT_static_libgcc) ||
  9792. Args.hasArg(options::OPT_static);
  9793. bool Shared = Args.hasArg(options::OPT_shared);
  9794. bool CXX = getToolChain().getDriver().CCCIsCXX();
  9795. if (Static || (!CXX && !Shared)) {
  9796. CmdArgs.push_back("-lgcc");
  9797. CmdArgs.push_back("-lgcc_eh");
  9798. } else {
  9799. CmdArgs.push_back("-lgcc_s");
  9800. CmdArgs.push_back("-lgcc");
  9801. }
  9802. } else {
  9803. AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
  9804. }
  9805. CmdArgs.push_back("-lmoldname");
  9806. CmdArgs.push_back("-lmingwex");
  9807. CmdArgs.push_back("-lmsvcrt");
  9808. }
  9809. void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9810. const InputInfo &Output,
  9811. const InputInfoList &Inputs,
  9812. const ArgList &Args,
  9813. const char *LinkingOutput) const {
  9814. const ToolChain &TC = getToolChain();
  9815. const Driver &D = TC.getDriver();
  9816. // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  9817. ArgStringList CmdArgs;
  9818. // Silence warning for "clang -g foo.o -o foo"
  9819. Args.ClaimAllArgs(options::OPT_g_Group);
  9820. // and "clang -emit-llvm foo.o -o foo"
  9821. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9822. // and for "clang -w foo.o -o foo". Other warning options are already
  9823. // handled somewhere else.
  9824. Args.ClaimAllArgs(options::OPT_w);
  9825. StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
  9826. if (LinkerName.equals_lower("lld")) {
  9827. CmdArgs.push_back("-flavor");
  9828. CmdArgs.push_back("gnu");
  9829. } else if (!LinkerName.equals_lower("ld")) {
  9830. D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
  9831. }
  9832. if (!D.SysRoot.empty())
  9833. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9834. if (Args.hasArg(options::OPT_s))
  9835. CmdArgs.push_back("-s");
  9836. CmdArgs.push_back("-m");
  9837. if (TC.getArch() == llvm::Triple::x86)
  9838. CmdArgs.push_back("i386pe");
  9839. if (TC.getArch() == llvm::Triple::x86_64)
  9840. CmdArgs.push_back("i386pep");
  9841. if (TC.getArch() == llvm::Triple::arm)
  9842. CmdArgs.push_back("thumb2pe");
  9843. if (Args.hasArg(options::OPT_mwindows)) {
  9844. CmdArgs.push_back("--subsystem");
  9845. CmdArgs.push_back("windows");
  9846. } else if (Args.hasArg(options::OPT_mconsole)) {
  9847. CmdArgs.push_back("--subsystem");
  9848. CmdArgs.push_back("console");
  9849. }
  9850. if (Args.hasArg(options::OPT_static))
  9851. CmdArgs.push_back("-Bstatic");
  9852. else {
  9853. if (Args.hasArg(options::OPT_mdll))
  9854. CmdArgs.push_back("--dll");
  9855. else if (Args.hasArg(options::OPT_shared))
  9856. CmdArgs.push_back("--shared");
  9857. CmdArgs.push_back("-Bdynamic");
  9858. if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
  9859. CmdArgs.push_back("-e");
  9860. if (TC.getArch() == llvm::Triple::x86)
  9861. CmdArgs.push_back("_DllMainCRTStartup@12");
  9862. else
  9863. CmdArgs.push_back("DllMainCRTStartup");
  9864. CmdArgs.push_back("--enable-auto-image-base");
  9865. }
  9866. }
  9867. CmdArgs.push_back("-o");
  9868. CmdArgs.push_back(Output.getFilename());
  9869. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9870. // FIXME: add -N, -n flags
  9871. Args.AddLastArg(CmdArgs, options::OPT_r);
  9872. Args.AddLastArg(CmdArgs, options::OPT_s);
  9873. Args.AddLastArg(CmdArgs, options::OPT_t);
  9874. Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
  9875. Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
  9876. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9877. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
  9878. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
  9879. } else {
  9880. if (Args.hasArg(options::OPT_municode))
  9881. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
  9882. else
  9883. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
  9884. }
  9885. if (Args.hasArg(options::OPT_pg))
  9886. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
  9887. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  9888. }
  9889. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9890. TC.AddFilePathLibArgs(Args, CmdArgs);
  9891. AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
  9892. // TODO: Add ASan stuff here
  9893. // TODO: Add profile stuff here
  9894. if (D.CCCIsCXX() &&
  9895. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9896. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  9897. !Args.hasArg(options::OPT_static);
  9898. if (OnlyLibstdcxxStatic)
  9899. CmdArgs.push_back("-Bstatic");
  9900. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  9901. if (OnlyLibstdcxxStatic)
  9902. CmdArgs.push_back("-Bdynamic");
  9903. }
  9904. if (!Args.hasArg(options::OPT_nostdlib)) {
  9905. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  9906. if (Args.hasArg(options::OPT_static))
  9907. CmdArgs.push_back("--start-group");
  9908. if (Args.hasArg(options::OPT_fstack_protector) ||
  9909. Args.hasArg(options::OPT_fstack_protector_strong) ||
  9910. Args.hasArg(options::OPT_fstack_protector_all)) {
  9911. CmdArgs.push_back("-lssp_nonshared");
  9912. CmdArgs.push_back("-lssp");
  9913. }
  9914. if (Args.hasArg(options::OPT_fopenmp))
  9915. CmdArgs.push_back("-lgomp");
  9916. AddLibGCC(Args, CmdArgs);
  9917. if (Args.hasArg(options::OPT_pg))
  9918. CmdArgs.push_back("-lgmon");
  9919. if (Args.hasArg(options::OPT_pthread))
  9920. CmdArgs.push_back("-lpthread");
  9921. // add system libraries
  9922. if (Args.hasArg(options::OPT_mwindows)) {
  9923. CmdArgs.push_back("-lgdi32");
  9924. CmdArgs.push_back("-lcomdlg32");
  9925. }
  9926. CmdArgs.push_back("-ladvapi32");
  9927. CmdArgs.push_back("-lshell32");
  9928. CmdArgs.push_back("-luser32");
  9929. CmdArgs.push_back("-lkernel32");
  9930. if (Args.hasArg(options::OPT_static))
  9931. CmdArgs.push_back("--end-group");
  9932. else if (!LinkerName.equals_lower("lld"))
  9933. AddLibGCC(Args, CmdArgs);
  9934. }
  9935. if (!Args.hasArg(options::OPT_nostartfiles)) {
  9936. // Add crtfastmath.o if available and fast math is enabled.
  9937. TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  9938. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  9939. }
  9940. }
  9941. const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
  9942. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9943. }
  9944. /// XCore Tools
  9945. // We pass assemble and link construction to the xcc tool.
  9946. void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9947. const InputInfo &Output,
  9948. const InputInfoList &Inputs,
  9949. const ArgList &Args,
  9950. const char *LinkingOutput) const {
  9951. claimNoWarnArgs(Args);
  9952. ArgStringList CmdArgs;
  9953. CmdArgs.push_back("-o");
  9954. CmdArgs.push_back(Output.getFilename());
  9955. CmdArgs.push_back("-c");
  9956. if (Args.hasArg(options::OPT_v))
  9957. CmdArgs.push_back("-v");
  9958. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  9959. if (!A->getOption().matches(options::OPT_g0))
  9960. CmdArgs.push_back("-g");
  9961. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  9962. false))
  9963. CmdArgs.push_back("-fverbose-asm");
  9964. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9965. for (const auto &II : Inputs)
  9966. CmdArgs.push_back(II.getFilename());
  9967. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  9968. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9969. }
  9970. void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9971. const InputInfo &Output,
  9972. const InputInfoList &Inputs,
  9973. const ArgList &Args,
  9974. const char *LinkingOutput) const {
  9975. ArgStringList CmdArgs;
  9976. if (Output.isFilename()) {
  9977. CmdArgs.push_back("-o");
  9978. CmdArgs.push_back(Output.getFilename());
  9979. } else {
  9980. assert(Output.isNothing() && "Invalid output.");
  9981. }
  9982. if (Args.hasArg(options::OPT_v))
  9983. CmdArgs.push_back("-v");
  9984. // Pass -fexceptions through to the linker if it was present.
  9985. if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  9986. false))
  9987. CmdArgs.push_back("-fexceptions");
  9988. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  9989. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  9990. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9991. }
  9992. void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9993. const InputInfo &Output,
  9994. const InputInfoList &Inputs,
  9995. const ArgList &Args,
  9996. const char *LinkingOutput) const {
  9997. claimNoWarnArgs(Args);
  9998. const auto &TC =
  9999. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  10000. ArgStringList CmdArgs;
  10001. const char *Exec;
  10002. switch (TC.getArch()) {
  10003. default:
  10004. llvm_unreachable("unsupported architecture");
  10005. case llvm::Triple::arm:
  10006. case llvm::Triple::thumb:
  10007. break;
  10008. case llvm::Triple::x86:
  10009. CmdArgs.push_back("--32");
  10010. break;
  10011. case llvm::Triple::x86_64:
  10012. CmdArgs.push_back("--64");
  10013. break;
  10014. }
  10015. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  10016. CmdArgs.push_back("-o");
  10017. CmdArgs.push_back(Output.getFilename());
  10018. for (const auto &Input : Inputs)
  10019. CmdArgs.push_back(Input.getFilename());
  10020. const std::string Assembler = TC.GetProgramPath("as");
  10021. Exec = Args.MakeArgString(Assembler);
  10022. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  10023. }
  10024. void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  10025. const InputInfo &Output,
  10026. const InputInfoList &Inputs,
  10027. const ArgList &Args,
  10028. const char *LinkingOutput) const {
  10029. const auto &TC =
  10030. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  10031. const llvm::Triple &T = TC.getTriple();
  10032. const Driver &D = TC.getDriver();
  10033. SmallString<128> EntryPoint;
  10034. ArgStringList CmdArgs;
  10035. const char *Exec;
  10036. // Silence warning for "clang -g foo.o -o foo"
  10037. Args.ClaimAllArgs(options::OPT_g_Group);
  10038. // and "clang -emit-llvm foo.o -o foo"
  10039. Args.ClaimAllArgs(options::OPT_emit_llvm);
  10040. // and for "clang -w foo.o -o foo"
  10041. Args.ClaimAllArgs(options::OPT_w);
  10042. // Other warning options are already handled somewhere else.
  10043. if (!D.SysRoot.empty())
  10044. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  10045. if (Args.hasArg(options::OPT_pie))
  10046. CmdArgs.push_back("-pie");
  10047. if (Args.hasArg(options::OPT_rdynamic))
  10048. CmdArgs.push_back("-export-dynamic");
  10049. if (Args.hasArg(options::OPT_s))
  10050. CmdArgs.push_back("--strip-all");
  10051. CmdArgs.push_back("-m");
  10052. switch (TC.getArch()) {
  10053. default:
  10054. llvm_unreachable("unsupported architecture");
  10055. case llvm::Triple::arm:
  10056. case llvm::Triple::thumb:
  10057. // FIXME: this is incorrect for WinCE
  10058. CmdArgs.push_back("thumb2pe");
  10059. break;
  10060. case llvm::Triple::x86:
  10061. CmdArgs.push_back("i386pe");
  10062. EntryPoint.append("_");
  10063. break;
  10064. case llvm::Triple::x86_64:
  10065. CmdArgs.push_back("i386pep");
  10066. break;
  10067. }
  10068. if (Args.hasArg(options::OPT_shared)) {
  10069. switch (T.getArch()) {
  10070. default:
  10071. llvm_unreachable("unsupported architecture");
  10072. case llvm::Triple::arm:
  10073. case llvm::Triple::thumb:
  10074. case llvm::Triple::x86_64:
  10075. EntryPoint.append("_DllMainCRTStartup");
  10076. break;
  10077. case llvm::Triple::x86:
  10078. EntryPoint.append("_DllMainCRTStartup@12");
  10079. break;
  10080. }
  10081. CmdArgs.push_back("-shared");
  10082. CmdArgs.push_back("-Bdynamic");
  10083. CmdArgs.push_back("--enable-auto-image-base");
  10084. CmdArgs.push_back("--entry");
  10085. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  10086. } else {
  10087. EntryPoint.append("mainCRTStartup");
  10088. CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
  10089. : "-Bdynamic");
  10090. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  10091. CmdArgs.push_back("--entry");
  10092. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  10093. }
  10094. // FIXME: handle subsystem
  10095. }
  10096. // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
  10097. CmdArgs.push_back("--allow-multiple-definition");
  10098. CmdArgs.push_back("-o");
  10099. CmdArgs.push_back(Output.getFilename());
  10100. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
  10101. SmallString<261> ImpLib(Output.getFilename());
  10102. llvm::sys::path::replace_extension(ImpLib, ".lib");
  10103. CmdArgs.push_back("--out-implib");
  10104. CmdArgs.push_back(Args.MakeArgString(ImpLib));
  10105. }
  10106. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  10107. const std::string CRTPath(D.SysRoot + "/usr/lib/");
  10108. const char *CRTBegin;
  10109. CRTBegin =
  10110. Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
  10111. CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
  10112. }
  10113. Args.AddAllArgs(CmdArgs, options::OPT_L);
  10114. TC.AddFilePathLibArgs(Args, CmdArgs);
  10115. AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
  10116. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  10117. !Args.hasArg(options::OPT_nodefaultlibs)) {
  10118. bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
  10119. !Args.hasArg(options::OPT_static);
  10120. if (StaticCXX)
  10121. CmdArgs.push_back("-Bstatic");
  10122. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  10123. if (StaticCXX)
  10124. CmdArgs.push_back("-Bdynamic");
  10125. }
  10126. if (!Args.hasArg(options::OPT_nostdlib)) {
  10127. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  10128. // TODO handle /MT[d] /MD[d]
  10129. CmdArgs.push_back("-lmsvcrt");
  10130. AddRunTimeLibs(TC, D, CmdArgs, Args);
  10131. }
  10132. }
  10133. if (TC.getSanitizerArgs().needsAsanRt()) {
  10134. // TODO handle /MT[d] /MD[d]
  10135. if (Args.hasArg(options::OPT_shared)) {
  10136. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  10137. } else {
  10138. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  10139. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  10140. // Make sure the dynamic runtime thunk is not optimized out at link time
  10141. // to ensure proper SEH handling.
  10142. CmdArgs.push_back(Args.MakeArgString("--undefined"));
  10143. CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
  10144. ? "___asan_seh_interceptor"
  10145. : "__asan_seh_interceptor"));
  10146. }
  10147. }
  10148. Exec = Args.MakeArgString(TC.GetLinkerPath());
  10149. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  10150. }
  10151. void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  10152. const InputInfo &Output,
  10153. const InputInfoList &Inputs,
  10154. const ArgList &Args,
  10155. const char *LinkingOutput) const {
  10156. ArgStringList CmdArgs;
  10157. assert(Inputs.size() == 1);
  10158. const InputInfo &II = Inputs[0];
  10159. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
  10160. II.getType() == types::TY_PP_CXX);
  10161. if (JA.getKind() == Action::PreprocessJobClass) {
  10162. Args.ClaimAllArgs();
  10163. CmdArgs.push_back("-E");
  10164. } else {
  10165. assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
  10166. CmdArgs.push_back("-S");
  10167. CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
  10168. }
  10169. CmdArgs.push_back("-DMYRIAD2");
  10170. // Append all -I, -iquote, -isystem paths, defines/undefines,
  10171. // 'f' flags, optimize flags, and warning options.
  10172. // These are spelled the same way in clang and moviCompile.
  10173. Args.AddAllArgsExcept(
  10174. CmdArgs,
  10175. {options::OPT_I_Group, options::OPT_clang_i_Group, options::OPT_std_EQ,
  10176. options::OPT_D, options::OPT_U, options::OPT_f_Group,
  10177. options::OPT_f_clang_Group, options::OPT_g_Group, options::OPT_M_Group,
  10178. options::OPT_O_Group, options::OPT_W_Group, options::OPT_mcpu_EQ},
  10179. {options::OPT_fno_split_dwarf_inlining});
  10180. Args.hasArg(options::OPT_fno_split_dwarf_inlining); // Claim it if present.
  10181. // If we're producing a dependency file, and assembly is the final action,
  10182. // then the name of the target in the dependency file should be the '.o'
  10183. // file, not the '.s' file produced by this step. For example, instead of
  10184. // /tmp/mumble.s: mumble.c .../someheader.h
  10185. // the filename on the lefthand side should be "mumble.o"
  10186. if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
  10187. C.getActions().size() == 1 &&
  10188. C.getActions()[0]->getKind() == Action::AssembleJobClass) {
  10189. Arg *A = Args.getLastArg(options::OPT_o);
  10190. if (A) {
  10191. CmdArgs.push_back("-MT");
  10192. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  10193. }
  10194. }
  10195. CmdArgs.push_back(II.getFilename());
  10196. CmdArgs.push_back("-o");
  10197. CmdArgs.push_back(Output.getFilename());
  10198. std::string Exec =
  10199. Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
  10200. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  10201. CmdArgs, Inputs));
  10202. }
  10203. void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  10204. const InputInfo &Output,
  10205. const InputInfoList &Inputs,
  10206. const ArgList &Args,
  10207. const char *LinkingOutput) const {
  10208. ArgStringList CmdArgs;
  10209. assert(Inputs.size() == 1);
  10210. const InputInfo &II = Inputs[0];
  10211. assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
  10212. assert(Output.getType() == types::TY_Object);
  10213. CmdArgs.push_back("-no6thSlotCompression");
  10214. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  10215. if (CPUArg)
  10216. CmdArgs.push_back(
  10217. Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
  10218. CmdArgs.push_back("-noSPrefixing");
  10219. CmdArgs.push_back("-a"); // Mystery option.
  10220. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  10221. for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
  10222. A->claim();
  10223. CmdArgs.push_back(
  10224. Args.MakeArgString(std::string("-i:") + A->getValue(0)));
  10225. }
  10226. CmdArgs.push_back("-elf"); // Output format.
  10227. CmdArgs.push_back(II.getFilename());
  10228. CmdArgs.push_back(
  10229. Args.MakeArgString(std::string("-o:") + Output.getFilename()));
  10230. std::string Exec =
  10231. Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
  10232. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  10233. CmdArgs, Inputs));
  10234. }
  10235. void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  10236. const InputInfo &Output,
  10237. const InputInfoList &Inputs,
  10238. const ArgList &Args,
  10239. const char *LinkingOutput) const {
  10240. const auto &TC =
  10241. static_cast<const toolchains::MyriadToolChain &>(getToolChain());
  10242. const llvm::Triple &T = TC.getTriple();
  10243. ArgStringList CmdArgs;
  10244. bool UseStartfiles =
  10245. !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
  10246. bool UseDefaultLibs =
  10247. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
  10248. // Silence warning if the args contain both -nostdlib and -stdlib=.
  10249. Args.getLastArg(options::OPT_stdlib_EQ);
  10250. if (T.getArch() == llvm::Triple::sparc)
  10251. CmdArgs.push_back("-EB");
  10252. else // SHAVE assumes little-endian, and sparcel is expressly so.
  10253. CmdArgs.push_back("-EL");
  10254. // The remaining logic is mostly like gnutools::Linker::ConstructJob,
  10255. // but we never pass through a --sysroot option and various other bits.
  10256. // For example, there are no sanitizers (yet) nor gold linker.
  10257. // Eat some arguments that may be present but have no effect.
  10258. Args.ClaimAllArgs(options::OPT_g_Group);
  10259. Args.ClaimAllArgs(options::OPT_w);
  10260. Args.ClaimAllArgs(options::OPT_static_libgcc);
  10261. if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
  10262. CmdArgs.push_back("-s");
  10263. CmdArgs.push_back("-o");
  10264. CmdArgs.push_back(Output.getFilename());
  10265. if (UseStartfiles) {
  10266. // If you want startfiles, it means you want the builtin crti and crtbegin,
  10267. // but not crt0. Myriad link commands provide their own crt0.o as needed.
  10268. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
  10269. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  10270. }
  10271. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  10272. options::OPT_e, options::OPT_s, options::OPT_t,
  10273. options::OPT_Z_Flag, options::OPT_r});
  10274. TC.AddFilePathLibArgs(Args, CmdArgs);
  10275. bool NeedsSanitizerDeps = addSanitizerRuntimes(TC, Args, CmdArgs);
  10276. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  10277. if (UseDefaultLibs) {
  10278. if (NeedsSanitizerDeps)
  10279. linkSanitizerRuntimeDeps(TC, CmdArgs);
  10280. if (C.getDriver().CCCIsCXX()) {
  10281. if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) {
  10282. CmdArgs.push_back("-lc++");
  10283. CmdArgs.push_back("-lc++abi");
  10284. } else
  10285. CmdArgs.push_back("-lstdc++");
  10286. }
  10287. if (T.getOS() == llvm::Triple::RTEMS) {
  10288. CmdArgs.push_back("--start-group");
  10289. CmdArgs.push_back("-lc");
  10290. CmdArgs.push_back("-lgcc"); // circularly dependent on rtems
  10291. // You must provide your own "-L" option to enable finding these.
  10292. CmdArgs.push_back("-lrtemscpu");
  10293. CmdArgs.push_back("-lrtemsbsp");
  10294. CmdArgs.push_back("--end-group");
  10295. } else {
  10296. CmdArgs.push_back("-lc");
  10297. CmdArgs.push_back("-lgcc");
  10298. }
  10299. }
  10300. if (UseStartfiles) {
  10301. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  10302. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
  10303. }
  10304. std::string Exec =
  10305. Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
  10306. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  10307. CmdArgs, Inputs));
  10308. }
  10309. void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
  10310. const InputInfo &Output,
  10311. const InputInfoList &Inputs,
  10312. const ArgList &Args,
  10313. const char *LinkingOutput) const {
  10314. claimNoWarnArgs(Args);
  10315. ArgStringList CmdArgs;
  10316. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  10317. CmdArgs.push_back("-o");
  10318. CmdArgs.push_back(Output.getFilename());
  10319. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  10320. const InputInfo &Input = Inputs[0];
  10321. assert(Input.isFilename() && "Invalid input.");
  10322. CmdArgs.push_back(Input.getFilename());
  10323. const char *Exec =
  10324. Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
  10325. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  10326. }
  10327. static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
  10328. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  10329. if (SanArgs.needsUbsanRt()) {
  10330. CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
  10331. }
  10332. if (SanArgs.needsAsanRt()) {
  10333. CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
  10334. }
  10335. }
  10336. static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
  10337. const JobAction &JA, const InputInfo &Output,
  10338. const InputInfoList &Inputs,
  10339. const ArgList &Args,
  10340. const char *LinkingOutput) {
  10341. const toolchains::FreeBSD &ToolChain =
  10342. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  10343. const Driver &D = ToolChain.getDriver();
  10344. ArgStringList CmdArgs;
  10345. // Silence warning for "clang -g foo.o -o foo"
  10346. Args.ClaimAllArgs(options::OPT_g_Group);
  10347. // and "clang -emit-llvm foo.o -o foo"
  10348. Args.ClaimAllArgs(options::OPT_emit_llvm);
  10349. // and for "clang -w foo.o -o foo". Other warning options are already
  10350. // handled somewhere else.
  10351. Args.ClaimAllArgs(options::OPT_w);
  10352. if (!D.SysRoot.empty())
  10353. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  10354. if (Args.hasArg(options::OPT_pie))
  10355. CmdArgs.push_back("-pie");
  10356. if (Args.hasArg(options::OPT_rdynamic))
  10357. CmdArgs.push_back("-export-dynamic");
  10358. if (Args.hasArg(options::OPT_shared))
  10359. CmdArgs.push_back("--oformat=so");
  10360. if (Output.isFilename()) {
  10361. CmdArgs.push_back("-o");
  10362. CmdArgs.push_back(Output.getFilename());
  10363. } else {
  10364. assert(Output.isNothing() && "Invalid output.");
  10365. }
  10366. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  10367. Args.AddAllArgs(CmdArgs, options::OPT_L);
  10368. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  10369. Args.AddAllArgs(CmdArgs, options::OPT_e);
  10370. Args.AddAllArgs(CmdArgs, options::OPT_s);
  10371. Args.AddAllArgs(CmdArgs, options::OPT_t);
  10372. Args.AddAllArgs(CmdArgs, options::OPT_r);
  10373. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  10374. CmdArgs.push_back("--no-demangle");
  10375. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  10376. if (Args.hasArg(options::OPT_pthread)) {
  10377. CmdArgs.push_back("-lpthread");
  10378. }
  10379. const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
  10380. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  10381. }
  10382. static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
  10383. const JobAction &JA, const InputInfo &Output,
  10384. const InputInfoList &Inputs,
  10385. const ArgList &Args,
  10386. const char *LinkingOutput) {
  10387. const toolchains::FreeBSD &ToolChain =
  10388. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  10389. const Driver &D = ToolChain.getDriver();
  10390. ArgStringList CmdArgs;
  10391. // Silence warning for "clang -g foo.o -o foo"
  10392. Args.ClaimAllArgs(options::OPT_g_Group);
  10393. // and "clang -emit-llvm foo.o -o foo"
  10394. Args.ClaimAllArgs(options::OPT_emit_llvm);
  10395. // and for "clang -w foo.o -o foo". Other warning options are already
  10396. // handled somewhere else.
  10397. Args.ClaimAllArgs(options::OPT_w);
  10398. if (!D.SysRoot.empty())
  10399. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  10400. if (Args.hasArg(options::OPT_pie))
  10401. CmdArgs.push_back("-pie");
  10402. if (Args.hasArg(options::OPT_static)) {
  10403. CmdArgs.push_back("-Bstatic");
  10404. } else {
  10405. if (Args.hasArg(options::OPT_rdynamic))
  10406. CmdArgs.push_back("-export-dynamic");
  10407. CmdArgs.push_back("--eh-frame-hdr");
  10408. if (Args.hasArg(options::OPT_shared)) {
  10409. CmdArgs.push_back("-Bshareable");
  10410. } else {
  10411. CmdArgs.push_back("-dynamic-linker");
  10412. CmdArgs.push_back("/libexec/ld-elf.so.1");
  10413. }
  10414. CmdArgs.push_back("--enable-new-dtags");
  10415. }
  10416. if (Output.isFilename()) {
  10417. CmdArgs.push_back("-o");
  10418. CmdArgs.push_back(Output.getFilename());
  10419. } else {
  10420. assert(Output.isNothing() && "Invalid output.");
  10421. }
  10422. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  10423. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  10424. const char *crt1 = nullptr;
  10425. if (!Args.hasArg(options::OPT_shared)) {
  10426. if (Args.hasArg(options::OPT_pg))
  10427. crt1 = "gcrt1.o";
  10428. else if (Args.hasArg(options::OPT_pie))
  10429. crt1 = "Scrt1.o";
  10430. else
  10431. crt1 = "crt1.o";
  10432. }
  10433. if (crt1)
  10434. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  10435. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  10436. const char *crtbegin = nullptr;
  10437. if (Args.hasArg(options::OPT_static))
  10438. crtbegin = "crtbeginT.o";
  10439. else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  10440. crtbegin = "crtbeginS.o";
  10441. else
  10442. crtbegin = "crtbegin.o";
  10443. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  10444. }
  10445. Args.AddAllArgs(CmdArgs, options::OPT_L);
  10446. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  10447. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  10448. Args.AddAllArgs(CmdArgs, options::OPT_e);
  10449. Args.AddAllArgs(CmdArgs, options::OPT_s);
  10450. Args.AddAllArgs(CmdArgs, options::OPT_t);
  10451. Args.AddAllArgs(CmdArgs, options::OPT_r);
  10452. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  10453. CmdArgs.push_back("--no-demangle");
  10454. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  10455. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  10456. // For PS4, we always want to pass libm, libstdc++ and libkernel
  10457. // libraries for both C and C++ compilations.
  10458. CmdArgs.push_back("-lkernel");
  10459. if (D.CCCIsCXX()) {
  10460. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  10461. if (Args.hasArg(options::OPT_pg))
  10462. CmdArgs.push_back("-lm_p");
  10463. else
  10464. CmdArgs.push_back("-lm");
  10465. }
  10466. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  10467. // the default system libraries. Just mimic this for now.
  10468. if (Args.hasArg(options::OPT_pg))
  10469. CmdArgs.push_back("-lgcc_p");
  10470. else
  10471. CmdArgs.push_back("-lcompiler_rt");
  10472. if (Args.hasArg(options::OPT_static)) {
  10473. CmdArgs.push_back("-lstdc++");
  10474. } else if (Args.hasArg(options::OPT_pg)) {
  10475. CmdArgs.push_back("-lgcc_eh_p");
  10476. } else {
  10477. CmdArgs.push_back("--as-needed");
  10478. CmdArgs.push_back("-lstdc++");
  10479. CmdArgs.push_back("--no-as-needed");
  10480. }
  10481. if (Args.hasArg(options::OPT_pthread)) {
  10482. if (Args.hasArg(options::OPT_pg))
  10483. CmdArgs.push_back("-lpthread_p");
  10484. else
  10485. CmdArgs.push_back("-lpthread");
  10486. }
  10487. if (Args.hasArg(options::OPT_pg)) {
  10488. if (Args.hasArg(options::OPT_shared))
  10489. CmdArgs.push_back("-lc");
  10490. else {
  10491. if (Args.hasArg(options::OPT_static)) {
  10492. CmdArgs.push_back("--start-group");
  10493. CmdArgs.push_back("-lc_p");
  10494. CmdArgs.push_back("-lpthread_p");
  10495. CmdArgs.push_back("--end-group");
  10496. } else {
  10497. CmdArgs.push_back("-lc_p");
  10498. }
  10499. }
  10500. CmdArgs.push_back("-lgcc_p");
  10501. } else {
  10502. if (Args.hasArg(options::OPT_static)) {
  10503. CmdArgs.push_back("--start-group");
  10504. CmdArgs.push_back("-lc");
  10505. CmdArgs.push_back("-lpthread");
  10506. CmdArgs.push_back("--end-group");
  10507. } else {
  10508. CmdArgs.push_back("-lc");
  10509. }
  10510. CmdArgs.push_back("-lcompiler_rt");
  10511. }
  10512. if (Args.hasArg(options::OPT_static)) {
  10513. CmdArgs.push_back("-lstdc++");
  10514. } else if (Args.hasArg(options::OPT_pg)) {
  10515. CmdArgs.push_back("-lgcc_eh_p");
  10516. } else {
  10517. CmdArgs.push_back("--as-needed");
  10518. CmdArgs.push_back("-lstdc++");
  10519. CmdArgs.push_back("--no-as-needed");
  10520. }
  10521. }
  10522. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  10523. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  10524. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  10525. else
  10526. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  10527. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  10528. }
  10529. const char *Exec =
  10530. #ifdef LLVM_ON_WIN32
  10531. Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
  10532. #else
  10533. Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
  10534. #endif
  10535. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  10536. }
  10537. void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
  10538. const InputInfo &Output,
  10539. const InputInfoList &Inputs,
  10540. const ArgList &Args,
  10541. const char *LinkingOutput) const {
  10542. const toolchains::FreeBSD &ToolChain =
  10543. static_cast<const toolchains::FreeBSD &>(getToolChain());
  10544. const Driver &D = ToolChain.getDriver();
  10545. bool PS4Linker;
  10546. StringRef LinkerOptName;
  10547. if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
  10548. LinkerOptName = A->getValue();
  10549. if (LinkerOptName != "ps4" && LinkerOptName != "gold")
  10550. D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
  10551. }
  10552. if (LinkerOptName == "gold")
  10553. PS4Linker = false;
  10554. else if (LinkerOptName == "ps4")
  10555. PS4Linker = true;
  10556. else
  10557. PS4Linker = !Args.hasArg(options::OPT_shared);
  10558. if (PS4Linker)
  10559. ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  10560. else
  10561. ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  10562. }
  10563. void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  10564. const InputInfo &Output,
  10565. const InputInfoList &Inputs,
  10566. const ArgList &Args,
  10567. const char *LinkingOutput) const {
  10568. const auto &TC =
  10569. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  10570. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  10571. // Obtain architecture from the action.
  10572. CudaArch gpu_arch = StringToCudaArch(JA.getOffloadingArch());
  10573. assert(gpu_arch != CudaArch::UNKNOWN &&
  10574. "Device action expected to have an architecture.");
  10575. // Check that our installation's ptxas supports gpu_arch.
  10576. if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
  10577. TC.CudaInstallation.CheckCudaVersionSupportsArch(gpu_arch);
  10578. }
  10579. ArgStringList CmdArgs;
  10580. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
  10581. if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
  10582. options::OPT_no_cuda_noopt_device_debug, false)) {
  10583. // ptxas does not accept -g option if optimization is enabled, so
  10584. // we ignore the compiler's -O* options if we want debug info.
  10585. CmdArgs.push_back("-g");
  10586. CmdArgs.push_back("--dont-merge-basicblocks");
  10587. CmdArgs.push_back("--return-at-end");
  10588. } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  10589. // Map the -O we received to -O{0,1,2,3}.
  10590. //
  10591. // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
  10592. // default, so it may correspond more closely to the spirit of clang -O2.
  10593. // -O3 seems like the least-bad option when -Osomething is specified to
  10594. // clang but it isn't handled below.
  10595. StringRef OOpt = "3";
  10596. if (A->getOption().matches(options::OPT_O4) ||
  10597. A->getOption().matches(options::OPT_Ofast))
  10598. OOpt = "3";
  10599. else if (A->getOption().matches(options::OPT_O0))
  10600. OOpt = "0";
  10601. else if (A->getOption().matches(options::OPT_O)) {
  10602. // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
  10603. OOpt = llvm::StringSwitch<const char *>(A->getValue())
  10604. .Case("1", "1")
  10605. .Case("2", "2")
  10606. .Case("3", "3")
  10607. .Case("s", "2")
  10608. .Case("z", "2")
  10609. .Default("2");
  10610. }
  10611. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
  10612. } else {
  10613. // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
  10614. // to no optimizations, but ptxas's default is -O3.
  10615. CmdArgs.push_back("-O0");
  10616. }
  10617. CmdArgs.push_back("--gpu-name");
  10618. CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
  10619. CmdArgs.push_back("--output-file");
  10620. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  10621. for (const auto& II : Inputs)
  10622. CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
  10623. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
  10624. CmdArgs.push_back(Args.MakeArgString(A));
  10625. const char *Exec;
  10626. if (Arg *A = Args.getLastArg(options::OPT_ptxas_path_EQ))
  10627. Exec = A->getValue();
  10628. else
  10629. Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
  10630. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  10631. }
  10632. // All inputs to this linker must be from CudaDeviceActions, as we need to look
  10633. // at the Inputs' Actions in order to figure out which GPU architecture they
  10634. // correspond to.
  10635. void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  10636. const InputInfo &Output,
  10637. const InputInfoList &Inputs,
  10638. const ArgList &Args,
  10639. const char *LinkingOutput) const {
  10640. const auto &TC =
  10641. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  10642. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  10643. ArgStringList CmdArgs;
  10644. CmdArgs.push_back("--cuda");
  10645. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
  10646. CmdArgs.push_back(Args.MakeArgString("--create"));
  10647. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  10648. for (const auto& II : Inputs) {
  10649. auto *A = II.getAction();
  10650. assert(A->getInputs().size() == 1 &&
  10651. "Device offload action is expected to have a single input");
  10652. const char *gpu_arch_str = A->getOffloadingArch();
  10653. assert(gpu_arch_str &&
  10654. "Device action expected to have associated a GPU architecture!");
  10655. CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
  10656. // We need to pass an Arch of the form "sm_XX" for cubin files and
  10657. // "compute_XX" for ptx.
  10658. const char *Arch =
  10659. (II.getType() == types::TY_PP_Asm)
  10660. ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
  10661. : gpu_arch_str;
  10662. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
  10663. Arch + ",file=" + II.getFilename()));
  10664. }
  10665. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
  10666. CmdArgs.push_back(Args.MakeArgString(A));
  10667. const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
  10668. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  10669. }
  10670. void AVR::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  10671. const InputInfo &Output,
  10672. const InputInfoList &Inputs,
  10673. const ArgList &Args,
  10674. const char *LinkingOutput) const {
  10675. std::string Linker = getToolChain().GetProgramPath(getShortName());
  10676. ArgStringList CmdArgs;
  10677. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  10678. CmdArgs.push_back("-o");
  10679. CmdArgs.push_back(Output.getFilename());
  10680. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  10681. CmdArgs, Inputs));
  10682. }
  10683. // AVR tools end.