CodeGenModule.cpp 208 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This coordinates the per-module state used while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenModule.h"
  13. #include "CGBlocks.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCall.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGObjCRuntime.h"
  19. #include "CGOpenCLRuntime.h"
  20. #include "CGOpenMPRuntime.h"
  21. #include "CGOpenMPRuntimeNVPTX.h"
  22. #include "CodeGenFunction.h"
  23. #include "CodeGenPGO.h"
  24. #include "ConstantEmitter.h"
  25. #include "CoverageMappingGen.h"
  26. #include "TargetInfo.h"
  27. #include "clang/AST/ASTContext.h"
  28. #include "clang/AST/CharUnits.h"
  29. #include "clang/AST/DeclCXX.h"
  30. #include "clang/AST/DeclObjC.h"
  31. #include "clang/AST/DeclTemplate.h"
  32. #include "clang/AST/Mangle.h"
  33. #include "clang/AST/RecordLayout.h"
  34. #include "clang/AST/RecursiveASTVisitor.h"
  35. #include "clang/AST/StmtVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/CodeGenOptions.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/Module.h"
  41. #include "clang/Basic/SourceManager.h"
  42. #include "clang/Basic/TargetInfo.h"
  43. #include "clang/Basic/Version.h"
  44. #include "clang/CodeGen/ConstantInitBuilder.h"
  45. #include "clang/Frontend/FrontendDiagnostic.h"
  46. #include "llvm/ADT/StringSwitch.h"
  47. #include "llvm/ADT/Triple.h"
  48. #include "llvm/Analysis/TargetLibraryInfo.h"
  49. #include "llvm/IR/CallingConv.h"
  50. #include "llvm/IR/DataLayout.h"
  51. #include "llvm/IR/Intrinsics.h"
  52. #include "llvm/IR/LLVMContext.h"
  53. #include "llvm/IR/Module.h"
  54. #include "llvm/IR/ProfileSummary.h"
  55. #include "llvm/ProfileData/InstrProfReader.h"
  56. #include "llvm/Support/CodeGen.h"
  57. #include "llvm/Support/ConvertUTF.h"
  58. #include "llvm/Support/ErrorHandling.h"
  59. #include "llvm/Support/MD5.h"
  60. #include "llvm/Support/TimeProfiler.h"
  61. using namespace clang;
  62. using namespace CodeGen;
  63. static llvm::cl::opt<bool> LimitedCoverage(
  64. "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
  65. llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
  66. llvm::cl::init(false));
  67. static const char AnnotationSection[] = "llvm.metadata";
  68. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  69. switch (CGM.getTarget().getCXXABI().getKind()) {
  70. case TargetCXXABI::GenericAArch64:
  71. case TargetCXXABI::GenericARM:
  72. case TargetCXXABI::iOS:
  73. case TargetCXXABI::iOS64:
  74. case TargetCXXABI::WatchOS:
  75. case TargetCXXABI::GenericMIPS:
  76. case TargetCXXABI::GenericItanium:
  77. case TargetCXXABI::WebAssembly:
  78. return CreateItaniumCXXABI(CGM);
  79. case TargetCXXABI::Microsoft:
  80. return CreateMicrosoftCXXABI(CGM);
  81. }
  82. llvm_unreachable("invalid C++ ABI kind");
  83. }
  84. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  85. const PreprocessorOptions &PPO,
  86. const CodeGenOptions &CGO, llvm::Module &M,
  87. DiagnosticsEngine &diags,
  88. CoverageSourceInfo *CoverageInfo)
  89. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  90. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  91. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  92. VMContext(M.getContext()), Types(*this), VTables(*this),
  93. SanitizerMD(new SanitizerMetadata(*this)) {
  94. // Initialize the type cache.
  95. llvm::LLVMContext &LLVMContext = M.getContext();
  96. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  97. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  98. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  99. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  100. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  101. HalfTy = llvm::Type::getHalfTy(LLVMContext);
  102. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  103. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  104. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  105. PointerAlignInBytes =
  106. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  107. SizeSizeInBytes =
  108. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  109. IntAlignInBytes =
  110. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  111. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  112. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  113. C.getTargetInfo().getMaxPointerWidth());
  114. Int8PtrTy = Int8Ty->getPointerTo(0);
  115. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  116. AllocaInt8PtrTy = Int8Ty->getPointerTo(
  117. M.getDataLayout().getAllocaAddrSpace());
  118. ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
  119. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  120. if (LangOpts.ObjC)
  121. createObjCRuntime();
  122. if (LangOpts.OpenCL)
  123. createOpenCLRuntime();
  124. if (LangOpts.OpenMP)
  125. createOpenMPRuntime();
  126. if (LangOpts.CUDA)
  127. createCUDARuntime();
  128. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  129. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  130. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  131. TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
  132. getCXXABI().getMangleContext()));
  133. // If debug info or coverage generation is enabled, create the CGDebugInfo
  134. // object.
  135. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  136. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  137. DebugInfo.reset(new CGDebugInfo(*this));
  138. Block.GlobalUniqueCount = 0;
  139. if (C.getLangOpts().ObjC)
  140. ObjCData.reset(new ObjCEntrypoints());
  141. if (CodeGenOpts.hasProfileClangUse()) {
  142. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  143. CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
  144. if (auto E = ReaderOrErr.takeError()) {
  145. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  146. "Could not read profile %0: %1");
  147. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  148. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  149. << EI.message();
  150. });
  151. } else
  152. PGOReader = std::move(ReaderOrErr.get());
  153. }
  154. // If coverage mapping generation is enabled, create the
  155. // CoverageMappingModuleGen object.
  156. if (CodeGenOpts.CoverageMapping)
  157. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  158. }
  159. CodeGenModule::~CodeGenModule() {}
  160. void CodeGenModule::createObjCRuntime() {
  161. // This is just isGNUFamily(), but we want to force implementors of
  162. // new ABIs to decide how best to do this.
  163. switch (LangOpts.ObjCRuntime.getKind()) {
  164. case ObjCRuntime::GNUstep:
  165. case ObjCRuntime::GCC:
  166. case ObjCRuntime::ObjFW:
  167. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  168. return;
  169. case ObjCRuntime::FragileMacOSX:
  170. case ObjCRuntime::MacOSX:
  171. case ObjCRuntime::iOS:
  172. case ObjCRuntime::WatchOS:
  173. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  174. return;
  175. }
  176. llvm_unreachable("bad runtime kind");
  177. }
  178. void CodeGenModule::createOpenCLRuntime() {
  179. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  180. }
  181. void CodeGenModule::createOpenMPRuntime() {
  182. // Select a specialized code generation class based on the target, if any.
  183. // If it does not exist use the default implementation.
  184. switch (getTriple().getArch()) {
  185. case llvm::Triple::nvptx:
  186. case llvm::Triple::nvptx64:
  187. assert(getLangOpts().OpenMPIsDevice &&
  188. "OpenMP NVPTX is only prepared to deal with device code.");
  189. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  190. break;
  191. default:
  192. if (LangOpts.OpenMPSimd)
  193. OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
  194. else
  195. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  196. break;
  197. }
  198. }
  199. void CodeGenModule::createCUDARuntime() {
  200. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  201. }
  202. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  203. Replacements[Name] = C;
  204. }
  205. void CodeGenModule::applyReplacements() {
  206. for (auto &I : Replacements) {
  207. StringRef MangledName = I.first();
  208. llvm::Constant *Replacement = I.second;
  209. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  210. if (!Entry)
  211. continue;
  212. auto *OldF = cast<llvm::Function>(Entry);
  213. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  214. if (!NewF) {
  215. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  216. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  217. } else {
  218. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  219. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  220. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  221. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  222. }
  223. }
  224. // Replace old with new, but keep the old order.
  225. OldF->replaceAllUsesWith(Replacement);
  226. if (NewF) {
  227. NewF->removeFromParent();
  228. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  229. NewF);
  230. }
  231. OldF->eraseFromParent();
  232. }
  233. }
  234. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  235. GlobalValReplacements.push_back(std::make_pair(GV, C));
  236. }
  237. void CodeGenModule::applyGlobalValReplacements() {
  238. for (auto &I : GlobalValReplacements) {
  239. llvm::GlobalValue *GV = I.first;
  240. llvm::Constant *C = I.second;
  241. GV->replaceAllUsesWith(C);
  242. GV->eraseFromParent();
  243. }
  244. }
  245. // This is only used in aliases that we created and we know they have a
  246. // linear structure.
  247. static const llvm::GlobalObject *getAliasedGlobal(
  248. const llvm::GlobalIndirectSymbol &GIS) {
  249. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  250. const llvm::Constant *C = &GIS;
  251. for (;;) {
  252. C = C->stripPointerCasts();
  253. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  254. return GO;
  255. // stripPointerCasts will not walk over weak aliases.
  256. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  257. if (!GIS2)
  258. return nullptr;
  259. if (!Visited.insert(GIS2).second)
  260. return nullptr;
  261. C = GIS2->getIndirectSymbol();
  262. }
  263. }
  264. void CodeGenModule::checkAliases() {
  265. // Check if the constructed aliases are well formed. It is really unfortunate
  266. // that we have to do this in CodeGen, but we only construct mangled names
  267. // and aliases during codegen.
  268. bool Error = false;
  269. DiagnosticsEngine &Diags = getDiags();
  270. for (const GlobalDecl &GD : Aliases) {
  271. const auto *D = cast<ValueDecl>(GD.getDecl());
  272. SourceLocation Location;
  273. bool IsIFunc = D->hasAttr<IFuncAttr>();
  274. if (const Attr *A = D->getDefiningAttr())
  275. Location = A->getLocation();
  276. else
  277. llvm_unreachable("Not an alias or ifunc?");
  278. StringRef MangledName = getMangledName(GD);
  279. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  280. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  281. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  282. if (!GV) {
  283. Error = true;
  284. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  285. } else if (GV->isDeclaration()) {
  286. Error = true;
  287. Diags.Report(Location, diag::err_alias_to_undefined)
  288. << IsIFunc << IsIFunc;
  289. } else if (IsIFunc) {
  290. // Check resolver function type.
  291. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  292. GV->getType()->getPointerElementType());
  293. assert(FTy);
  294. if (!FTy->getReturnType()->isPointerTy())
  295. Diags.Report(Location, diag::err_ifunc_resolver_return);
  296. }
  297. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  298. llvm::GlobalValue *AliaseeGV;
  299. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  300. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  301. else
  302. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  303. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  304. StringRef AliasSection = SA->getName();
  305. if (AliasSection != AliaseeGV->getSection())
  306. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  307. << AliasSection << IsIFunc << IsIFunc;
  308. }
  309. // We have to handle alias to weak aliases in here. LLVM itself disallows
  310. // this since the object semantics would not match the IL one. For
  311. // compatibility with gcc we implement it by just pointing the alias
  312. // to its aliasee's aliasee. We also warn, since the user is probably
  313. // expecting the link to be weak.
  314. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  315. if (GA->isInterposable()) {
  316. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  317. << GV->getName() << GA->getName() << IsIFunc;
  318. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  319. GA->getIndirectSymbol(), Alias->getType());
  320. Alias->setIndirectSymbol(Aliasee);
  321. }
  322. }
  323. }
  324. if (!Error)
  325. return;
  326. for (const GlobalDecl &GD : Aliases) {
  327. StringRef MangledName = getMangledName(GD);
  328. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  329. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  330. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  331. Alias->eraseFromParent();
  332. }
  333. }
  334. void CodeGenModule::clear() {
  335. DeferredDeclsToEmit.clear();
  336. if (OpenMPRuntime)
  337. OpenMPRuntime->clear();
  338. }
  339. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  340. StringRef MainFile) {
  341. if (!hasDiagnostics())
  342. return;
  343. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  344. if (MainFile.empty())
  345. MainFile = "<stdin>";
  346. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  347. } else {
  348. if (Mismatched > 0)
  349. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
  350. if (Missing > 0)
  351. Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
  352. }
  353. }
  354. void CodeGenModule::Release() {
  355. EmitDeferred();
  356. EmitVTablesOpportunistically();
  357. applyGlobalValReplacements();
  358. applyReplacements();
  359. checkAliases();
  360. emitMultiVersionFunctions();
  361. EmitCXXGlobalInitFunc();
  362. EmitCXXGlobalDtorFunc();
  363. registerGlobalDtorsWithAtExit();
  364. EmitCXXThreadLocalInitFunc();
  365. if (ObjCRuntime)
  366. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  367. AddGlobalCtor(ObjCInitFunction);
  368. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  369. CUDARuntime) {
  370. if (llvm::Function *CudaCtorFunction =
  371. CUDARuntime->makeModuleCtorFunction())
  372. AddGlobalCtor(CudaCtorFunction);
  373. }
  374. if (OpenMPRuntime) {
  375. if (llvm::Function *OpenMPRegistrationFunction =
  376. OpenMPRuntime->emitRegistrationFunction()) {
  377. auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
  378. OpenMPRegistrationFunction : nullptr;
  379. AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
  380. }
  381. OpenMPRuntime->clear();
  382. }
  383. if (PGOReader) {
  384. getModule().setProfileSummary(
  385. PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
  386. llvm::ProfileSummary::PSK_Instr);
  387. if (PGOStats.hasDiagnostics())
  388. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  389. }
  390. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  391. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  392. EmitGlobalAnnotations();
  393. EmitStaticExternCAliases();
  394. EmitDeferredUnusedCoverageMappings();
  395. if (CoverageMapping)
  396. CoverageMapping->emit();
  397. if (CodeGenOpts.SanitizeCfiCrossDso) {
  398. CodeGenFunction(*this).EmitCfiCheckFail();
  399. CodeGenFunction(*this).EmitCfiCheckStub();
  400. }
  401. emitAtAvailableLinkGuard();
  402. emitLLVMUsed();
  403. if (SanStats)
  404. SanStats->finish();
  405. if (CodeGenOpts.Autolink &&
  406. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  407. EmitModuleLinkOptions();
  408. }
  409. // Record mregparm value now so it is visible through rest of codegen.
  410. if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  411. getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
  412. CodeGenOpts.NumRegisterParameters);
  413. if (CodeGenOpts.DwarfVersion) {
  414. // We actually want the latest version when there are conflicts.
  415. // We can change from Warning to Latest if such mode is supported.
  416. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  417. CodeGenOpts.DwarfVersion);
  418. }
  419. if (CodeGenOpts.EmitCodeView) {
  420. // Indicate that we want CodeView in the metadata.
  421. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  422. }
  423. if (CodeGenOpts.CodeViewGHash) {
  424. getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
  425. }
  426. if (CodeGenOpts.ControlFlowGuard) {
  427. // We want function ID tables for Control Flow Guard.
  428. getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
  429. }
  430. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  431. // We don't support LTO with 2 with different StrictVTablePointers
  432. // FIXME: we could support it by stripping all the information introduced
  433. // by StrictVTablePointers.
  434. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  435. llvm::Metadata *Ops[2] = {
  436. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  437. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  438. llvm::Type::getInt32Ty(VMContext), 1))};
  439. getModule().addModuleFlag(llvm::Module::Require,
  440. "StrictVTablePointersRequirement",
  441. llvm::MDNode::get(VMContext, Ops));
  442. }
  443. if (DebugInfo)
  444. // We support a single version in the linked module. The LLVM
  445. // parser will drop debug info with a different version number
  446. // (and warn about it, too).
  447. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  448. llvm::DEBUG_METADATA_VERSION);
  449. // We need to record the widths of enums and wchar_t, so that we can generate
  450. // the correct build attributes in the ARM backend. wchar_size is also used by
  451. // TargetLibraryInfo.
  452. uint64_t WCharWidth =
  453. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  454. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  455. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  456. if ( Arch == llvm::Triple::arm
  457. || Arch == llvm::Triple::armeb
  458. || Arch == llvm::Triple::thumb
  459. || Arch == llvm::Triple::thumbeb) {
  460. // The minimum width of an enum in bytes
  461. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  462. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  463. }
  464. if (CodeGenOpts.SanitizeCfiCrossDso) {
  465. // Indicate that we want cross-DSO control flow integrity checks.
  466. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  467. }
  468. if (CodeGenOpts.CFProtectionReturn &&
  469. Target.checkCFProtectionReturnSupported(getDiags())) {
  470. // Indicate that we want to instrument return control flow protection.
  471. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
  472. 1);
  473. }
  474. if (CodeGenOpts.CFProtectionBranch &&
  475. Target.checkCFProtectionBranchSupported(getDiags())) {
  476. // Indicate that we want to instrument branch control flow protection.
  477. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
  478. 1);
  479. }
  480. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  481. // Indicate whether __nvvm_reflect should be configured to flush denormal
  482. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  483. // property.)
  484. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  485. CodeGenOpts.FlushDenorm ? 1 : 0);
  486. }
  487. // Emit OpenCL specific module metadata: OpenCL/SPIR version.
  488. if (LangOpts.OpenCL) {
  489. EmitOpenCLMetadata();
  490. // Emit SPIR version.
  491. if (getTriple().getArch() == llvm::Triple::spir ||
  492. getTriple().getArch() == llvm::Triple::spir64) {
  493. // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
  494. // opencl.spir.version named metadata.
  495. llvm::Metadata *SPIRVerElts[] = {
  496. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  497. Int32Ty, LangOpts.OpenCLVersion / 100)),
  498. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  499. Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
  500. llvm::NamedMDNode *SPIRVerMD =
  501. TheModule.getOrInsertNamedMetadata("opencl.spir.version");
  502. llvm::LLVMContext &Ctx = TheModule.getContext();
  503. SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
  504. }
  505. }
  506. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  507. assert(PLevel < 3 && "Invalid PIC Level");
  508. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  509. if (Context.getLangOpts().PIE)
  510. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  511. }
  512. if (getCodeGenOpts().CodeModel.size() > 0) {
  513. unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
  514. .Case("tiny", llvm::CodeModel::Tiny)
  515. .Case("small", llvm::CodeModel::Small)
  516. .Case("kernel", llvm::CodeModel::Kernel)
  517. .Case("medium", llvm::CodeModel::Medium)
  518. .Case("large", llvm::CodeModel::Large)
  519. .Default(~0u);
  520. if (CM != ~0u) {
  521. llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
  522. getModule().setCodeModel(codeModel);
  523. }
  524. }
  525. if (CodeGenOpts.NoPLT)
  526. getModule().setRtLibUseGOT();
  527. SimplifyPersonality();
  528. if (getCodeGenOpts().EmitDeclMetadata)
  529. EmitDeclMetadata();
  530. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  531. EmitCoverageFile();
  532. if (DebugInfo)
  533. DebugInfo->finalize();
  534. if (getCodeGenOpts().EmitVersionIdentMetadata)
  535. EmitVersionIdentMetadata();
  536. if (!getCodeGenOpts().RecordCommandLine.empty())
  537. EmitCommandLineMetadata();
  538. EmitTargetMetadata();
  539. }
  540. void CodeGenModule::EmitOpenCLMetadata() {
  541. // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
  542. // opencl.ocl.version named metadata node.
  543. llvm::Metadata *OCLVerElts[] = {
  544. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  545. Int32Ty, LangOpts.OpenCLVersion / 100)),
  546. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  547. Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
  548. llvm::NamedMDNode *OCLVerMD =
  549. TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
  550. llvm::LLVMContext &Ctx = TheModule.getContext();
  551. OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
  552. }
  553. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  554. // Make sure that this type is translated.
  555. Types.UpdateCompletedType(TD);
  556. }
  557. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  558. // Make sure that this type is translated.
  559. Types.RefreshTypeCacheForClass(RD);
  560. }
  561. llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
  562. if (!TBAA)
  563. return nullptr;
  564. return TBAA->getTypeInfo(QTy);
  565. }
  566. TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
  567. if (!TBAA)
  568. return TBAAAccessInfo();
  569. return TBAA->getAccessInfo(AccessType);
  570. }
  571. TBAAAccessInfo
  572. CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
  573. if (!TBAA)
  574. return TBAAAccessInfo();
  575. return TBAA->getVTablePtrAccessInfo(VTablePtrType);
  576. }
  577. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  578. if (!TBAA)
  579. return nullptr;
  580. return TBAA->getTBAAStructInfo(QTy);
  581. }
  582. llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
  583. if (!TBAA)
  584. return nullptr;
  585. return TBAA->getBaseTypeInfo(QTy);
  586. }
  587. llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
  588. if (!TBAA)
  589. return nullptr;
  590. return TBAA->getAccessTagInfo(Info);
  591. }
  592. TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  593. TBAAAccessInfo TargetInfo) {
  594. if (!TBAA)
  595. return TBAAAccessInfo();
  596. return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
  597. }
  598. TBAAAccessInfo
  599. CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
  600. TBAAAccessInfo InfoB) {
  601. if (!TBAA)
  602. return TBAAAccessInfo();
  603. return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
  604. }
  605. TBAAAccessInfo
  606. CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
  607. TBAAAccessInfo SrcInfo) {
  608. if (!TBAA)
  609. return TBAAAccessInfo();
  610. return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
  611. }
  612. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  613. TBAAAccessInfo TBAAInfo) {
  614. if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
  615. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
  616. }
  617. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  618. llvm::Instruction *I, const CXXRecordDecl *RD) {
  619. I->setMetadata(llvm::LLVMContext::MD_invariant_group,
  620. llvm::MDNode::get(getLLVMContext(), {}));
  621. }
  622. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  623. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  624. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  625. }
  626. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  627. /// specified stmt yet.
  628. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  629. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  630. "cannot compile this %0 yet");
  631. std::string Msg = Type;
  632. getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
  633. << Msg << S->getSourceRange();
  634. }
  635. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  636. /// specified decl yet.
  637. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  638. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  639. "cannot compile this %0 yet");
  640. std::string Msg = Type;
  641. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  642. }
  643. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  644. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  645. }
  646. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  647. const NamedDecl *D) const {
  648. if (GV->hasDLLImportStorageClass())
  649. return;
  650. // Internal definitions always have default visibility.
  651. if (GV->hasLocalLinkage()) {
  652. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  653. return;
  654. }
  655. if (!D)
  656. return;
  657. // Set visibility for definitions, and for declarations if requested globally
  658. // or set explicitly.
  659. LinkageInfo LV = D->getLinkageAndVisibility();
  660. if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
  661. !GV->isDeclarationForLinker())
  662. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  663. }
  664. static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
  665. llvm::GlobalValue *GV) {
  666. if (GV->hasLocalLinkage())
  667. return true;
  668. if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
  669. return true;
  670. // DLLImport explicitly marks the GV as external.
  671. if (GV->hasDLLImportStorageClass())
  672. return false;
  673. const llvm::Triple &TT = CGM.getTriple();
  674. if (TT.isWindowsGNUEnvironment()) {
  675. // In MinGW, variables without DLLImport can still be automatically
  676. // imported from a DLL by the linker; don't mark variables that
  677. // potentially could come from another DLL as DSO local.
  678. if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
  679. !GV->isThreadLocal())
  680. return false;
  681. }
  682. // Every other GV is local on COFF.
  683. // Make an exception for windows OS in the triple: Some firmware builds use
  684. // *-win32-macho triples. This (accidentally?) produced windows relocations
  685. // without GOT tables in older clang versions; Keep this behaviour.
  686. // FIXME: even thread local variables?
  687. if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
  688. return true;
  689. // Only handle COFF and ELF for now.
  690. if (!TT.isOSBinFormatELF())
  691. return false;
  692. // If this is not an executable, don't assume anything is local.
  693. const auto &CGOpts = CGM.getCodeGenOpts();
  694. llvm::Reloc::Model RM = CGOpts.RelocationModel;
  695. const auto &LOpts = CGM.getLangOpts();
  696. if (RM != llvm::Reloc::Static && !LOpts.PIE)
  697. return false;
  698. // A definition cannot be preempted from an executable.
  699. if (!GV->isDeclarationForLinker())
  700. return true;
  701. // Most PIC code sequences that assume that a symbol is local cannot produce a
  702. // 0 if it turns out the symbol is undefined. While this is ABI and relocation
  703. // depended, it seems worth it to handle it here.
  704. if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
  705. return false;
  706. // PPC has no copy relocations and cannot use a plt entry as a symbol address.
  707. llvm::Triple::ArchType Arch = TT.getArch();
  708. if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  709. Arch == llvm::Triple::ppc64le)
  710. return false;
  711. // If we can use copy relocations we can assume it is local.
  712. if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
  713. if (!Var->isThreadLocal() &&
  714. (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
  715. return true;
  716. // If we can use a plt entry as the symbol address we can assume it
  717. // is local.
  718. // FIXME: This should work for PIE, but the gold linker doesn't support it.
  719. if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
  720. return true;
  721. // Otherwise don't assue it is local.
  722. return false;
  723. }
  724. void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
  725. GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
  726. }
  727. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  728. GlobalDecl GD) const {
  729. const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
  730. // C++ destructors have a few C++ ABI specific special cases.
  731. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
  732. getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
  733. return;
  734. }
  735. setDLLImportDLLExport(GV, D);
  736. }
  737. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  738. const NamedDecl *D) const {
  739. if (D && D->isExternallyVisible()) {
  740. if (D->hasAttr<DLLImportAttr>())
  741. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  742. else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
  743. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  744. }
  745. }
  746. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  747. GlobalDecl GD) const {
  748. setDLLImportDLLExport(GV, GD);
  749. setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
  750. }
  751. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  752. const NamedDecl *D) const {
  753. setDLLImportDLLExport(GV, D);
  754. setGlobalVisibilityAndLocal(GV, D);
  755. }
  756. void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
  757. const NamedDecl *D) const {
  758. setGlobalVisibility(GV, D);
  759. setDSOLocal(GV);
  760. }
  761. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  762. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  763. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  764. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  765. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  766. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  767. }
  768. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  769. CodeGenOptions::TLSModel M) {
  770. switch (M) {
  771. case CodeGenOptions::GeneralDynamicTLSModel:
  772. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  773. case CodeGenOptions::LocalDynamicTLSModel:
  774. return llvm::GlobalVariable::LocalDynamicTLSModel;
  775. case CodeGenOptions::InitialExecTLSModel:
  776. return llvm::GlobalVariable::InitialExecTLSModel;
  777. case CodeGenOptions::LocalExecTLSModel:
  778. return llvm::GlobalVariable::LocalExecTLSModel;
  779. }
  780. llvm_unreachable("Invalid TLS model!");
  781. }
  782. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  783. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  784. llvm::GlobalValue::ThreadLocalMode TLM;
  785. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  786. // Override the TLS model if it is explicitly specified.
  787. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  788. TLM = GetLLVMTLSModel(Attr->getModel());
  789. }
  790. GV->setThreadLocalMode(TLM);
  791. }
  792. static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
  793. StringRef Name) {
  794. const TargetInfo &Target = CGM.getTarget();
  795. return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
  796. }
  797. static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
  798. const CPUSpecificAttr *Attr,
  799. unsigned CPUIndex,
  800. raw_ostream &Out) {
  801. // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
  802. // supported.
  803. if (Attr)
  804. Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
  805. else if (CGM.getTarget().supportsIFunc())
  806. Out << ".resolver";
  807. }
  808. static void AppendTargetMangling(const CodeGenModule &CGM,
  809. const TargetAttr *Attr, raw_ostream &Out) {
  810. if (Attr->isDefaultVersion())
  811. return;
  812. Out << '.';
  813. const TargetInfo &Target = CGM.getTarget();
  814. TargetAttr::ParsedTargetAttr Info =
  815. Attr->parse([&Target](StringRef LHS, StringRef RHS) {
  816. // Multiversioning doesn't allow "no-${feature}", so we can
  817. // only have "+" prefixes here.
  818. assert(LHS.startswith("+") && RHS.startswith("+") &&
  819. "Features should always have a prefix.");
  820. return Target.multiVersionSortPriority(LHS.substr(1)) >
  821. Target.multiVersionSortPriority(RHS.substr(1));
  822. });
  823. bool IsFirst = true;
  824. if (!Info.Architecture.empty()) {
  825. IsFirst = false;
  826. Out << "arch_" << Info.Architecture;
  827. }
  828. for (StringRef Feat : Info.Features) {
  829. if (!IsFirst)
  830. Out << '_';
  831. IsFirst = false;
  832. Out << Feat.substr(1);
  833. }
  834. }
  835. static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
  836. const NamedDecl *ND,
  837. bool OmitMultiVersionMangling = false) {
  838. SmallString<256> Buffer;
  839. llvm::raw_svector_ostream Out(Buffer);
  840. MangleContext &MC = CGM.getCXXABI().getMangleContext();
  841. if (MC.shouldMangleDeclName(ND)) {
  842. llvm::raw_svector_ostream Out(Buffer);
  843. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  844. MC.mangleCXXCtor(D, GD.getCtorType(), Out);
  845. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  846. MC.mangleCXXDtor(D, GD.getDtorType(), Out);
  847. else
  848. MC.mangleName(ND, Out);
  849. } else {
  850. IdentifierInfo *II = ND->getIdentifier();
  851. assert(II && "Attempt to mangle unnamed decl.");
  852. const auto *FD = dyn_cast<FunctionDecl>(ND);
  853. if (FD &&
  854. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  855. llvm::raw_svector_ostream Out(Buffer);
  856. Out << "__regcall3__" << II->getName();
  857. } else {
  858. Out << II->getName();
  859. }
  860. }
  861. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  862. if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
  863. switch (FD->getMultiVersionKind()) {
  864. case MultiVersionKind::CPUDispatch:
  865. case MultiVersionKind::CPUSpecific:
  866. AppendCPUSpecificCPUDispatchMangling(CGM,
  867. FD->getAttr<CPUSpecificAttr>(),
  868. GD.getMultiVersionIndex(), Out);
  869. break;
  870. case MultiVersionKind::Target:
  871. AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
  872. break;
  873. case MultiVersionKind::None:
  874. llvm_unreachable("None multiversion type isn't valid here");
  875. }
  876. }
  877. return Out.str();
  878. }
  879. void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
  880. const FunctionDecl *FD) {
  881. if (!FD->isMultiVersion())
  882. return;
  883. // Get the name of what this would be without the 'target' attribute. This
  884. // allows us to lookup the version that was emitted when this wasn't a
  885. // multiversion function.
  886. std::string NonTargetName =
  887. getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
  888. GlobalDecl OtherGD;
  889. if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
  890. assert(OtherGD.getCanonicalDecl()
  891. .getDecl()
  892. ->getAsFunction()
  893. ->isMultiVersion() &&
  894. "Other GD should now be a multiversioned function");
  895. // OtherFD is the version of this function that was mangled BEFORE
  896. // becoming a MultiVersion function. It potentially needs to be updated.
  897. const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
  898. .getDecl()
  899. ->getAsFunction()
  900. ->getMostRecentDecl();
  901. std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
  902. // This is so that if the initial version was already the 'default'
  903. // version, we don't try to update it.
  904. if (OtherName != NonTargetName) {
  905. // Remove instead of erase, since others may have stored the StringRef
  906. // to this.
  907. const auto ExistingRecord = Manglings.find(NonTargetName);
  908. if (ExistingRecord != std::end(Manglings))
  909. Manglings.remove(&(*ExistingRecord));
  910. auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
  911. MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
  912. if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
  913. Entry->setName(OtherName);
  914. }
  915. }
  916. }
  917. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  918. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  919. // Some ABIs don't have constructor variants. Make sure that base and
  920. // complete constructors get mangled the same.
  921. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  922. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  923. CXXCtorType OrigCtorType = GD.getCtorType();
  924. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  925. if (OrigCtorType == Ctor_Base)
  926. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  927. }
  928. }
  929. auto FoundName = MangledDeclNames.find(CanonicalGD);
  930. if (FoundName != MangledDeclNames.end())
  931. return FoundName->second;
  932. // Keep the first result in the case of a mangling collision.
  933. const auto *ND = cast<NamedDecl>(GD.getDecl());
  934. std::string MangledName = getMangledNameImpl(*this, GD, ND);
  935. // Postfix kernel stub names with .stub to differentiate them from kernel
  936. // names in device binaries. This is to facilitate the debugger to find
  937. // the correct symbols for kernels in the device binary.
  938. if (auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()))
  939. if (getLangOpts().HIP && !getLangOpts().CUDAIsDevice &&
  940. FD->hasAttr<CUDAGlobalAttr>())
  941. MangledName = MangledName + ".stub";
  942. auto Result = Manglings.insert(std::make_pair(MangledName, GD));
  943. return MangledDeclNames[CanonicalGD] = Result.first->first();
  944. }
  945. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  946. const BlockDecl *BD) {
  947. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  948. const Decl *D = GD.getDecl();
  949. SmallString<256> Buffer;
  950. llvm::raw_svector_ostream Out(Buffer);
  951. if (!D)
  952. MangleCtx.mangleGlobalBlock(BD,
  953. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  954. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  955. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  956. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  957. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  958. else
  959. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  960. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  961. return Result.first->first();
  962. }
  963. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  964. return getModule().getNamedValue(Name);
  965. }
  966. /// AddGlobalCtor - Add a function to the list that will be called before
  967. /// main() runs.
  968. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  969. llvm::Constant *AssociatedData) {
  970. // FIXME: Type coercion of void()* types.
  971. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  972. }
  973. /// AddGlobalDtor - Add a function to the list that will be called
  974. /// when the module is unloaded.
  975. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  976. if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
  977. DtorsUsingAtExit[Priority].push_back(Dtor);
  978. return;
  979. }
  980. // FIXME: Type coercion of void()* types.
  981. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  982. }
  983. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  984. if (Fns.empty()) return;
  985. // Ctor function type is void()*.
  986. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  987. llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
  988. TheModule.getDataLayout().getProgramAddressSpace());
  989. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  990. llvm::StructType *CtorStructTy = llvm::StructType::get(
  991. Int32Ty, CtorPFTy, VoidPtrTy);
  992. // Construct the constructor and destructor arrays.
  993. ConstantInitBuilder builder(*this);
  994. auto ctors = builder.beginArray(CtorStructTy);
  995. for (const auto &I : Fns) {
  996. auto ctor = ctors.beginStruct(CtorStructTy);
  997. ctor.addInt(Int32Ty, I.Priority);
  998. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  999. if (I.AssociatedData)
  1000. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  1001. else
  1002. ctor.addNullPointer(VoidPtrTy);
  1003. ctor.finishAndAddTo(ctors);
  1004. }
  1005. auto list =
  1006. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  1007. /*constant*/ false,
  1008. llvm::GlobalValue::AppendingLinkage);
  1009. // The LTO linker doesn't seem to like it when we set an alignment
  1010. // on appending variables. Take it off as a workaround.
  1011. list->setAlignment(0);
  1012. Fns.clear();
  1013. }
  1014. llvm::GlobalValue::LinkageTypes
  1015. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  1016. const auto *D = cast<FunctionDecl>(GD.getDecl());
  1017. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  1018. if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
  1019. return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
  1020. if (isa<CXXConstructorDecl>(D) &&
  1021. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  1022. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1023. // Our approach to inheriting constructors is fundamentally different from
  1024. // that used by the MS ABI, so keep our inheriting constructor thunks
  1025. // internal rather than trying to pick an unambiguous mangling for them.
  1026. return llvm::GlobalValue::InternalLinkage;
  1027. }
  1028. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  1029. }
  1030. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  1031. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  1032. if (!MDS) return nullptr;
  1033. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  1034. }
  1035. void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
  1036. const CGFunctionInfo &Info,
  1037. llvm::Function *F) {
  1038. unsigned CallingConv;
  1039. llvm::AttributeList PAL;
  1040. ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
  1041. F->setAttributes(PAL);
  1042. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  1043. }
  1044. /// Determines whether the language options require us to model
  1045. /// unwind exceptions. We treat -fexceptions as mandating this
  1046. /// except under the fragile ObjC ABI with only ObjC exceptions
  1047. /// enabled. This means, for example, that C with -fexceptions
  1048. /// enables this.
  1049. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  1050. // If exceptions are completely disabled, obviously this is false.
  1051. if (!LangOpts.Exceptions) return false;
  1052. // If C++ exceptions are enabled, this is true.
  1053. if (LangOpts.CXXExceptions) return true;
  1054. // If ObjC exceptions are enabled, this depends on the ABI.
  1055. if (LangOpts.ObjCExceptions) {
  1056. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  1057. }
  1058. return true;
  1059. }
  1060. static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
  1061. const CXXMethodDecl *MD) {
  1062. // Check that the type metadata can ever actually be used by a call.
  1063. if (!CGM.getCodeGenOpts().LTOUnit ||
  1064. !CGM.HasHiddenLTOVisibility(MD->getParent()))
  1065. return false;
  1066. // Only functions whose address can be taken with a member function pointer
  1067. // need this sort of type metadata.
  1068. return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
  1069. !isa<CXXDestructorDecl>(MD);
  1070. }
  1071. std::vector<const CXXRecordDecl *>
  1072. CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
  1073. llvm::SetVector<const CXXRecordDecl *> MostBases;
  1074. std::function<void (const CXXRecordDecl *)> CollectMostBases;
  1075. CollectMostBases = [&](const CXXRecordDecl *RD) {
  1076. if (RD->getNumBases() == 0)
  1077. MostBases.insert(RD);
  1078. for (const CXXBaseSpecifier &B : RD->bases())
  1079. CollectMostBases(B.getType()->getAsCXXRecordDecl());
  1080. };
  1081. CollectMostBases(RD);
  1082. return MostBases.takeVector();
  1083. }
  1084. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  1085. llvm::Function *F) {
  1086. llvm::AttrBuilder B;
  1087. if (CodeGenOpts.UnwindTables)
  1088. B.addAttribute(llvm::Attribute::UWTable);
  1089. if (!hasUnwindExceptions(LangOpts))
  1090. B.addAttribute(llvm::Attribute::NoUnwind);
  1091. if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
  1092. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  1093. B.addAttribute(llvm::Attribute::StackProtect);
  1094. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  1095. B.addAttribute(llvm::Attribute::StackProtectStrong);
  1096. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  1097. B.addAttribute(llvm::Attribute::StackProtectReq);
  1098. }
  1099. if (!D) {
  1100. // If we don't have a declaration to control inlining, the function isn't
  1101. // explicitly marked as alwaysinline for semantic reasons, and inlining is
  1102. // disabled, mark the function as noinline.
  1103. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1104. CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
  1105. B.addAttribute(llvm::Attribute::NoInline);
  1106. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1107. return;
  1108. }
  1109. // Track whether we need to add the optnone LLVM attribute,
  1110. // starting with the default for this optimization level.
  1111. bool ShouldAddOptNone =
  1112. !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
  1113. // We can't add optnone in the following cases, it won't pass the verifier.
  1114. ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
  1115. ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
  1116. ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
  1117. if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
  1118. B.addAttribute(llvm::Attribute::OptimizeNone);
  1119. // OptimizeNone implies noinline; we should not be inlining such functions.
  1120. B.addAttribute(llvm::Attribute::NoInline);
  1121. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1122. "OptimizeNone and AlwaysInline on same function!");
  1123. // We still need to handle naked functions even though optnone subsumes
  1124. // much of their semantics.
  1125. if (D->hasAttr<NakedAttr>())
  1126. B.addAttribute(llvm::Attribute::Naked);
  1127. // OptimizeNone wins over OptimizeForSize and MinSize.
  1128. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  1129. F->removeFnAttr(llvm::Attribute::MinSize);
  1130. } else if (D->hasAttr<NakedAttr>()) {
  1131. // Naked implies noinline: we should not be inlining such functions.
  1132. B.addAttribute(llvm::Attribute::Naked);
  1133. B.addAttribute(llvm::Attribute::NoInline);
  1134. } else if (D->hasAttr<NoDuplicateAttr>()) {
  1135. B.addAttribute(llvm::Attribute::NoDuplicate);
  1136. } else if (D->hasAttr<NoInlineAttr>()) {
  1137. B.addAttribute(llvm::Attribute::NoInline);
  1138. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  1139. !F->hasFnAttribute(llvm::Attribute::NoInline)) {
  1140. // (noinline wins over always_inline, and we can't specify both in IR)
  1141. B.addAttribute(llvm::Attribute::AlwaysInline);
  1142. } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
  1143. // If we're not inlining, then force everything that isn't always_inline to
  1144. // carry an explicit noinline attribute.
  1145. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
  1146. B.addAttribute(llvm::Attribute::NoInline);
  1147. } else {
  1148. // Otherwise, propagate the inline hint attribute and potentially use its
  1149. // absence to mark things as noinline.
  1150. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1151. // Search function and template pattern redeclarations for inline.
  1152. auto CheckForInline = [](const FunctionDecl *FD) {
  1153. auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
  1154. return Redecl->isInlineSpecified();
  1155. };
  1156. if (any_of(FD->redecls(), CheckRedeclForInline))
  1157. return true;
  1158. const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
  1159. if (!Pattern)
  1160. return false;
  1161. return any_of(Pattern->redecls(), CheckRedeclForInline);
  1162. };
  1163. if (CheckForInline(FD)) {
  1164. B.addAttribute(llvm::Attribute::InlineHint);
  1165. } else if (CodeGenOpts.getInlining() ==
  1166. CodeGenOptions::OnlyHintInlining &&
  1167. !FD->isInlined() &&
  1168. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  1169. B.addAttribute(llvm::Attribute::NoInline);
  1170. }
  1171. }
  1172. }
  1173. // Add other optimization related attributes if we are optimizing this
  1174. // function.
  1175. if (!D->hasAttr<OptimizeNoneAttr>()) {
  1176. if (D->hasAttr<ColdAttr>()) {
  1177. if (!ShouldAddOptNone)
  1178. B.addAttribute(llvm::Attribute::OptimizeForSize);
  1179. B.addAttribute(llvm::Attribute::Cold);
  1180. }
  1181. if (D->hasAttr<MinSizeAttr>())
  1182. B.addAttribute(llvm::Attribute::MinSize);
  1183. }
  1184. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1185. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  1186. if (alignment)
  1187. F->setAlignment(alignment);
  1188. if (!D->hasAttr<AlignedAttr>())
  1189. if (LangOpts.FunctionAlignment)
  1190. F->setAlignment(1 << LangOpts.FunctionAlignment);
  1191. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  1192. // reserve a bit for differentiating between virtual and non-virtual member
  1193. // functions. If the current target's C++ ABI requires this and this is a
  1194. // member function, set its alignment accordingly.
  1195. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  1196. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  1197. F->setAlignment(2);
  1198. }
  1199. // In the cross-dso CFI mode, we want !type attributes on definitions only.
  1200. if (CodeGenOpts.SanitizeCfiCrossDso)
  1201. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1202. CreateFunctionTypeMetadataForIcall(FD, F);
  1203. // Emit type metadata on member functions for member function pointer checks.
  1204. // These are only ever necessary on definitions; we're guaranteed that the
  1205. // definition will be present in the LTO unit as a result of LTO visibility.
  1206. auto *MD = dyn_cast<CXXMethodDecl>(D);
  1207. if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
  1208. for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
  1209. llvm::Metadata *Id =
  1210. CreateMetadataIdentifierForType(Context.getMemberPointerType(
  1211. MD->getType(), Context.getRecordType(Base).getTypePtr()));
  1212. F->addTypeMetadata(0, Id);
  1213. }
  1214. }
  1215. }
  1216. void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
  1217. const Decl *D = GD.getDecl();
  1218. if (dyn_cast_or_null<NamedDecl>(D))
  1219. setGVProperties(GV, GD);
  1220. else
  1221. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  1222. if (D && D->hasAttr<UsedAttr>())
  1223. addUsedGlobal(GV);
  1224. if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
  1225. const auto *VD = cast<VarDecl>(D);
  1226. if (VD->getType().isConstQualified() &&
  1227. VD->getStorageDuration() == SD_Static)
  1228. addUsedGlobal(GV);
  1229. }
  1230. }
  1231. bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
  1232. llvm::AttrBuilder &Attrs) {
  1233. // Add target-cpu and target-features attributes to functions. If
  1234. // we have a decl for the function and it has a target attribute then
  1235. // parse that and add it to the feature set.
  1236. StringRef TargetCPU = getTarget().getTargetOpts().CPU;
  1237. std::vector<std::string> Features;
  1238. const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
  1239. FD = FD ? FD->getMostRecentDecl() : FD;
  1240. const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
  1241. const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
  1242. bool AddedAttr = false;
  1243. if (TD || SD) {
  1244. llvm::StringMap<bool> FeatureMap;
  1245. getFunctionFeatureMap(FeatureMap, GD);
  1246. // Produce the canonical string for this set of features.
  1247. for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
  1248. Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
  1249. // Now add the target-cpu and target-features to the function.
  1250. // While we populated the feature map above, we still need to
  1251. // get and parse the target attribute so we can get the cpu for
  1252. // the function.
  1253. if (TD) {
  1254. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  1255. if (ParsedAttr.Architecture != "" &&
  1256. getTarget().isValidCPUName(ParsedAttr.Architecture))
  1257. TargetCPU = ParsedAttr.Architecture;
  1258. }
  1259. } else {
  1260. // Otherwise just add the existing target cpu and target features to the
  1261. // function.
  1262. Features = getTarget().getTargetOpts().Features;
  1263. }
  1264. if (TargetCPU != "") {
  1265. Attrs.addAttribute("target-cpu", TargetCPU);
  1266. AddedAttr = true;
  1267. }
  1268. if (!Features.empty()) {
  1269. llvm::sort(Features);
  1270. Attrs.addAttribute("target-features", llvm::join(Features, ","));
  1271. AddedAttr = true;
  1272. }
  1273. return AddedAttr;
  1274. }
  1275. void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
  1276. llvm::GlobalObject *GO) {
  1277. const Decl *D = GD.getDecl();
  1278. SetCommonAttributes(GD, GO);
  1279. if (D) {
  1280. if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
  1281. if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
  1282. GV->addAttribute("bss-section", SA->getName());
  1283. if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
  1284. GV->addAttribute("data-section", SA->getName());
  1285. if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
  1286. GV->addAttribute("rodata-section", SA->getName());
  1287. }
  1288. if (auto *F = dyn_cast<llvm::Function>(GO)) {
  1289. if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
  1290. if (!D->getAttr<SectionAttr>())
  1291. F->addFnAttr("implicit-section-name", SA->getName());
  1292. llvm::AttrBuilder Attrs;
  1293. if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
  1294. // We know that GetCPUAndFeaturesAttributes will always have the
  1295. // newest set, since it has the newest possible FunctionDecl, so the
  1296. // new ones should replace the old.
  1297. F->removeFnAttr("target-cpu");
  1298. F->removeFnAttr("target-features");
  1299. F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
  1300. }
  1301. }
  1302. if (const auto *CSA = D->getAttr<CodeSegAttr>())
  1303. GO->setSection(CSA->getName());
  1304. else if (const auto *SA = D->getAttr<SectionAttr>())
  1305. GO->setSection(SA->getName());
  1306. }
  1307. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  1308. }
  1309. void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
  1310. llvm::Function *F,
  1311. const CGFunctionInfo &FI) {
  1312. const Decl *D = GD.getDecl();
  1313. SetLLVMFunctionAttributes(GD, FI, F);
  1314. SetLLVMFunctionAttributesForDefinition(D, F);
  1315. F->setLinkage(llvm::Function::InternalLinkage);
  1316. setNonAliasAttributes(GD, F);
  1317. }
  1318. static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
  1319. // Set linkage and visibility in case we never see a definition.
  1320. LinkageInfo LV = ND->getLinkageAndVisibility();
  1321. // Don't set internal linkage on declarations.
  1322. // "extern_weak" is overloaded in LLVM; we probably should have
  1323. // separate linkage types for this.
  1324. if (isExternallyVisible(LV.getLinkage()) &&
  1325. (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
  1326. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1327. }
  1328. void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
  1329. llvm::Function *F) {
  1330. // Only if we are checking indirect calls.
  1331. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  1332. return;
  1333. // Non-static class methods are handled via vtable or member function pointer
  1334. // checks elsewhere.
  1335. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  1336. return;
  1337. // Additionally, if building with cross-DSO support...
  1338. if (CodeGenOpts.SanitizeCfiCrossDso) {
  1339. // Skip available_externally functions. They won't be codegen'ed in the
  1340. // current module anyway.
  1341. if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
  1342. return;
  1343. }
  1344. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  1345. F->addTypeMetadata(0, MD);
  1346. F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
  1347. // Emit a hash-based bit set entry for cross-DSO calls.
  1348. if (CodeGenOpts.SanitizeCfiCrossDso)
  1349. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  1350. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  1351. }
  1352. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  1353. bool IsIncompleteFunction,
  1354. bool IsThunk) {
  1355. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  1356. // If this is an intrinsic function, set the function's attributes
  1357. // to the intrinsic's attributes.
  1358. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  1359. return;
  1360. }
  1361. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1362. if (!IsIncompleteFunction)
  1363. SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
  1364. // Add the Returned attribute for "this", except for iOS 5 and earlier
  1365. // where substantial code, including the libstdc++ dylib, was compiled with
  1366. // GCC and does not actually return "this".
  1367. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  1368. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  1369. assert(!F->arg_empty() &&
  1370. F->arg_begin()->getType()
  1371. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  1372. "unexpected this return");
  1373. F->addAttribute(1, llvm::Attribute::Returned);
  1374. }
  1375. // Only a few attributes are set on declarations; these may later be
  1376. // overridden by a definition.
  1377. setLinkageForGV(F, FD);
  1378. setGVProperties(F, FD);
  1379. // Setup target-specific attributes.
  1380. if (!IsIncompleteFunction && F->isDeclaration())
  1381. getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
  1382. if (const auto *CSA = FD->getAttr<CodeSegAttr>())
  1383. F->setSection(CSA->getName());
  1384. else if (const auto *SA = FD->getAttr<SectionAttr>())
  1385. F->setSection(SA->getName());
  1386. if (FD->isReplaceableGlobalAllocationFunction()) {
  1387. // A replaceable global allocation function does not act like a builtin by
  1388. // default, only if it is invoked by a new-expression or delete-expression.
  1389. F->addAttribute(llvm::AttributeList::FunctionIndex,
  1390. llvm::Attribute::NoBuiltin);
  1391. // A sane operator new returns a non-aliasing pointer.
  1392. // FIXME: Also add NonNull attribute to the return value
  1393. // for the non-nothrow forms?
  1394. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  1395. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  1396. (Kind == OO_New || Kind == OO_Array_New))
  1397. F->addAttribute(llvm::AttributeList::ReturnIndex,
  1398. llvm::Attribute::NoAlias);
  1399. }
  1400. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  1401. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1402. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  1403. if (MD->isVirtual())
  1404. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1405. // Don't emit entries for function declarations in the cross-DSO mode. This
  1406. // is handled with better precision by the receiving DSO.
  1407. if (!CodeGenOpts.SanitizeCfiCrossDso)
  1408. CreateFunctionTypeMetadataForIcall(FD, F);
  1409. if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
  1410. getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
  1411. if (const auto *CB = FD->getAttr<CallbackAttr>()) {
  1412. // Annotate the callback behavior as metadata:
  1413. // - The callback callee (as argument number).
  1414. // - The callback payloads (as argument numbers).
  1415. llvm::LLVMContext &Ctx = F->getContext();
  1416. llvm::MDBuilder MDB(Ctx);
  1417. // The payload indices are all but the first one in the encoding. The first
  1418. // identifies the callback callee.
  1419. int CalleeIdx = *CB->encoding_begin();
  1420. ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
  1421. F->addMetadata(llvm::LLVMContext::MD_callback,
  1422. *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
  1423. CalleeIdx, PayloadIndices,
  1424. /* VarArgsArePassed */ false)}));
  1425. }
  1426. }
  1427. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  1428. assert(!GV->isDeclaration() &&
  1429. "Only globals with definition can force usage.");
  1430. LLVMUsed.emplace_back(GV);
  1431. }
  1432. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  1433. assert(!GV->isDeclaration() &&
  1434. "Only globals with definition can force usage.");
  1435. LLVMCompilerUsed.emplace_back(GV);
  1436. }
  1437. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  1438. std::vector<llvm::WeakTrackingVH> &List) {
  1439. // Don't create llvm.used if there is no need.
  1440. if (List.empty())
  1441. return;
  1442. // Convert List to what ConstantArray needs.
  1443. SmallVector<llvm::Constant*, 8> UsedArray;
  1444. UsedArray.resize(List.size());
  1445. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  1446. UsedArray[i] =
  1447. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  1448. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  1449. }
  1450. if (UsedArray.empty())
  1451. return;
  1452. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  1453. auto *GV = new llvm::GlobalVariable(
  1454. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  1455. llvm::ConstantArray::get(ATy, UsedArray), Name);
  1456. GV->setSection("llvm.metadata");
  1457. }
  1458. void CodeGenModule::emitLLVMUsed() {
  1459. emitUsed(*this, "llvm.used", LLVMUsed);
  1460. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  1461. }
  1462. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  1463. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  1464. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1465. }
  1466. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  1467. llvm::SmallString<32> Opt;
  1468. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  1469. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1470. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1471. }
  1472. void CodeGenModule::AddELFLibDirective(StringRef Lib) {
  1473. auto &C = getLLVMContext();
  1474. LinkerOptionsMetadata.push_back(llvm::MDNode::get(
  1475. C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
  1476. }
  1477. void CodeGenModule::AddDependentLib(StringRef Lib) {
  1478. llvm::SmallString<24> Opt;
  1479. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1480. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1481. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1482. }
  1483. /// Add link options implied by the given module, including modules
  1484. /// it depends on, using a postorder walk.
  1485. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1486. SmallVectorImpl<llvm::MDNode *> &Metadata,
  1487. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1488. // Import this module's parent.
  1489. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1490. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1491. }
  1492. // Import this module's dependencies.
  1493. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1494. if (Visited.insert(Mod->Imports[I - 1]).second)
  1495. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1496. }
  1497. // Add linker options to link against the libraries/frameworks
  1498. // described by this module.
  1499. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1500. bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
  1501. bool IsPS4 = CGM.getTarget().getTriple().isPS4();
  1502. // For modules that use export_as for linking, use that module
  1503. // name instead.
  1504. if (Mod->UseExportAsModuleLinkName)
  1505. return;
  1506. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1507. // Link against a framework. Frameworks are currently Darwin only, so we
  1508. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1509. if (Mod->LinkLibraries[I-1].IsFramework) {
  1510. llvm::Metadata *Args[2] = {
  1511. llvm::MDString::get(Context, "-framework"),
  1512. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1513. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1514. continue;
  1515. }
  1516. // Link against a library.
  1517. if (IsELF && !IsPS4) {
  1518. llvm::Metadata *Args[2] = {
  1519. llvm::MDString::get(Context, "lib"),
  1520. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
  1521. };
  1522. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1523. } else {
  1524. llvm::SmallString<24> Opt;
  1525. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1526. Mod->LinkLibraries[I - 1].Library, Opt);
  1527. auto *OptString = llvm::MDString::get(Context, Opt);
  1528. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1529. }
  1530. }
  1531. }
  1532. void CodeGenModule::EmitModuleLinkOptions() {
  1533. // Collect the set of all of the modules we want to visit to emit link
  1534. // options, which is essentially the imported modules and all of their
  1535. // non-explicit child modules.
  1536. llvm::SetVector<clang::Module *> LinkModules;
  1537. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1538. SmallVector<clang::Module *, 16> Stack;
  1539. // Seed the stack with imported modules.
  1540. for (Module *M : ImportedModules) {
  1541. // Do not add any link flags when an implementation TU of a module imports
  1542. // a header of that same module.
  1543. if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  1544. !getLangOpts().isCompilingModule())
  1545. continue;
  1546. if (Visited.insert(M).second)
  1547. Stack.push_back(M);
  1548. }
  1549. // Find all of the modules to import, making a little effort to prune
  1550. // non-leaf modules.
  1551. while (!Stack.empty()) {
  1552. clang::Module *Mod = Stack.pop_back_val();
  1553. bool AnyChildren = false;
  1554. // Visit the submodules of this module.
  1555. for (const auto &SM : Mod->submodules()) {
  1556. // Skip explicit children; they need to be explicitly imported to be
  1557. // linked against.
  1558. if (SM->IsExplicit)
  1559. continue;
  1560. if (Visited.insert(SM).second) {
  1561. Stack.push_back(SM);
  1562. AnyChildren = true;
  1563. }
  1564. }
  1565. // We didn't find any children, so add this module to the list of
  1566. // modules to link against.
  1567. if (!AnyChildren) {
  1568. LinkModules.insert(Mod);
  1569. }
  1570. }
  1571. // Add link options for all of the imported modules in reverse topological
  1572. // order. We don't do anything to try to order import link flags with respect
  1573. // to linker options inserted by things like #pragma comment().
  1574. SmallVector<llvm::MDNode *, 16> MetadataArgs;
  1575. Visited.clear();
  1576. for (Module *M : LinkModules)
  1577. if (Visited.insert(M).second)
  1578. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1579. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1580. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1581. // Add the linker options metadata flag.
  1582. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
  1583. for (auto *MD : LinkerOptionsMetadata)
  1584. NMD->addOperand(MD);
  1585. }
  1586. void CodeGenModule::EmitDeferred() {
  1587. // Emit deferred declare target declarations.
  1588. if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
  1589. getOpenMPRuntime().emitDeferredTargetDecls();
  1590. // Emit code for any potentially referenced deferred decls. Since a
  1591. // previously unused static decl may become used during the generation of code
  1592. // for a static function, iterate until no changes are made.
  1593. if (!DeferredVTables.empty()) {
  1594. EmitDeferredVTables();
  1595. // Emitting a vtable doesn't directly cause more vtables to
  1596. // become deferred, although it can cause functions to be
  1597. // emitted that then need those vtables.
  1598. assert(DeferredVTables.empty());
  1599. }
  1600. // Stop if we're out of both deferred vtables and deferred declarations.
  1601. if (DeferredDeclsToEmit.empty())
  1602. return;
  1603. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1604. // work, it will not interfere with this.
  1605. std::vector<GlobalDecl> CurDeclsToEmit;
  1606. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1607. for (GlobalDecl &D : CurDeclsToEmit) {
  1608. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1609. // to get GlobalValue with exactly the type we need, not something that
  1610. // might had been created for another decl with the same mangled name but
  1611. // different type.
  1612. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1613. GetAddrOfGlobal(D, ForDefinition));
  1614. // In case of different address spaces, we may still get a cast, even with
  1615. // IsForDefinition equal to true. Query mangled names table to get
  1616. // GlobalValue.
  1617. if (!GV)
  1618. GV = GetGlobalValue(getMangledName(D));
  1619. // Make sure GetGlobalValue returned non-null.
  1620. assert(GV);
  1621. // Check to see if we've already emitted this. This is necessary
  1622. // for a couple of reasons: first, decls can end up in the
  1623. // deferred-decls queue multiple times, and second, decls can end
  1624. // up with definitions in unusual ways (e.g. by an extern inline
  1625. // function acquiring a strong function redefinition). Just
  1626. // ignore these cases.
  1627. if (!GV->isDeclaration())
  1628. continue;
  1629. // Otherwise, emit the definition and move on to the next one.
  1630. EmitGlobalDefinition(D, GV);
  1631. // If we found out that we need to emit more decls, do that recursively.
  1632. // This has the advantage that the decls are emitted in a DFS and related
  1633. // ones are close together, which is convenient for testing.
  1634. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1635. EmitDeferred();
  1636. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1637. }
  1638. }
  1639. }
  1640. void CodeGenModule::EmitVTablesOpportunistically() {
  1641. // Try to emit external vtables as available_externally if they have emitted
  1642. // all inlined virtual functions. It runs after EmitDeferred() and therefore
  1643. // is not allowed to create new references to things that need to be emitted
  1644. // lazily. Note that it also uses fact that we eagerly emitting RTTI.
  1645. assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
  1646. && "Only emit opportunistic vtables with optimizations");
  1647. for (const CXXRecordDecl *RD : OpportunisticVTables) {
  1648. assert(getVTables().isVTableExternal(RD) &&
  1649. "This queue should only contain external vtables");
  1650. if (getCXXABI().canSpeculativelyEmitVTable(RD))
  1651. VTables.GenerateClassData(RD);
  1652. }
  1653. OpportunisticVTables.clear();
  1654. }
  1655. void CodeGenModule::EmitGlobalAnnotations() {
  1656. if (Annotations.empty())
  1657. return;
  1658. // Create a new global variable for the ConstantStruct in the Module.
  1659. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1660. Annotations[0]->getType(), Annotations.size()), Annotations);
  1661. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1662. llvm::GlobalValue::AppendingLinkage,
  1663. Array, "llvm.global.annotations");
  1664. gv->setSection(AnnotationSection);
  1665. }
  1666. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1667. llvm::Constant *&AStr = AnnotationStrings[Str];
  1668. if (AStr)
  1669. return AStr;
  1670. // Not found yet, create a new global.
  1671. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1672. auto *gv =
  1673. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1674. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1675. gv->setSection(AnnotationSection);
  1676. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1677. AStr = gv;
  1678. return gv;
  1679. }
  1680. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1681. SourceManager &SM = getContext().getSourceManager();
  1682. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1683. if (PLoc.isValid())
  1684. return EmitAnnotationString(PLoc.getFilename());
  1685. return EmitAnnotationString(SM.getBufferName(Loc));
  1686. }
  1687. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1688. SourceManager &SM = getContext().getSourceManager();
  1689. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1690. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1691. SM.getExpansionLineNumber(L);
  1692. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1693. }
  1694. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1695. const AnnotateAttr *AA,
  1696. SourceLocation L) {
  1697. // Get the globals for file name, annotation, and the line number.
  1698. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1699. *UnitGV = EmitAnnotationUnit(L),
  1700. *LineNoCst = EmitAnnotationLineNo(L);
  1701. // Create the ConstantStruct for the global annotation.
  1702. llvm::Constant *Fields[4] = {
  1703. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1704. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1705. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1706. LineNoCst
  1707. };
  1708. return llvm::ConstantStruct::getAnon(Fields);
  1709. }
  1710. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1711. llvm::GlobalValue *GV) {
  1712. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1713. // Get the struct elements for these annotations.
  1714. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1715. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1716. }
  1717. bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
  1718. llvm::Function *Fn,
  1719. SourceLocation Loc) const {
  1720. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1721. // Blacklist by function name.
  1722. if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
  1723. return true;
  1724. // Blacklist by location.
  1725. if (Loc.isValid())
  1726. return SanitizerBL.isBlacklistedLocation(Kind, Loc);
  1727. // If location is unknown, this may be a compiler-generated function. Assume
  1728. // it's located in the main file.
  1729. auto &SM = Context.getSourceManager();
  1730. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1731. return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
  1732. }
  1733. return false;
  1734. }
  1735. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1736. SourceLocation Loc, QualType Ty,
  1737. StringRef Category) const {
  1738. // For now globals can be blacklisted only in ASan and KASan.
  1739. const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
  1740. (SanitizerKind::Address | SanitizerKind::KernelAddress |
  1741. SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
  1742. if (!EnabledAsanMask)
  1743. return false;
  1744. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1745. if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
  1746. return true;
  1747. if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
  1748. return true;
  1749. // Check global type.
  1750. if (!Ty.isNull()) {
  1751. // Drill down the array types: if global variable of a fixed type is
  1752. // blacklisted, we also don't instrument arrays of them.
  1753. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1754. Ty = AT->getElementType();
  1755. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1756. // We allow to blacklist only record types (classes, structs etc.)
  1757. if (Ty->isRecordType()) {
  1758. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1759. if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
  1760. return true;
  1761. }
  1762. }
  1763. return false;
  1764. }
  1765. bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  1766. StringRef Category) const {
  1767. const auto &XRayFilter = getContext().getXRayFilter();
  1768. using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
  1769. auto Attr = ImbueAttr::NONE;
  1770. if (Loc.isValid())
  1771. Attr = XRayFilter.shouldImbueLocation(Loc, Category);
  1772. if (Attr == ImbueAttr::NONE)
  1773. Attr = XRayFilter.shouldImbueFunction(Fn->getName());
  1774. switch (Attr) {
  1775. case ImbueAttr::NONE:
  1776. return false;
  1777. case ImbueAttr::ALWAYS:
  1778. Fn->addFnAttr("function-instrument", "xray-always");
  1779. break;
  1780. case ImbueAttr::ALWAYS_ARG1:
  1781. Fn->addFnAttr("function-instrument", "xray-always");
  1782. Fn->addFnAttr("xray-log-args", "1");
  1783. break;
  1784. case ImbueAttr::NEVER:
  1785. Fn->addFnAttr("function-instrument", "xray-never");
  1786. break;
  1787. }
  1788. return true;
  1789. }
  1790. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1791. // Never defer when EmitAllDecls is specified.
  1792. if (LangOpts.EmitAllDecls)
  1793. return true;
  1794. if (CodeGenOpts.KeepStaticConsts) {
  1795. const auto *VD = dyn_cast<VarDecl>(Global);
  1796. if (VD && VD->getType().isConstQualified() &&
  1797. VD->getStorageDuration() == SD_Static)
  1798. return true;
  1799. }
  1800. return getContext().DeclMustBeEmitted(Global);
  1801. }
  1802. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1803. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1804. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1805. // Implicit template instantiations may change linkage if they are later
  1806. // explicitly instantiated, so they should not be emitted eagerly.
  1807. return false;
  1808. if (const auto *VD = dyn_cast<VarDecl>(Global))
  1809. if (Context.getInlineVariableDefinitionKind(VD) ==
  1810. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  1811. // A definition of an inline constexpr static data member may change
  1812. // linkage later if it's redeclared outside the class.
  1813. return false;
  1814. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1815. // codegen for global variables, because they may be marked as threadprivate.
  1816. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1817. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
  1818. !isTypeConstant(Global->getType(), false) &&
  1819. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
  1820. return false;
  1821. return true;
  1822. }
  1823. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  1824. const CXXUuidofExpr* E) {
  1825. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1826. // well-formed.
  1827. StringRef Uuid = E->getUuidStr();
  1828. std::string Name = "_GUID_" + Uuid.lower();
  1829. std::replace(Name.begin(), Name.end(), '-', '_');
  1830. // The UUID descriptor should be pointer aligned.
  1831. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  1832. // Look for an existing global.
  1833. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1834. return ConstantAddress(GV, Alignment);
  1835. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1836. assert(Init && "failed to initialize as constant");
  1837. auto *GV = new llvm::GlobalVariable(
  1838. getModule(), Init->getType(),
  1839. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1840. if (supportsCOMDAT())
  1841. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1842. setDSOLocal(GV);
  1843. return ConstantAddress(GV, Alignment);
  1844. }
  1845. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1846. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1847. assert(AA && "No alias?");
  1848. CharUnits Alignment = getContext().getDeclAlign(VD);
  1849. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1850. // See if there is already something with the target's name in the module.
  1851. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1852. if (Entry) {
  1853. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1854. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1855. return ConstantAddress(Ptr, Alignment);
  1856. }
  1857. llvm::Constant *Aliasee;
  1858. if (isa<llvm::FunctionType>(DeclTy))
  1859. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1860. GlobalDecl(cast<FunctionDecl>(VD)),
  1861. /*ForVTable=*/false);
  1862. else
  1863. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1864. llvm::PointerType::getUnqual(DeclTy),
  1865. nullptr);
  1866. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1867. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1868. WeakRefReferences.insert(F);
  1869. return ConstantAddress(Aliasee, Alignment);
  1870. }
  1871. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1872. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1873. // Weak references don't produce any output by themselves.
  1874. if (Global->hasAttr<WeakRefAttr>())
  1875. return;
  1876. // If this is an alias definition (which otherwise looks like a declaration)
  1877. // emit it now.
  1878. if (Global->hasAttr<AliasAttr>())
  1879. return EmitAliasDefinition(GD);
  1880. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  1881. if (Global->hasAttr<IFuncAttr>())
  1882. return emitIFuncDefinition(GD);
  1883. // If this is a cpu_dispatch multiversion function, emit the resolver.
  1884. if (Global->hasAttr<CPUDispatchAttr>())
  1885. return emitCPUDispatchDefinition(GD);
  1886. // If this is CUDA, be selective about which declarations we emit.
  1887. if (LangOpts.CUDA) {
  1888. if (LangOpts.CUDAIsDevice) {
  1889. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1890. !Global->hasAttr<CUDAGlobalAttr>() &&
  1891. !Global->hasAttr<CUDAConstantAttr>() &&
  1892. !Global->hasAttr<CUDASharedAttr>())
  1893. return;
  1894. } else {
  1895. // We need to emit host-side 'shadows' for all global
  1896. // device-side variables because the CUDA runtime needs their
  1897. // size and host-side address in order to provide access to
  1898. // their device-side incarnations.
  1899. // So device-only functions are the only things we skip.
  1900. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  1901. Global->hasAttr<CUDADeviceAttr>())
  1902. return;
  1903. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  1904. "Expected Variable or Function");
  1905. }
  1906. }
  1907. if (LangOpts.OpenMP) {
  1908. // If this is OpenMP device, check if it is legal to emit this global
  1909. // normally.
  1910. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  1911. return;
  1912. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  1913. if (MustBeEmitted(Global))
  1914. EmitOMPDeclareReduction(DRD);
  1915. return;
  1916. } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
  1917. if (MustBeEmitted(Global))
  1918. EmitOMPDeclareMapper(DMD);
  1919. return;
  1920. }
  1921. }
  1922. // Ignore declarations, they will be emitted on their first use.
  1923. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1924. // Forward declarations are emitted lazily on first use.
  1925. if (!FD->doesThisDeclarationHaveABody()) {
  1926. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1927. return;
  1928. StringRef MangledName = getMangledName(GD);
  1929. // Compute the function info and LLVM type.
  1930. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1931. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1932. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1933. /*DontDefer=*/false);
  1934. return;
  1935. }
  1936. } else {
  1937. const auto *VD = cast<VarDecl>(Global);
  1938. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1939. if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1940. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  1941. if (LangOpts.OpenMP) {
  1942. // Emit declaration of the must-be-emitted declare target variable.
  1943. if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  1944. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  1945. if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
  1946. (void)GetAddrOfGlobalVar(VD);
  1947. } else {
  1948. assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
  1949. "link claue expected.");
  1950. (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
  1951. }
  1952. return;
  1953. }
  1954. }
  1955. // If this declaration may have caused an inline variable definition to
  1956. // change linkage, make sure that it's emitted.
  1957. if (Context.getInlineVariableDefinitionKind(VD) ==
  1958. ASTContext::InlineVariableDefinitionKind::Strong)
  1959. GetAddrOfGlobalVar(VD);
  1960. return;
  1961. }
  1962. }
  1963. // Defer code generation to first use when possible, e.g. if this is an inline
  1964. // function. If the global must always be emitted, do it eagerly if possible
  1965. // to benefit from cache locality.
  1966. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1967. // Emit the definition if it can't be deferred.
  1968. EmitGlobalDefinition(GD);
  1969. return;
  1970. }
  1971. // If we're deferring emission of a C++ variable with an
  1972. // initializer, remember the order in which it appeared in the file.
  1973. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1974. cast<VarDecl>(Global)->hasInit()) {
  1975. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1976. CXXGlobalInits.push_back(nullptr);
  1977. }
  1978. StringRef MangledName = getMangledName(GD);
  1979. if (GetGlobalValue(MangledName) != nullptr) {
  1980. // The value has already been used and should therefore be emitted.
  1981. addDeferredDeclToEmit(GD);
  1982. } else if (MustBeEmitted(Global)) {
  1983. // The value must be emitted, but cannot be emitted eagerly.
  1984. assert(!MayBeEmittedEagerly(Global));
  1985. addDeferredDeclToEmit(GD);
  1986. } else {
  1987. // Otherwise, remember that we saw a deferred decl with this name. The
  1988. // first use of the mangled name will cause it to move into
  1989. // DeferredDeclsToEmit.
  1990. DeferredDecls[MangledName] = GD;
  1991. }
  1992. }
  1993. // Check if T is a class type with a destructor that's not dllimport.
  1994. static bool HasNonDllImportDtor(QualType T) {
  1995. if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
  1996. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1997. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  1998. return true;
  1999. return false;
  2000. }
  2001. namespace {
  2002. struct FunctionIsDirectlyRecursive
  2003. : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
  2004. const StringRef Name;
  2005. const Builtin::Context &BI;
  2006. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
  2007. : Name(N), BI(C) {}
  2008. bool VisitCallExpr(const CallExpr *E) {
  2009. const FunctionDecl *FD = E->getDirectCallee();
  2010. if (!FD)
  2011. return false;
  2012. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  2013. if (Attr && Name == Attr->getLabel())
  2014. return true;
  2015. unsigned BuiltinID = FD->getBuiltinID();
  2016. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  2017. return false;
  2018. StringRef BuiltinName = BI.getName(BuiltinID);
  2019. if (BuiltinName.startswith("__builtin_") &&
  2020. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  2021. return true;
  2022. }
  2023. return false;
  2024. }
  2025. bool VisitStmt(const Stmt *S) {
  2026. for (const Stmt *Child : S->children())
  2027. if (Child && this->Visit(Child))
  2028. return true;
  2029. return false;
  2030. }
  2031. };
  2032. // Make sure we're not referencing non-imported vars or functions.
  2033. struct DLLImportFunctionVisitor
  2034. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  2035. bool SafeToInline = true;
  2036. bool shouldVisitImplicitCode() const { return true; }
  2037. bool VisitVarDecl(VarDecl *VD) {
  2038. if (VD->getTLSKind()) {
  2039. // A thread-local variable cannot be imported.
  2040. SafeToInline = false;
  2041. return SafeToInline;
  2042. }
  2043. // A variable definition might imply a destructor call.
  2044. if (VD->isThisDeclarationADefinition())
  2045. SafeToInline = !HasNonDllImportDtor(VD->getType());
  2046. return SafeToInline;
  2047. }
  2048. bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  2049. if (const auto *D = E->getTemporary()->getDestructor())
  2050. SafeToInline = D->hasAttr<DLLImportAttr>();
  2051. return SafeToInline;
  2052. }
  2053. bool VisitDeclRefExpr(DeclRefExpr *E) {
  2054. ValueDecl *VD = E->getDecl();
  2055. if (isa<FunctionDecl>(VD))
  2056. SafeToInline = VD->hasAttr<DLLImportAttr>();
  2057. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  2058. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  2059. return SafeToInline;
  2060. }
  2061. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  2062. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  2063. return SafeToInline;
  2064. }
  2065. bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  2066. CXXMethodDecl *M = E->getMethodDecl();
  2067. if (!M) {
  2068. // Call through a pointer to member function. This is safe to inline.
  2069. SafeToInline = true;
  2070. } else {
  2071. SafeToInline = M->hasAttr<DLLImportAttr>();
  2072. }
  2073. return SafeToInline;
  2074. }
  2075. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  2076. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  2077. return SafeToInline;
  2078. }
  2079. bool VisitCXXNewExpr(CXXNewExpr *E) {
  2080. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  2081. return SafeToInline;
  2082. }
  2083. };
  2084. }
  2085. // isTriviallyRecursive - Check if this function calls another
  2086. // decl that, because of the asm attribute or the other decl being a builtin,
  2087. // ends up pointing to itself.
  2088. bool
  2089. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  2090. StringRef Name;
  2091. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  2092. // asm labels are a special kind of mangling we have to support.
  2093. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  2094. if (!Attr)
  2095. return false;
  2096. Name = Attr->getLabel();
  2097. } else {
  2098. Name = FD->getName();
  2099. }
  2100. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  2101. const Stmt *Body = FD->getBody();
  2102. return Body ? Walker.Visit(Body) : false;
  2103. }
  2104. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  2105. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  2106. return true;
  2107. const auto *F = cast<FunctionDecl>(GD.getDecl());
  2108. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  2109. return false;
  2110. if (F->hasAttr<DLLImportAttr>()) {
  2111. // Check whether it would be safe to inline this dllimport function.
  2112. DLLImportFunctionVisitor Visitor;
  2113. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  2114. if (!Visitor.SafeToInline)
  2115. return false;
  2116. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  2117. // Implicit destructor invocations aren't captured in the AST, so the
  2118. // check above can't see them. Check for them manually here.
  2119. for (const Decl *Member : Dtor->getParent()->decls())
  2120. if (isa<FieldDecl>(Member))
  2121. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  2122. return false;
  2123. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  2124. if (HasNonDllImportDtor(B.getType()))
  2125. return false;
  2126. }
  2127. }
  2128. // PR9614. Avoid cases where the source code is lying to us. An available
  2129. // externally function should have an equivalent function somewhere else,
  2130. // but a function that calls itself is clearly not equivalent to the real
  2131. // implementation.
  2132. // This happens in glibc's btowc and in some configure checks.
  2133. return !isTriviallyRecursive(F);
  2134. }
  2135. bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
  2136. return CodeGenOpts.OptimizationLevel > 0;
  2137. }
  2138. void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
  2139. llvm::GlobalValue *GV) {
  2140. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2141. if (FD->isCPUSpecificMultiVersion()) {
  2142. auto *Spec = FD->getAttr<CPUSpecificAttr>();
  2143. for (unsigned I = 0; I < Spec->cpus_size(); ++I)
  2144. EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
  2145. // Requires multiple emits.
  2146. } else
  2147. EmitGlobalFunctionDefinition(GD, GV);
  2148. }
  2149. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  2150. const auto *D = cast<ValueDecl>(GD.getDecl());
  2151. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  2152. Context.getSourceManager(),
  2153. "Generating code for declaration");
  2154. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2155. // At -O0, don't generate IR for functions with available_externally
  2156. // linkage.
  2157. if (!shouldEmitFunction(GD))
  2158. return;
  2159. llvm::TimeTraceScope TimeScope(
  2160. "CodeGen Function", [&]() { return FD->getQualifiedNameAsString(); });
  2161. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  2162. // Make sure to emit the definition(s) before we emit the thunks.
  2163. // This is necessary for the generation of certain thunks.
  2164. if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
  2165. ABI->emitCXXStructor(GD);
  2166. else if (FD->isMultiVersion())
  2167. EmitMultiVersionFunctionDefinition(GD, GV);
  2168. else
  2169. EmitGlobalFunctionDefinition(GD, GV);
  2170. if (Method->isVirtual())
  2171. getVTables().EmitThunks(GD);
  2172. return;
  2173. }
  2174. if (FD->isMultiVersion())
  2175. return EmitMultiVersionFunctionDefinition(GD, GV);
  2176. return EmitGlobalFunctionDefinition(GD, GV);
  2177. }
  2178. if (const auto *VD = dyn_cast<VarDecl>(D))
  2179. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  2180. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  2181. }
  2182. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2183. llvm::Function *NewFn);
  2184. static unsigned
  2185. TargetMVPriority(const TargetInfo &TI,
  2186. const CodeGenFunction::MultiVersionResolverOption &RO) {
  2187. unsigned Priority = 0;
  2188. for (StringRef Feat : RO.Conditions.Features)
  2189. Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
  2190. if (!RO.Conditions.Architecture.empty())
  2191. Priority = std::max(
  2192. Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
  2193. return Priority;
  2194. }
  2195. void CodeGenModule::emitMultiVersionFunctions() {
  2196. for (GlobalDecl GD : MultiVersionFuncs) {
  2197. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  2198. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  2199. getContext().forEachMultiversionedFunctionVersion(
  2200. FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
  2201. GlobalDecl CurGD{
  2202. (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
  2203. StringRef MangledName = getMangledName(CurGD);
  2204. llvm::Constant *Func = GetGlobalValue(MangledName);
  2205. if (!Func) {
  2206. if (CurFD->isDefined()) {
  2207. EmitGlobalFunctionDefinition(CurGD, nullptr);
  2208. Func = GetGlobalValue(MangledName);
  2209. } else {
  2210. const CGFunctionInfo &FI =
  2211. getTypes().arrangeGlobalDeclaration(GD);
  2212. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2213. Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
  2214. /*DontDefer=*/false, ForDefinition);
  2215. }
  2216. assert(Func && "This should have just been created");
  2217. }
  2218. const auto *TA = CurFD->getAttr<TargetAttr>();
  2219. llvm::SmallVector<StringRef, 8> Feats;
  2220. TA->getAddedFeatures(Feats);
  2221. Options.emplace_back(cast<llvm::Function>(Func),
  2222. TA->getArchitecture(), Feats);
  2223. });
  2224. llvm::Function *ResolverFunc;
  2225. const TargetInfo &TI = getTarget();
  2226. if (TI.supportsIFunc() || FD->isTargetMultiVersion())
  2227. ResolverFunc = cast<llvm::Function>(
  2228. GetGlobalValue((getMangledName(GD) + ".resolver").str()));
  2229. else
  2230. ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
  2231. if (supportsCOMDAT())
  2232. ResolverFunc->setComdat(
  2233. getModule().getOrInsertComdat(ResolverFunc->getName()));
  2234. llvm::stable_sort(
  2235. Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
  2236. const CodeGenFunction::MultiVersionResolverOption &RHS) {
  2237. return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
  2238. });
  2239. CodeGenFunction CGF(*this);
  2240. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  2241. }
  2242. }
  2243. void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
  2244. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2245. assert(FD && "Not a FunctionDecl?");
  2246. const auto *DD = FD->getAttr<CPUDispatchAttr>();
  2247. assert(DD && "Not a cpu_dispatch Function?");
  2248. llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
  2249. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  2250. const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
  2251. DeclTy = getTypes().GetFunctionType(FInfo);
  2252. }
  2253. StringRef ResolverName = getMangledName(GD);
  2254. llvm::Type *ResolverType;
  2255. GlobalDecl ResolverGD;
  2256. if (getTarget().supportsIFunc())
  2257. ResolverType = llvm::FunctionType::get(
  2258. llvm::PointerType::get(DeclTy,
  2259. Context.getTargetAddressSpace(FD->getType())),
  2260. false);
  2261. else {
  2262. ResolverType = DeclTy;
  2263. ResolverGD = GD;
  2264. }
  2265. auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
  2266. ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
  2267. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  2268. const TargetInfo &Target = getTarget();
  2269. unsigned Index = 0;
  2270. for (const IdentifierInfo *II : DD->cpus()) {
  2271. // Get the name of the target function so we can look it up/create it.
  2272. std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
  2273. getCPUSpecificMangling(*this, II->getName());
  2274. llvm::Constant *Func = GetGlobalValue(MangledName);
  2275. if (!Func) {
  2276. GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
  2277. if (ExistingDecl.getDecl() &&
  2278. ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
  2279. EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
  2280. Func = GetGlobalValue(MangledName);
  2281. } else {
  2282. if (!ExistingDecl.getDecl())
  2283. ExistingDecl = GD.getWithMultiVersionIndex(Index);
  2284. Func = GetOrCreateLLVMFunction(
  2285. MangledName, DeclTy, ExistingDecl,
  2286. /*ForVTable=*/false, /*DontDefer=*/true,
  2287. /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
  2288. }
  2289. }
  2290. llvm::SmallVector<StringRef, 32> Features;
  2291. Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
  2292. llvm::transform(Features, Features.begin(),
  2293. [](StringRef Str) { return Str.substr(1); });
  2294. Features.erase(std::remove_if(
  2295. Features.begin(), Features.end(), [&Target](StringRef Feat) {
  2296. return !Target.validateCpuSupports(Feat);
  2297. }), Features.end());
  2298. Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
  2299. ++Index;
  2300. }
  2301. llvm::sort(
  2302. Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
  2303. const CodeGenFunction::MultiVersionResolverOption &RHS) {
  2304. return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
  2305. CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
  2306. });
  2307. // If the list contains multiple 'default' versions, such as when it contains
  2308. // 'pentium' and 'generic', don't emit the call to the generic one (since we
  2309. // always run on at least a 'pentium'). We do this by deleting the 'least
  2310. // advanced' (read, lowest mangling letter).
  2311. while (Options.size() > 1 &&
  2312. CodeGenFunction::GetX86CpuSupportsMask(
  2313. (Options.end() - 2)->Conditions.Features) == 0) {
  2314. StringRef LHSName = (Options.end() - 2)->Function->getName();
  2315. StringRef RHSName = (Options.end() - 1)->Function->getName();
  2316. if (LHSName.compare(RHSName) < 0)
  2317. Options.erase(Options.end() - 2);
  2318. else
  2319. Options.erase(Options.end() - 1);
  2320. }
  2321. CodeGenFunction CGF(*this);
  2322. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  2323. }
  2324. /// If a dispatcher for the specified mangled name is not in the module, create
  2325. /// and return an llvm Function with the specified type.
  2326. llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
  2327. GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
  2328. std::string MangledName =
  2329. getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
  2330. // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
  2331. // a separate resolver).
  2332. std::string ResolverName = MangledName;
  2333. if (getTarget().supportsIFunc())
  2334. ResolverName += ".ifunc";
  2335. else if (FD->isTargetMultiVersion())
  2336. ResolverName += ".resolver";
  2337. // If this already exists, just return that one.
  2338. if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
  2339. return ResolverGV;
  2340. // Since this is the first time we've created this IFunc, make sure
  2341. // that we put this multiversioned function into the list to be
  2342. // replaced later if necessary (target multiversioning only).
  2343. if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
  2344. MultiVersionFuncs.push_back(GD);
  2345. if (getTarget().supportsIFunc()) {
  2346. llvm::Type *ResolverType = llvm::FunctionType::get(
  2347. llvm::PointerType::get(
  2348. DeclTy, getContext().getTargetAddressSpace(FD->getType())),
  2349. false);
  2350. llvm::Constant *Resolver = GetOrCreateLLVMFunction(
  2351. MangledName + ".resolver", ResolverType, GlobalDecl{},
  2352. /*ForVTable=*/false);
  2353. llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
  2354. DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
  2355. GIF->setName(ResolverName);
  2356. SetCommonAttributes(FD, GIF);
  2357. return GIF;
  2358. }
  2359. llvm::Constant *Resolver = GetOrCreateLLVMFunction(
  2360. ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
  2361. assert(isa<llvm::GlobalValue>(Resolver) &&
  2362. "Resolver should be created for the first time");
  2363. SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
  2364. return Resolver;
  2365. }
  2366. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  2367. /// module, create and return an llvm Function with the specified type. If there
  2368. /// is something in the module with the specified name, return it potentially
  2369. /// bitcasted to the right type.
  2370. ///
  2371. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2372. /// to set the attributes on the function when it is first created.
  2373. llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
  2374. StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
  2375. bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
  2376. ForDefinition_t IsForDefinition) {
  2377. const Decl *D = GD.getDecl();
  2378. // Any attempts to use a MultiVersion function should result in retrieving
  2379. // the iFunc instead. Name Mangling will handle the rest of the changes.
  2380. if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
  2381. // For the device mark the function as one that should be emitted.
  2382. if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
  2383. !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
  2384. !DontDefer && !IsForDefinition) {
  2385. if (const FunctionDecl *FDDef = FD->getDefinition()) {
  2386. GlobalDecl GDDef;
  2387. if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
  2388. GDDef = GlobalDecl(CD, GD.getCtorType());
  2389. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
  2390. GDDef = GlobalDecl(DD, GD.getDtorType());
  2391. else
  2392. GDDef = GlobalDecl(FDDef);
  2393. EmitGlobal(GDDef);
  2394. }
  2395. }
  2396. if (FD->isMultiVersion()) {
  2397. const auto *TA = FD->getAttr<TargetAttr>();
  2398. if (TA && TA->isDefaultVersion())
  2399. UpdateMultiVersionNames(GD, FD);
  2400. if (!IsForDefinition)
  2401. return GetOrCreateMultiVersionResolver(GD, Ty, FD);
  2402. }
  2403. }
  2404. // Lookup the entry, lazily creating it if necessary.
  2405. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2406. if (Entry) {
  2407. if (WeakRefReferences.erase(Entry)) {
  2408. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  2409. if (FD && !FD->hasAttr<WeakAttr>())
  2410. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2411. }
  2412. // Handle dropped DLL attributes.
  2413. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
  2414. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2415. setDSOLocal(Entry);
  2416. }
  2417. // If there are two attempts to define the same mangled name, issue an
  2418. // error.
  2419. if (IsForDefinition && !Entry->isDeclaration()) {
  2420. GlobalDecl OtherGD;
  2421. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  2422. // to make sure that we issue an error only once.
  2423. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2424. (GD.getCanonicalDecl().getDecl() !=
  2425. OtherGD.getCanonicalDecl().getDecl()) &&
  2426. DiagnosedConflictingDefinitions.insert(GD).second) {
  2427. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
  2428. << MangledName;
  2429. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2430. diag::note_previous_definition);
  2431. }
  2432. }
  2433. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  2434. (Entry->getType()->getElementType() == Ty)) {
  2435. return Entry;
  2436. }
  2437. // Make sure the result is of the correct type.
  2438. // (If function is requested for a definition, we always need to create a new
  2439. // function, not just return a bitcast.)
  2440. if (!IsForDefinition)
  2441. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  2442. }
  2443. // This function doesn't have a complete type (for example, the return
  2444. // type is an incomplete struct). Use a fake type instead, and make
  2445. // sure not to try to set attributes.
  2446. bool IsIncompleteFunction = false;
  2447. llvm::FunctionType *FTy;
  2448. if (isa<llvm::FunctionType>(Ty)) {
  2449. FTy = cast<llvm::FunctionType>(Ty);
  2450. } else {
  2451. FTy = llvm::FunctionType::get(VoidTy, false);
  2452. IsIncompleteFunction = true;
  2453. }
  2454. llvm::Function *F =
  2455. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  2456. Entry ? StringRef() : MangledName, &getModule());
  2457. // If we already created a function with the same mangled name (but different
  2458. // type) before, take its name and add it to the list of functions to be
  2459. // replaced with F at the end of CodeGen.
  2460. //
  2461. // This happens if there is a prototype for a function (e.g. "int f()") and
  2462. // then a definition of a different type (e.g. "int f(int x)").
  2463. if (Entry) {
  2464. F->takeName(Entry);
  2465. // This might be an implementation of a function without a prototype, in
  2466. // which case, try to do special replacement of calls which match the new
  2467. // prototype. The really key thing here is that we also potentially drop
  2468. // arguments from the call site so as to make a direct call, which makes the
  2469. // inliner happier and suppresses a number of optimizer warnings (!) about
  2470. // dropping arguments.
  2471. if (!Entry->use_empty()) {
  2472. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  2473. Entry->removeDeadConstantUsers();
  2474. }
  2475. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  2476. F, Entry->getType()->getElementType()->getPointerTo());
  2477. addGlobalValReplacement(Entry, BC);
  2478. }
  2479. assert(F->getName() == MangledName && "name was uniqued!");
  2480. if (D)
  2481. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  2482. if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
  2483. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
  2484. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  2485. }
  2486. if (!DontDefer) {
  2487. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  2488. // each other bottoming out with the base dtor. Therefore we emit non-base
  2489. // dtors on usage, even if there is no dtor definition in the TU.
  2490. if (D && isa<CXXDestructorDecl>(D) &&
  2491. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  2492. GD.getDtorType()))
  2493. addDeferredDeclToEmit(GD);
  2494. // This is the first use or definition of a mangled name. If there is a
  2495. // deferred decl with this name, remember that we need to emit it at the end
  2496. // of the file.
  2497. auto DDI = DeferredDecls.find(MangledName);
  2498. if (DDI != DeferredDecls.end()) {
  2499. // Move the potentially referenced deferred decl to the
  2500. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  2501. // don't need it anymore).
  2502. addDeferredDeclToEmit(DDI->second);
  2503. DeferredDecls.erase(DDI);
  2504. // Otherwise, there are cases we have to worry about where we're
  2505. // using a declaration for which we must emit a definition but where
  2506. // we might not find a top-level definition:
  2507. // - member functions defined inline in their classes
  2508. // - friend functions defined inline in some class
  2509. // - special member functions with implicit definitions
  2510. // If we ever change our AST traversal to walk into class methods,
  2511. // this will be unnecessary.
  2512. //
  2513. // We also don't emit a definition for a function if it's going to be an
  2514. // entry in a vtable, unless it's already marked as used.
  2515. } else if (getLangOpts().CPlusPlus && D) {
  2516. // Look for a declaration that's lexically in a record.
  2517. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  2518. FD = FD->getPreviousDecl()) {
  2519. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  2520. if (FD->doesThisDeclarationHaveABody()) {
  2521. addDeferredDeclToEmit(GD.getWithDecl(FD));
  2522. break;
  2523. }
  2524. }
  2525. }
  2526. }
  2527. }
  2528. // Make sure the result is of the requested type.
  2529. if (!IsIncompleteFunction) {
  2530. assert(F->getType()->getElementType() == Ty);
  2531. return F;
  2532. }
  2533. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2534. return llvm::ConstantExpr::getBitCast(F, PTy);
  2535. }
  2536. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  2537. /// non-null, then this function will use the specified type if it has to
  2538. /// create it (this occurs when we see a definition of the function).
  2539. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  2540. llvm::Type *Ty,
  2541. bool ForVTable,
  2542. bool DontDefer,
  2543. ForDefinition_t IsForDefinition) {
  2544. // If there was no specific requested type, just convert it now.
  2545. if (!Ty) {
  2546. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2547. Ty = getTypes().ConvertType(FD->getType());
  2548. }
  2549. // Devirtualized destructor calls may come through here instead of via
  2550. // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
  2551. // of the complete destructor when necessary.
  2552. if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
  2553. if (getTarget().getCXXABI().isMicrosoft() &&
  2554. GD.getDtorType() == Dtor_Complete &&
  2555. DD->getParent()->getNumVBases() == 0)
  2556. GD = GlobalDecl(DD, Dtor_Base);
  2557. }
  2558. StringRef MangledName = getMangledName(GD);
  2559. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  2560. /*IsThunk=*/false, llvm::AttributeList(),
  2561. IsForDefinition);
  2562. }
  2563. static const FunctionDecl *
  2564. GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
  2565. TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
  2566. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2567. IdentifierInfo &CII = C.Idents.get(Name);
  2568. for (const auto &Result : DC->lookup(&CII))
  2569. if (const auto FD = dyn_cast<FunctionDecl>(Result))
  2570. return FD;
  2571. if (!C.getLangOpts().CPlusPlus)
  2572. return nullptr;
  2573. // Demangle the premangled name from getTerminateFn()
  2574. IdentifierInfo &CXXII =
  2575. (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
  2576. ? C.Idents.get("terminate")
  2577. : C.Idents.get(Name);
  2578. for (const auto &N : {"__cxxabiv1", "std"}) {
  2579. IdentifierInfo &NS = C.Idents.get(N);
  2580. for (const auto &Result : DC->lookup(&NS)) {
  2581. NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
  2582. if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
  2583. for (const auto &Result : LSD->lookup(&NS))
  2584. if ((ND = dyn_cast<NamespaceDecl>(Result)))
  2585. break;
  2586. if (ND)
  2587. for (const auto &Result : ND->lookup(&CXXII))
  2588. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  2589. return FD;
  2590. }
  2591. }
  2592. return nullptr;
  2593. }
  2594. /// CreateRuntimeFunction - Create a new runtime function with the specified
  2595. /// type and name.
  2596. llvm::FunctionCallee
  2597. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
  2598. llvm::AttributeList ExtraAttrs,
  2599. bool Local) {
  2600. llvm::Constant *C =
  2601. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  2602. /*DontDefer=*/false, /*IsThunk=*/false,
  2603. ExtraAttrs);
  2604. if (auto *F = dyn_cast<llvm::Function>(C)) {
  2605. if (F->empty()) {
  2606. F->setCallingConv(getRuntimeCC());
  2607. if (!Local && getTriple().isOSBinFormatCOFF() &&
  2608. !getCodeGenOpts().LTOVisibilityPublicStd &&
  2609. !getTriple().isWindowsGNUEnvironment()) {
  2610. const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
  2611. if (!FD || FD->hasAttr<DLLImportAttr>()) {
  2612. F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2613. F->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2614. }
  2615. }
  2616. setDSOLocal(F);
  2617. }
  2618. }
  2619. return {FTy, C};
  2620. }
  2621. /// isTypeConstant - Determine whether an object of this type can be emitted
  2622. /// as a constant.
  2623. ///
  2624. /// If ExcludeCtor is true, the duration when the object's constructor runs
  2625. /// will not be considered. The caller will need to verify that the object is
  2626. /// not written to during its construction.
  2627. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  2628. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  2629. return false;
  2630. if (Context.getLangOpts().CPlusPlus) {
  2631. if (const CXXRecordDecl *Record
  2632. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  2633. return ExcludeCtor && !Record->hasMutableFields() &&
  2634. Record->hasTrivialDestructor();
  2635. }
  2636. return true;
  2637. }
  2638. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  2639. /// create and return an llvm GlobalVariable with the specified type. If there
  2640. /// is something in the module with the specified name, return it potentially
  2641. /// bitcasted to the right type.
  2642. ///
  2643. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2644. /// to set the attributes on the global when it is first created.
  2645. ///
  2646. /// If IsForDefinition is true, it is guaranteed that an actual global with
  2647. /// type Ty will be returned, not conversion of a variable with the same
  2648. /// mangled name but some other type.
  2649. llvm::Constant *
  2650. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  2651. llvm::PointerType *Ty,
  2652. const VarDecl *D,
  2653. ForDefinition_t IsForDefinition) {
  2654. // Lookup the entry, lazily creating it if necessary.
  2655. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2656. if (Entry) {
  2657. if (WeakRefReferences.erase(Entry)) {
  2658. if (D && !D->hasAttr<WeakAttr>())
  2659. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2660. }
  2661. // Handle dropped DLL attributes.
  2662. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2663. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2664. if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
  2665. getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
  2666. if (Entry->getType() == Ty)
  2667. return Entry;
  2668. // If there are two attempts to define the same mangled name, issue an
  2669. // error.
  2670. if (IsForDefinition && !Entry->isDeclaration()) {
  2671. GlobalDecl OtherGD;
  2672. const VarDecl *OtherD;
  2673. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  2674. // to make sure that we issue an error only once.
  2675. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  2676. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  2677. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  2678. OtherD->hasInit() &&
  2679. DiagnosedConflictingDefinitions.insert(D).second) {
  2680. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
  2681. << MangledName;
  2682. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2683. diag::note_previous_definition);
  2684. }
  2685. }
  2686. // Make sure the result is of the correct type.
  2687. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  2688. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  2689. // (If global is requested for a definition, we always need to create a new
  2690. // global, not just return a bitcast.)
  2691. if (!IsForDefinition)
  2692. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  2693. }
  2694. auto AddrSpace = GetGlobalVarAddressSpace(D);
  2695. auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
  2696. auto *GV = new llvm::GlobalVariable(
  2697. getModule(), Ty->getElementType(), false,
  2698. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  2699. llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
  2700. // If we already created a global with the same mangled name (but different
  2701. // type) before, take its name and remove it from its parent.
  2702. if (Entry) {
  2703. GV->takeName(Entry);
  2704. if (!Entry->use_empty()) {
  2705. llvm::Constant *NewPtrForOldDecl =
  2706. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2707. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2708. }
  2709. Entry->eraseFromParent();
  2710. }
  2711. // This is the first use or definition of a mangled name. If there is a
  2712. // deferred decl with this name, remember that we need to emit it at the end
  2713. // of the file.
  2714. auto DDI = DeferredDecls.find(MangledName);
  2715. if (DDI != DeferredDecls.end()) {
  2716. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  2717. // list, and remove it from DeferredDecls (since we don't need it anymore).
  2718. addDeferredDeclToEmit(DDI->second);
  2719. DeferredDecls.erase(DDI);
  2720. }
  2721. // Handle things which are present even on external declarations.
  2722. if (D) {
  2723. if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
  2724. getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
  2725. // FIXME: This code is overly simple and should be merged with other global
  2726. // handling.
  2727. GV->setConstant(isTypeConstant(D->getType(), false));
  2728. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2729. setLinkageForGV(GV, D);
  2730. if (D->getTLSKind()) {
  2731. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2732. CXXThreadLocals.push_back(D);
  2733. setTLSMode(GV, *D);
  2734. }
  2735. setGVProperties(GV, D);
  2736. // If required by the ABI, treat declarations of static data members with
  2737. // inline initializers as definitions.
  2738. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  2739. EmitGlobalVarDefinition(D);
  2740. }
  2741. // Emit section information for extern variables.
  2742. if (D->hasExternalStorage()) {
  2743. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  2744. GV->setSection(SA->getName());
  2745. }
  2746. // Handle XCore specific ABI requirements.
  2747. if (getTriple().getArch() == llvm::Triple::xcore &&
  2748. D->getLanguageLinkage() == CLanguageLinkage &&
  2749. D->getType().isConstant(Context) &&
  2750. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  2751. GV->setSection(".cp.rodata");
  2752. // Check if we a have a const declaration with an initializer, we may be
  2753. // able to emit it as available_externally to expose it's value to the
  2754. // optimizer.
  2755. if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
  2756. D->getType().isConstQualified() && !GV->hasInitializer() &&
  2757. !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
  2758. const auto *Record =
  2759. Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
  2760. bool HasMutableFields = Record && Record->hasMutableFields();
  2761. if (!HasMutableFields) {
  2762. const VarDecl *InitDecl;
  2763. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2764. if (InitExpr) {
  2765. ConstantEmitter emitter(*this);
  2766. llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
  2767. if (Init) {
  2768. auto *InitType = Init->getType();
  2769. if (GV->getType()->getElementType() != InitType) {
  2770. // The type of the initializer does not match the definition.
  2771. // This happens when an initializer has a different type from
  2772. // the type of the global (because of padding at the end of a
  2773. // structure for instance).
  2774. GV->setName(StringRef());
  2775. // Make a new global with the correct type, this is now guaranteed
  2776. // to work.
  2777. auto *NewGV = cast<llvm::GlobalVariable>(
  2778. GetAddrOfGlobalVar(D, InitType, IsForDefinition));
  2779. // Erase the old global, since it is no longer used.
  2780. GV->eraseFromParent();
  2781. GV = NewGV;
  2782. } else {
  2783. GV->setInitializer(Init);
  2784. GV->setConstant(true);
  2785. GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  2786. }
  2787. emitter.finalize(GV);
  2788. }
  2789. }
  2790. }
  2791. }
  2792. }
  2793. LangAS ExpectedAS =
  2794. D ? D->getType().getAddressSpace()
  2795. : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
  2796. assert(getContext().getTargetAddressSpace(ExpectedAS) ==
  2797. Ty->getPointerAddressSpace());
  2798. if (AddrSpace != ExpectedAS)
  2799. return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
  2800. ExpectedAS, Ty);
  2801. if (GV->isDeclaration())
  2802. getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
  2803. return GV;
  2804. }
  2805. llvm::Constant *
  2806. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  2807. ForDefinition_t IsForDefinition) {
  2808. const Decl *D = GD.getDecl();
  2809. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  2810. return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2811. /*DontDefer=*/false, IsForDefinition);
  2812. else if (isa<CXXMethodDecl>(D)) {
  2813. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  2814. cast<CXXMethodDecl>(D));
  2815. auto Ty = getTypes().GetFunctionType(*FInfo);
  2816. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2817. IsForDefinition);
  2818. } else if (isa<FunctionDecl>(D)) {
  2819. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2820. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2821. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2822. IsForDefinition);
  2823. } else
  2824. return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
  2825. IsForDefinition);
  2826. }
  2827. llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
  2828. StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
  2829. unsigned Alignment) {
  2830. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  2831. llvm::GlobalVariable *OldGV = nullptr;
  2832. if (GV) {
  2833. // Check if the variable has the right type.
  2834. if (GV->getType()->getElementType() == Ty)
  2835. return GV;
  2836. // Because C++ name mangling, the only way we can end up with an already
  2837. // existing global with the same name is if it has been declared extern "C".
  2838. assert(GV->isDeclaration() && "Declaration has wrong type!");
  2839. OldGV = GV;
  2840. }
  2841. // Create a new variable.
  2842. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  2843. Linkage, nullptr, Name);
  2844. if (OldGV) {
  2845. // Replace occurrences of the old variable if needed.
  2846. GV->takeName(OldGV);
  2847. if (!OldGV->use_empty()) {
  2848. llvm::Constant *NewPtrForOldDecl =
  2849. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2850. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  2851. }
  2852. OldGV->eraseFromParent();
  2853. }
  2854. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  2855. !GV->hasAvailableExternallyLinkage())
  2856. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2857. GV->setAlignment(Alignment);
  2858. return GV;
  2859. }
  2860. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  2861. /// given global variable. If Ty is non-null and if the global doesn't exist,
  2862. /// then it will be created with the specified type instead of whatever the
  2863. /// normal requested type would be. If IsForDefinition is true, it is guaranteed
  2864. /// that an actual global with type Ty will be returned, not conversion of a
  2865. /// variable with the same mangled name but some other type.
  2866. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  2867. llvm::Type *Ty,
  2868. ForDefinition_t IsForDefinition) {
  2869. assert(D->hasGlobalStorage() && "Not a global variable");
  2870. QualType ASTTy = D->getType();
  2871. if (!Ty)
  2872. Ty = getTypes().ConvertTypeForMem(ASTTy);
  2873. llvm::PointerType *PTy =
  2874. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  2875. StringRef MangledName = getMangledName(D);
  2876. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  2877. }
  2878. /// CreateRuntimeVariable - Create a new runtime global variable with the
  2879. /// specified type and name.
  2880. llvm::Constant *
  2881. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  2882. StringRef Name) {
  2883. auto *Ret =
  2884. GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  2885. setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
  2886. return Ret;
  2887. }
  2888. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  2889. assert(!D->getInit() && "Cannot emit definite definitions here!");
  2890. StringRef MangledName = getMangledName(D);
  2891. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  2892. // We already have a definition, not declaration, with the same mangled name.
  2893. // Emitting of declaration is not required (and actually overwrites emitted
  2894. // definition).
  2895. if (GV && !GV->isDeclaration())
  2896. return;
  2897. // If we have not seen a reference to this variable yet, place it into the
  2898. // deferred declarations table to be emitted if needed later.
  2899. if (!MustBeEmitted(D) && !GV) {
  2900. DeferredDecls[MangledName] = D;
  2901. return;
  2902. }
  2903. // The tentative definition is the only definition.
  2904. EmitGlobalVarDefinition(D);
  2905. }
  2906. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  2907. return Context.toCharUnitsFromBits(
  2908. getDataLayout().getTypeStoreSizeInBits(Ty));
  2909. }
  2910. LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
  2911. LangAS AddrSpace = LangAS::Default;
  2912. if (LangOpts.OpenCL) {
  2913. AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
  2914. assert(AddrSpace == LangAS::opencl_global ||
  2915. AddrSpace == LangAS::opencl_constant ||
  2916. AddrSpace == LangAS::opencl_local ||
  2917. AddrSpace >= LangAS::FirstTargetAddressSpace);
  2918. return AddrSpace;
  2919. }
  2920. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  2921. if (D && D->hasAttr<CUDAConstantAttr>())
  2922. return LangAS::cuda_constant;
  2923. else if (D && D->hasAttr<CUDASharedAttr>())
  2924. return LangAS::cuda_shared;
  2925. else if (D && D->hasAttr<CUDADeviceAttr>())
  2926. return LangAS::cuda_device;
  2927. else if (D && D->getType().isConstQualified())
  2928. return LangAS::cuda_constant;
  2929. else
  2930. return LangAS::cuda_device;
  2931. }
  2932. if (LangOpts.OpenMP) {
  2933. LangAS AS;
  2934. if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
  2935. return AS;
  2936. }
  2937. return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
  2938. }
  2939. LangAS CodeGenModule::getStringLiteralAddressSpace() const {
  2940. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  2941. if (LangOpts.OpenCL)
  2942. return LangAS::opencl_constant;
  2943. if (auto AS = getTarget().getConstantAddressSpace())
  2944. return AS.getValue();
  2945. return LangAS::Default;
  2946. }
  2947. // In address space agnostic languages, string literals are in default address
  2948. // space in AST. However, certain targets (e.g. amdgcn) request them to be
  2949. // emitted in constant address space in LLVM IR. To be consistent with other
  2950. // parts of AST, string literal global variables in constant address space
  2951. // need to be casted to default address space before being put into address
  2952. // map and referenced by other part of CodeGen.
  2953. // In OpenCL, string literals are in constant address space in AST, therefore
  2954. // they should not be casted to default address space.
  2955. static llvm::Constant *
  2956. castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
  2957. llvm::GlobalVariable *GV) {
  2958. llvm::Constant *Cast = GV;
  2959. if (!CGM.getLangOpts().OpenCL) {
  2960. if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
  2961. if (AS != LangAS::Default)
  2962. Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
  2963. CGM, GV, AS.getValue(), LangAS::Default,
  2964. GV->getValueType()->getPointerTo(
  2965. CGM.getContext().getTargetAddressSpace(LangAS::Default)));
  2966. }
  2967. }
  2968. return Cast;
  2969. }
  2970. template<typename SomeDecl>
  2971. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  2972. llvm::GlobalValue *GV) {
  2973. if (!getLangOpts().CPlusPlus)
  2974. return;
  2975. // Must have 'used' attribute, or else inline assembly can't rely on
  2976. // the name existing.
  2977. if (!D->template hasAttr<UsedAttr>())
  2978. return;
  2979. // Must have internal linkage and an ordinary name.
  2980. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  2981. return;
  2982. // Must be in an extern "C" context. Entities declared directly within
  2983. // a record are not extern "C" even if the record is in such a context.
  2984. const SomeDecl *First = D->getFirstDecl();
  2985. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  2986. return;
  2987. // OK, this is an internal linkage entity inside an extern "C" linkage
  2988. // specification. Make a note of that so we can give it the "expected"
  2989. // mangled name if nothing else is using that name.
  2990. std::pair<StaticExternCMap::iterator, bool> R =
  2991. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  2992. // If we have multiple internal linkage entities with the same name
  2993. // in extern "C" regions, none of them gets that name.
  2994. if (!R.second)
  2995. R.first->second = nullptr;
  2996. }
  2997. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  2998. if (!CGM.supportsCOMDAT())
  2999. return false;
  3000. if (D.hasAttr<SelectAnyAttr>())
  3001. return true;
  3002. GVALinkage Linkage;
  3003. if (auto *VD = dyn_cast<VarDecl>(&D))
  3004. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  3005. else
  3006. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  3007. switch (Linkage) {
  3008. case GVA_Internal:
  3009. case GVA_AvailableExternally:
  3010. case GVA_StrongExternal:
  3011. return false;
  3012. case GVA_DiscardableODR:
  3013. case GVA_StrongODR:
  3014. return true;
  3015. }
  3016. llvm_unreachable("No such linkage");
  3017. }
  3018. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  3019. llvm::GlobalObject &GO) {
  3020. if (!shouldBeInCOMDAT(*this, D))
  3021. return;
  3022. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  3023. }
  3024. /// Pass IsTentative as true if you want to create a tentative definition.
  3025. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  3026. bool IsTentative) {
  3027. // OpenCL global variables of sampler type are translated to function calls,
  3028. // therefore no need to be translated.
  3029. QualType ASTTy = D->getType();
  3030. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  3031. return;
  3032. // If this is OpenMP device, check if it is legal to emit this global
  3033. // normally.
  3034. if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
  3035. OpenMPRuntime->emitTargetGlobalVariable(D))
  3036. return;
  3037. llvm::Constant *Init = nullptr;
  3038. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  3039. bool NeedsGlobalCtor = false;
  3040. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  3041. const VarDecl *InitDecl;
  3042. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  3043. Optional<ConstantEmitter> emitter;
  3044. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  3045. // as part of their declaration." Sema has already checked for
  3046. // error cases, so we just need to set Init to UndefValue.
  3047. bool IsCUDASharedVar =
  3048. getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
  3049. // Shadows of initialized device-side global variables are also left
  3050. // undefined.
  3051. bool IsCUDAShadowVar =
  3052. !getLangOpts().CUDAIsDevice &&
  3053. (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
  3054. D->hasAttr<CUDASharedAttr>());
  3055. if (getLangOpts().CUDA && (IsCUDASharedVar || IsCUDAShadowVar))
  3056. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  3057. else if (!InitExpr) {
  3058. // This is a tentative definition; tentative definitions are
  3059. // implicitly initialized with { 0 }.
  3060. //
  3061. // Note that tentative definitions are only emitted at the end of
  3062. // a translation unit, so they should never have incomplete
  3063. // type. In addition, EmitTentativeDefinition makes sure that we
  3064. // never attempt to emit a tentative definition if a real one
  3065. // exists. A use may still exists, however, so we still may need
  3066. // to do a RAUW.
  3067. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  3068. Init = EmitNullConstant(D->getType());
  3069. } else {
  3070. initializedGlobalDecl = GlobalDecl(D);
  3071. emitter.emplace(*this);
  3072. Init = emitter->tryEmitForInitializer(*InitDecl);
  3073. if (!Init) {
  3074. QualType T = InitExpr->getType();
  3075. if (D->getType()->isReferenceType())
  3076. T = D->getType();
  3077. if (getLangOpts().CPlusPlus) {
  3078. Init = EmitNullConstant(T);
  3079. NeedsGlobalCtor = true;
  3080. } else {
  3081. ErrorUnsupported(D, "static initializer");
  3082. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  3083. }
  3084. } else {
  3085. // We don't need an initializer, so remove the entry for the delayed
  3086. // initializer position (just in case this entry was delayed) if we
  3087. // also don't need to register a destructor.
  3088. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  3089. DelayedCXXInitPosition.erase(D);
  3090. }
  3091. }
  3092. llvm::Type* InitType = Init->getType();
  3093. llvm::Constant *Entry =
  3094. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  3095. // Strip off a bitcast if we got one back.
  3096. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  3097. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  3098. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  3099. // All zero index gep.
  3100. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  3101. Entry = CE->getOperand(0);
  3102. }
  3103. // Entry is now either a Function or GlobalVariable.
  3104. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  3105. // We have a definition after a declaration with the wrong type.
  3106. // We must make a new GlobalVariable* and update everything that used OldGV
  3107. // (a declaration or tentative definition) with the new GlobalVariable*
  3108. // (which will be a definition).
  3109. //
  3110. // This happens if there is a prototype for a global (e.g.
  3111. // "extern int x[];") and then a definition of a different type (e.g.
  3112. // "int x[10];"). This also happens when an initializer has a different type
  3113. // from the type of the global (this happens with unions).
  3114. if (!GV || GV->getType()->getElementType() != InitType ||
  3115. GV->getType()->getAddressSpace() !=
  3116. getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
  3117. // Move the old entry aside so that we'll create a new one.
  3118. Entry->setName(StringRef());
  3119. // Make a new global with the correct type, this is now guaranteed to work.
  3120. GV = cast<llvm::GlobalVariable>(
  3121. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
  3122. // Replace all uses of the old global with the new global
  3123. llvm::Constant *NewPtrForOldDecl =
  3124. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  3125. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  3126. // Erase the old global, since it is no longer used.
  3127. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  3128. }
  3129. MaybeHandleStaticInExternC(D, GV);
  3130. if (D->hasAttr<AnnotateAttr>())
  3131. AddGlobalAnnotations(D, GV);
  3132. // Set the llvm linkage type as appropriate.
  3133. llvm::GlobalValue::LinkageTypes Linkage =
  3134. getLLVMLinkageVarDefinition(D, GV->isConstant());
  3135. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  3136. // the device. [...]"
  3137. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  3138. // __device__, declares a variable that: [...]
  3139. // Is accessible from all the threads within the grid and from the host
  3140. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  3141. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  3142. if (GV && LangOpts.CUDA) {
  3143. if (LangOpts.CUDAIsDevice) {
  3144. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
  3145. GV->setExternallyInitialized(true);
  3146. } else {
  3147. // Host-side shadows of external declarations of device-side
  3148. // global variables become internal definitions. These have to
  3149. // be internal in order to prevent name conflicts with global
  3150. // host variables with the same name in a different TUs.
  3151. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
  3152. Linkage = llvm::GlobalValue::InternalLinkage;
  3153. // Shadow variables and their properties must be registered
  3154. // with CUDA runtime.
  3155. unsigned Flags = 0;
  3156. if (!D->hasDefinition())
  3157. Flags |= CGCUDARuntime::ExternDeviceVar;
  3158. if (D->hasAttr<CUDAConstantAttr>())
  3159. Flags |= CGCUDARuntime::ConstantDeviceVar;
  3160. // Extern global variables will be registered in the TU where they are
  3161. // defined.
  3162. if (!D->hasExternalStorage())
  3163. getCUDARuntime().registerDeviceVar(D, *GV, Flags);
  3164. } else if (D->hasAttr<CUDASharedAttr>())
  3165. // __shared__ variables are odd. Shadows do get created, but
  3166. // they are not registered with the CUDA runtime, so they
  3167. // can't really be used to access their device-side
  3168. // counterparts. It's not clear yet whether it's nvcc's bug or
  3169. // a feature, but we've got to do the same for compatibility.
  3170. Linkage = llvm::GlobalValue::InternalLinkage;
  3171. }
  3172. }
  3173. GV->setInitializer(Init);
  3174. if (emitter) emitter->finalize(GV);
  3175. // If it is safe to mark the global 'constant', do so now.
  3176. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  3177. isTypeConstant(D->getType(), true));
  3178. // If it is in a read-only section, mark it 'constant'.
  3179. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  3180. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  3181. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  3182. GV->setConstant(true);
  3183. }
  3184. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  3185. // On Darwin, if the normal linkage of a C++ thread_local variable is
  3186. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  3187. // copies within a linkage unit; otherwise, the backing variable has
  3188. // internal linkage and all accesses should just be calls to the
  3189. // Itanium-specified entry point, which has the normal linkage of the
  3190. // variable. This is to preserve the ability to change the implementation
  3191. // behind the scenes.
  3192. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  3193. Context.getTargetInfo().getTriple().isOSDarwin() &&
  3194. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  3195. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  3196. Linkage = llvm::GlobalValue::InternalLinkage;
  3197. GV->setLinkage(Linkage);
  3198. if (D->hasAttr<DLLImportAttr>())
  3199. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  3200. else if (D->hasAttr<DLLExportAttr>())
  3201. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  3202. else
  3203. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  3204. if (Linkage == llvm::GlobalVariable::CommonLinkage) {
  3205. // common vars aren't constant even if declared const.
  3206. GV->setConstant(false);
  3207. // Tentative definition of global variables may be initialized with
  3208. // non-zero null pointers. In this case they should have weak linkage
  3209. // since common linkage must have zero initializer and must not have
  3210. // explicit section therefore cannot have non-zero initial value.
  3211. if (!GV->getInitializer()->isNullValue())
  3212. GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
  3213. }
  3214. setNonAliasAttributes(D, GV);
  3215. if (D->getTLSKind() && !GV->isThreadLocal()) {
  3216. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  3217. CXXThreadLocals.push_back(D);
  3218. setTLSMode(GV, *D);
  3219. }
  3220. maybeSetTrivialComdat(*D, *GV);
  3221. // Emit the initializer function if necessary.
  3222. if (NeedsGlobalCtor || NeedsGlobalDtor)
  3223. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  3224. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  3225. // Emit global variable debug information.
  3226. if (CGDebugInfo *DI = getModuleDebugInfo())
  3227. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3228. DI->EmitGlobalVariable(GV, D);
  3229. }
  3230. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  3231. CodeGenModule &CGM, const VarDecl *D,
  3232. bool NoCommon) {
  3233. // Don't give variables common linkage if -fno-common was specified unless it
  3234. // was overridden by a NoCommon attribute.
  3235. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  3236. return true;
  3237. // C11 6.9.2/2:
  3238. // A declaration of an identifier for an object that has file scope without
  3239. // an initializer, and without a storage-class specifier or with the
  3240. // storage-class specifier static, constitutes a tentative definition.
  3241. if (D->getInit() || D->hasExternalStorage())
  3242. return true;
  3243. // A variable cannot be both common and exist in a section.
  3244. if (D->hasAttr<SectionAttr>())
  3245. return true;
  3246. // A variable cannot be both common and exist in a section.
  3247. // We don't try to determine which is the right section in the front-end.
  3248. // If no specialized section name is applicable, it will resort to default.
  3249. if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
  3250. D->hasAttr<PragmaClangDataSectionAttr>() ||
  3251. D->hasAttr<PragmaClangRodataSectionAttr>())
  3252. return true;
  3253. // Thread local vars aren't considered common linkage.
  3254. if (D->getTLSKind())
  3255. return true;
  3256. // Tentative definitions marked with WeakImportAttr are true definitions.
  3257. if (D->hasAttr<WeakImportAttr>())
  3258. return true;
  3259. // A variable cannot be both common and exist in a comdat.
  3260. if (shouldBeInCOMDAT(CGM, *D))
  3261. return true;
  3262. // Declarations with a required alignment do not have common linkage in MSVC
  3263. // mode.
  3264. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  3265. if (D->hasAttr<AlignedAttr>())
  3266. return true;
  3267. QualType VarType = D->getType();
  3268. if (Context.isAlignmentRequired(VarType))
  3269. return true;
  3270. if (const auto *RT = VarType->getAs<RecordType>()) {
  3271. const RecordDecl *RD = RT->getDecl();
  3272. for (const FieldDecl *FD : RD->fields()) {
  3273. if (FD->isBitField())
  3274. continue;
  3275. if (FD->hasAttr<AlignedAttr>())
  3276. return true;
  3277. if (Context.isAlignmentRequired(FD->getType()))
  3278. return true;
  3279. }
  3280. }
  3281. }
  3282. // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
  3283. // common symbols, so symbols with greater alignment requirements cannot be
  3284. // common.
  3285. // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
  3286. // alignments for common symbols via the aligncomm directive, so this
  3287. // restriction only applies to MSVC environments.
  3288. if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
  3289. Context.getTypeAlignIfKnown(D->getType()) >
  3290. Context.toBits(CharUnits::fromQuantity(32)))
  3291. return true;
  3292. return false;
  3293. }
  3294. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  3295. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  3296. if (Linkage == GVA_Internal)
  3297. return llvm::Function::InternalLinkage;
  3298. if (D->hasAttr<WeakAttr>()) {
  3299. if (IsConstantVariable)
  3300. return llvm::GlobalVariable::WeakODRLinkage;
  3301. else
  3302. return llvm::GlobalVariable::WeakAnyLinkage;
  3303. }
  3304. if (const auto *FD = D->getAsFunction())
  3305. if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
  3306. return llvm::GlobalVariable::LinkOnceAnyLinkage;
  3307. // We are guaranteed to have a strong definition somewhere else,
  3308. // so we can use available_externally linkage.
  3309. if (Linkage == GVA_AvailableExternally)
  3310. return llvm::GlobalValue::AvailableExternallyLinkage;
  3311. // Note that Apple's kernel linker doesn't support symbol
  3312. // coalescing, so we need to avoid linkonce and weak linkages there.
  3313. // Normally, this means we just map to internal, but for explicit
  3314. // instantiations we'll map to external.
  3315. // In C++, the compiler has to emit a definition in every translation unit
  3316. // that references the function. We should use linkonce_odr because
  3317. // a) if all references in this translation unit are optimized away, we
  3318. // don't need to codegen it. b) if the function persists, it needs to be
  3319. // merged with other definitions. c) C++ has the ODR, so we know the
  3320. // definition is dependable.
  3321. if (Linkage == GVA_DiscardableODR)
  3322. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  3323. : llvm::Function::InternalLinkage;
  3324. // An explicit instantiation of a template has weak linkage, since
  3325. // explicit instantiations can occur in multiple translation units
  3326. // and must all be equivalent. However, we are not allowed to
  3327. // throw away these explicit instantiations.
  3328. //
  3329. // We don't currently support CUDA device code spread out across multiple TUs,
  3330. // so say that CUDA templates are either external (for kernels) or internal.
  3331. // This lets llvm perform aggressive inter-procedural optimizations.
  3332. if (Linkage == GVA_StrongODR) {
  3333. if (Context.getLangOpts().AppleKext)
  3334. return llvm::Function::ExternalLinkage;
  3335. if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
  3336. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  3337. : llvm::Function::InternalLinkage;
  3338. return llvm::Function::WeakODRLinkage;
  3339. }
  3340. // C++ doesn't have tentative definitions and thus cannot have common
  3341. // linkage.
  3342. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  3343. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  3344. CodeGenOpts.NoCommon))
  3345. return llvm::GlobalVariable::CommonLinkage;
  3346. // selectany symbols are externally visible, so use weak instead of
  3347. // linkonce. MSVC optimizes away references to const selectany globals, so
  3348. // all definitions should be the same and ODR linkage should be used.
  3349. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  3350. if (D->hasAttr<SelectAnyAttr>())
  3351. return llvm::GlobalVariable::WeakODRLinkage;
  3352. // Otherwise, we have strong external linkage.
  3353. assert(Linkage == GVA_StrongExternal);
  3354. return llvm::GlobalVariable::ExternalLinkage;
  3355. }
  3356. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  3357. const VarDecl *VD, bool IsConstant) {
  3358. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  3359. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  3360. }
  3361. /// Replace the uses of a function that was declared with a non-proto type.
  3362. /// We want to silently drop extra arguments from call sites
  3363. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  3364. llvm::Function *newFn) {
  3365. // Fast path.
  3366. if (old->use_empty()) return;
  3367. llvm::Type *newRetTy = newFn->getReturnType();
  3368. SmallVector<llvm::Value*, 4> newArgs;
  3369. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  3370. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  3371. ui != ue; ) {
  3372. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  3373. llvm::User *user = use->getUser();
  3374. // Recognize and replace uses of bitcasts. Most calls to
  3375. // unprototyped functions will use bitcasts.
  3376. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  3377. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  3378. replaceUsesOfNonProtoConstant(bitcast, newFn);
  3379. continue;
  3380. }
  3381. // Recognize calls to the function.
  3382. llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
  3383. if (!callSite) continue;
  3384. if (!callSite->isCallee(&*use))
  3385. continue;
  3386. // If the return types don't match exactly, then we can't
  3387. // transform this call unless it's dead.
  3388. if (callSite->getType() != newRetTy && !callSite->use_empty())
  3389. continue;
  3390. // Get the call site's attribute list.
  3391. SmallVector<llvm::AttributeSet, 8> newArgAttrs;
  3392. llvm::AttributeList oldAttrs = callSite->getAttributes();
  3393. // If the function was passed too few arguments, don't transform.
  3394. unsigned newNumArgs = newFn->arg_size();
  3395. if (callSite->arg_size() < newNumArgs)
  3396. continue;
  3397. // If extra arguments were passed, we silently drop them.
  3398. // If any of the types mismatch, we don't transform.
  3399. unsigned argNo = 0;
  3400. bool dontTransform = false;
  3401. for (llvm::Argument &A : newFn->args()) {
  3402. if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
  3403. dontTransform = true;
  3404. break;
  3405. }
  3406. // Add any parameter attributes.
  3407. newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
  3408. argNo++;
  3409. }
  3410. if (dontTransform)
  3411. continue;
  3412. // Okay, we can transform this. Create the new call instruction and copy
  3413. // over the required information.
  3414. newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
  3415. // Copy over any operand bundles.
  3416. callSite->getOperandBundlesAsDefs(newBundles);
  3417. llvm::CallBase *newCall;
  3418. if (dyn_cast<llvm::CallInst>(callSite)) {
  3419. newCall =
  3420. llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
  3421. } else {
  3422. auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
  3423. newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
  3424. oldInvoke->getUnwindDest(), newArgs,
  3425. newBundles, "", callSite);
  3426. }
  3427. newArgs.clear(); // for the next iteration
  3428. if (!newCall->getType()->isVoidTy())
  3429. newCall->takeName(callSite);
  3430. newCall->setAttributes(llvm::AttributeList::get(
  3431. newFn->getContext(), oldAttrs.getFnAttributes(),
  3432. oldAttrs.getRetAttributes(), newArgAttrs));
  3433. newCall->setCallingConv(callSite->getCallingConv());
  3434. // Finally, remove the old call, replacing any uses with the new one.
  3435. if (!callSite->use_empty())
  3436. callSite->replaceAllUsesWith(newCall);
  3437. // Copy debug location attached to CI.
  3438. if (callSite->getDebugLoc())
  3439. newCall->setDebugLoc(callSite->getDebugLoc());
  3440. callSite->eraseFromParent();
  3441. }
  3442. }
  3443. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  3444. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  3445. /// existing call uses of the old function in the module, this adjusts them to
  3446. /// call the new function directly.
  3447. ///
  3448. /// This is not just a cleanup: the always_inline pass requires direct calls to
  3449. /// functions to be able to inline them. If there is a bitcast in the way, it
  3450. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  3451. /// run at -O0.
  3452. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  3453. llvm::Function *NewFn) {
  3454. // If we're redefining a global as a function, don't transform it.
  3455. if (!isa<llvm::Function>(Old)) return;
  3456. replaceUsesOfNonProtoConstant(Old, NewFn);
  3457. }
  3458. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  3459. auto DK = VD->isThisDeclarationADefinition();
  3460. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  3461. return;
  3462. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  3463. // If we have a definition, this might be a deferred decl. If the
  3464. // instantiation is explicit, make sure we emit it at the end.
  3465. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  3466. GetAddrOfGlobalVar(VD);
  3467. EmitTopLevelDecl(VD);
  3468. }
  3469. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  3470. llvm::GlobalValue *GV) {
  3471. const auto *D = cast<FunctionDecl>(GD.getDecl());
  3472. // Compute the function info and LLVM type.
  3473. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  3474. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  3475. // Get or create the prototype for the function.
  3476. if (!GV || (GV->getType()->getElementType() != Ty))
  3477. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  3478. /*DontDefer=*/true,
  3479. ForDefinition));
  3480. // Already emitted.
  3481. if (!GV->isDeclaration())
  3482. return;
  3483. // We need to set linkage and visibility on the function before
  3484. // generating code for it because various parts of IR generation
  3485. // want to propagate this information down (e.g. to local static
  3486. // declarations).
  3487. auto *Fn = cast<llvm::Function>(GV);
  3488. setFunctionLinkage(GD, Fn);
  3489. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  3490. setGVProperties(Fn, GD);
  3491. MaybeHandleStaticInExternC(D, Fn);
  3492. maybeSetTrivialComdat(*D, *Fn);
  3493. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  3494. setNonAliasAttributes(GD, Fn);
  3495. SetLLVMFunctionAttributesForDefinition(D, Fn);
  3496. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  3497. AddGlobalCtor(Fn, CA->getPriority());
  3498. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  3499. AddGlobalDtor(Fn, DA->getPriority());
  3500. if (D->hasAttr<AnnotateAttr>())
  3501. AddGlobalAnnotations(D, Fn);
  3502. }
  3503. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  3504. const auto *D = cast<ValueDecl>(GD.getDecl());
  3505. const AliasAttr *AA = D->getAttr<AliasAttr>();
  3506. assert(AA && "Not an alias?");
  3507. StringRef MangledName = getMangledName(GD);
  3508. if (AA->getAliasee() == MangledName) {
  3509. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3510. return;
  3511. }
  3512. // If there is a definition in the module, then it wins over the alias.
  3513. // This is dubious, but allow it to be safe. Just ignore the alias.
  3514. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3515. if (Entry && !Entry->isDeclaration())
  3516. return;
  3517. Aliases.push_back(GD);
  3518. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3519. // Create a reference to the named value. This ensures that it is emitted
  3520. // if a deferred decl.
  3521. llvm::Constant *Aliasee;
  3522. if (isa<llvm::FunctionType>(DeclTy))
  3523. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  3524. /*ForVTable=*/false);
  3525. else
  3526. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  3527. llvm::PointerType::getUnqual(DeclTy),
  3528. /*D=*/nullptr);
  3529. // Create the new alias itself, but don't set a name yet.
  3530. auto *GA = llvm::GlobalAlias::create(
  3531. DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  3532. if (Entry) {
  3533. if (GA->getAliasee() == Entry) {
  3534. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3535. return;
  3536. }
  3537. assert(Entry->isDeclaration());
  3538. // If there is a declaration in the module, then we had an extern followed
  3539. // by the alias, as in:
  3540. // extern int test6();
  3541. // ...
  3542. // int test6() __attribute__((alias("test7")));
  3543. //
  3544. // Remove it and replace uses of it with the alias.
  3545. GA->takeName(Entry);
  3546. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  3547. Entry->getType()));
  3548. Entry->eraseFromParent();
  3549. } else {
  3550. GA->setName(MangledName);
  3551. }
  3552. // Set attributes which are particular to an alias; this is a
  3553. // specialization of the attributes which may be set on a global
  3554. // variable/function.
  3555. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  3556. D->isWeakImported()) {
  3557. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  3558. }
  3559. if (const auto *VD = dyn_cast<VarDecl>(D))
  3560. if (VD->getTLSKind())
  3561. setTLSMode(GA, *VD);
  3562. SetCommonAttributes(GD, GA);
  3563. }
  3564. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  3565. const auto *D = cast<ValueDecl>(GD.getDecl());
  3566. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  3567. assert(IFA && "Not an ifunc?");
  3568. StringRef MangledName = getMangledName(GD);
  3569. if (IFA->getResolver() == MangledName) {
  3570. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3571. return;
  3572. }
  3573. // Report an error if some definition overrides ifunc.
  3574. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3575. if (Entry && !Entry->isDeclaration()) {
  3576. GlobalDecl OtherGD;
  3577. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  3578. DiagnosedConflictingDefinitions.insert(GD).second) {
  3579. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
  3580. << MangledName;
  3581. Diags.Report(OtherGD.getDecl()->getLocation(),
  3582. diag::note_previous_definition);
  3583. }
  3584. return;
  3585. }
  3586. Aliases.push_back(GD);
  3587. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3588. llvm::Constant *Resolver =
  3589. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  3590. /*ForVTable=*/false);
  3591. llvm::GlobalIFunc *GIF =
  3592. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  3593. "", Resolver, &getModule());
  3594. if (Entry) {
  3595. if (GIF->getResolver() == Entry) {
  3596. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3597. return;
  3598. }
  3599. assert(Entry->isDeclaration());
  3600. // If there is a declaration in the module, then we had an extern followed
  3601. // by the ifunc, as in:
  3602. // extern int test();
  3603. // ...
  3604. // int test() __attribute__((ifunc("resolver")));
  3605. //
  3606. // Remove it and replace uses of it with the ifunc.
  3607. GIF->takeName(Entry);
  3608. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  3609. Entry->getType()));
  3610. Entry->eraseFromParent();
  3611. } else
  3612. GIF->setName(MangledName);
  3613. SetCommonAttributes(GD, GIF);
  3614. }
  3615. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  3616. ArrayRef<llvm::Type*> Tys) {
  3617. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  3618. Tys);
  3619. }
  3620. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  3621. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  3622. const StringLiteral *Literal, bool TargetIsLSB,
  3623. bool &IsUTF16, unsigned &StringLength) {
  3624. StringRef String = Literal->getString();
  3625. unsigned NumBytes = String.size();
  3626. // Check for simple case.
  3627. if (!Literal->containsNonAsciiOrNull()) {
  3628. StringLength = NumBytes;
  3629. return *Map.insert(std::make_pair(String, nullptr)).first;
  3630. }
  3631. // Otherwise, convert the UTF8 literals into a string of shorts.
  3632. IsUTF16 = true;
  3633. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  3634. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3635. llvm::UTF16 *ToPtr = &ToBuf[0];
  3636. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3637. ToPtr + NumBytes, llvm::strictConversion);
  3638. // ConvertUTF8toUTF16 returns the length in ToPtr.
  3639. StringLength = ToPtr - &ToBuf[0];
  3640. // Add an explicit null.
  3641. *ToPtr = 0;
  3642. return *Map.insert(std::make_pair(
  3643. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  3644. (StringLength + 1) * 2),
  3645. nullptr)).first;
  3646. }
  3647. ConstantAddress
  3648. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  3649. unsigned StringLength = 0;
  3650. bool isUTF16 = false;
  3651. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  3652. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  3653. getDataLayout().isLittleEndian(), isUTF16,
  3654. StringLength);
  3655. if (auto *C = Entry.second)
  3656. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  3657. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  3658. llvm::Constant *Zeros[] = { Zero, Zero };
  3659. const ASTContext &Context = getContext();
  3660. const llvm::Triple &Triple = getTriple();
  3661. const auto CFRuntime = getLangOpts().CFRuntime;
  3662. const bool IsSwiftABI =
  3663. static_cast<unsigned>(CFRuntime) >=
  3664. static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
  3665. const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
  3666. // If we don't already have it, get __CFConstantStringClassReference.
  3667. if (!CFConstantStringClassRef) {
  3668. const char *CFConstantStringClassName = "__CFConstantStringClassReference";
  3669. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  3670. Ty = llvm::ArrayType::get(Ty, 0);
  3671. switch (CFRuntime) {
  3672. default: break;
  3673. case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
  3674. case LangOptions::CoreFoundationABI::Swift5_0:
  3675. CFConstantStringClassName =
  3676. Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
  3677. : "$s10Foundation19_NSCFConstantStringCN";
  3678. Ty = IntPtrTy;
  3679. break;
  3680. case LangOptions::CoreFoundationABI::Swift4_2:
  3681. CFConstantStringClassName =
  3682. Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
  3683. : "$S10Foundation19_NSCFConstantStringCN";
  3684. Ty = IntPtrTy;
  3685. break;
  3686. case LangOptions::CoreFoundationABI::Swift4_1:
  3687. CFConstantStringClassName =
  3688. Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
  3689. : "__T010Foundation19_NSCFConstantStringCN";
  3690. Ty = IntPtrTy;
  3691. break;
  3692. }
  3693. llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
  3694. if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
  3695. llvm::GlobalValue *GV = nullptr;
  3696. if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
  3697. IdentifierInfo &II = Context.Idents.get(GV->getName());
  3698. TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
  3699. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  3700. const VarDecl *VD = nullptr;
  3701. for (const auto &Result : DC->lookup(&II))
  3702. if ((VD = dyn_cast<VarDecl>(Result)))
  3703. break;
  3704. if (Triple.isOSBinFormatELF()) {
  3705. if (!VD)
  3706. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3707. } else {
  3708. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3709. if (!VD || !VD->hasAttr<DLLExportAttr>())
  3710. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  3711. else
  3712. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  3713. }
  3714. setDSOLocal(GV);
  3715. }
  3716. }
  3717. // Decay array -> ptr
  3718. CFConstantStringClassRef =
  3719. IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
  3720. : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
  3721. }
  3722. QualType CFTy = Context.getCFConstantStringType();
  3723. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  3724. ConstantInitBuilder Builder(*this);
  3725. auto Fields = Builder.beginStruct(STy);
  3726. // Class pointer.
  3727. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  3728. // Flags.
  3729. if (IsSwiftABI) {
  3730. Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
  3731. Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
  3732. } else {
  3733. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  3734. }
  3735. // String pointer.
  3736. llvm::Constant *C = nullptr;
  3737. if (isUTF16) {
  3738. auto Arr = llvm::makeArrayRef(
  3739. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  3740. Entry.first().size() / 2);
  3741. C = llvm::ConstantDataArray::get(VMContext, Arr);
  3742. } else {
  3743. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  3744. }
  3745. // Note: -fwritable-strings doesn't make the backing store strings of
  3746. // CFStrings writable. (See <rdar://problem/10657500>)
  3747. auto *GV =
  3748. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  3749. llvm::GlobalValue::PrivateLinkage, C, ".str");
  3750. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3751. // Don't enforce the target's minimum global alignment, since the only use
  3752. // of the string is via this class initializer.
  3753. CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
  3754. : Context.getTypeAlignInChars(Context.CharTy);
  3755. GV->setAlignment(Align.getQuantity());
  3756. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  3757. // Without it LLVM can merge the string with a non unnamed_addr one during
  3758. // LTO. Doing that changes the section it ends in, which surprises ld64.
  3759. if (Triple.isOSBinFormatMachO())
  3760. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  3761. : "__TEXT,__cstring,cstring_literals");
  3762. // Make sure the literal ends up in .rodata to allow for safe ICF and for
  3763. // the static linker to adjust permissions to read-only later on.
  3764. else if (Triple.isOSBinFormatELF())
  3765. GV->setSection(".rodata");
  3766. // String.
  3767. llvm::Constant *Str =
  3768. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  3769. if (isUTF16)
  3770. // Cast the UTF16 string to the correct type.
  3771. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  3772. Fields.add(Str);
  3773. // String length.
  3774. llvm::IntegerType *LengthTy =
  3775. llvm::IntegerType::get(getModule().getContext(),
  3776. Context.getTargetInfo().getLongWidth());
  3777. if (IsSwiftABI) {
  3778. if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
  3779. CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
  3780. LengthTy = Int32Ty;
  3781. else
  3782. LengthTy = IntPtrTy;
  3783. }
  3784. Fields.addInt(LengthTy, StringLength);
  3785. CharUnits Alignment = getPointerAlign();
  3786. // The struct.
  3787. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  3788. /*isConstant=*/false,
  3789. llvm::GlobalVariable::PrivateLinkage);
  3790. switch (Triple.getObjectFormat()) {
  3791. case llvm::Triple::UnknownObjectFormat:
  3792. llvm_unreachable("unknown file format");
  3793. case llvm::Triple::XCOFF:
  3794. llvm_unreachable("XCOFF is not yet implemented");
  3795. case llvm::Triple::COFF:
  3796. case llvm::Triple::ELF:
  3797. case llvm::Triple::Wasm:
  3798. GV->setSection("cfstring");
  3799. break;
  3800. case llvm::Triple::MachO:
  3801. GV->setSection("__DATA,__cfstring");
  3802. break;
  3803. }
  3804. Entry.second = GV;
  3805. return ConstantAddress(GV, Alignment);
  3806. }
  3807. bool CodeGenModule::getExpressionLocationsEnabled() const {
  3808. return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
  3809. }
  3810. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  3811. if (ObjCFastEnumerationStateType.isNull()) {
  3812. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  3813. D->startDefinition();
  3814. QualType FieldTypes[] = {
  3815. Context.UnsignedLongTy,
  3816. Context.getPointerType(Context.getObjCIdType()),
  3817. Context.getPointerType(Context.UnsignedLongTy),
  3818. Context.getConstantArrayType(Context.UnsignedLongTy,
  3819. llvm::APInt(32, 5), ArrayType::Normal, 0)
  3820. };
  3821. for (size_t i = 0; i < 4; ++i) {
  3822. FieldDecl *Field = FieldDecl::Create(Context,
  3823. D,
  3824. SourceLocation(),
  3825. SourceLocation(), nullptr,
  3826. FieldTypes[i], /*TInfo=*/nullptr,
  3827. /*BitWidth=*/nullptr,
  3828. /*Mutable=*/false,
  3829. ICIS_NoInit);
  3830. Field->setAccess(AS_public);
  3831. D->addDecl(Field);
  3832. }
  3833. D->completeDefinition();
  3834. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  3835. }
  3836. return ObjCFastEnumerationStateType;
  3837. }
  3838. llvm::Constant *
  3839. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  3840. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  3841. // Don't emit it as the address of the string, emit the string data itself
  3842. // as an inline array.
  3843. if (E->getCharByteWidth() == 1) {
  3844. SmallString<64> Str(E->getString());
  3845. // Resize the string to the right size, which is indicated by its type.
  3846. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  3847. Str.resize(CAT->getSize().getZExtValue());
  3848. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  3849. }
  3850. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  3851. llvm::Type *ElemTy = AType->getElementType();
  3852. unsigned NumElements = AType->getNumElements();
  3853. // Wide strings have either 2-byte or 4-byte elements.
  3854. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  3855. SmallVector<uint16_t, 32> Elements;
  3856. Elements.reserve(NumElements);
  3857. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3858. Elements.push_back(E->getCodeUnit(i));
  3859. Elements.resize(NumElements);
  3860. return llvm::ConstantDataArray::get(VMContext, Elements);
  3861. }
  3862. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  3863. SmallVector<uint32_t, 32> Elements;
  3864. Elements.reserve(NumElements);
  3865. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3866. Elements.push_back(E->getCodeUnit(i));
  3867. Elements.resize(NumElements);
  3868. return llvm::ConstantDataArray::get(VMContext, Elements);
  3869. }
  3870. static llvm::GlobalVariable *
  3871. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  3872. CodeGenModule &CGM, StringRef GlobalName,
  3873. CharUnits Alignment) {
  3874. unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
  3875. CGM.getStringLiteralAddressSpace());
  3876. llvm::Module &M = CGM.getModule();
  3877. // Create a global variable for this string
  3878. auto *GV = new llvm::GlobalVariable(
  3879. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  3880. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  3881. GV->setAlignment(Alignment.getQuantity());
  3882. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3883. if (GV->isWeakForLinker()) {
  3884. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  3885. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  3886. }
  3887. CGM.setDSOLocal(GV);
  3888. return GV;
  3889. }
  3890. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  3891. /// constant array for the given string literal.
  3892. ConstantAddress
  3893. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  3894. StringRef Name) {
  3895. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  3896. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  3897. llvm::GlobalVariable **Entry = nullptr;
  3898. if (!LangOpts.WritableStrings) {
  3899. Entry = &ConstantStringMap[C];
  3900. if (auto GV = *Entry) {
  3901. if (Alignment.getQuantity() > GV->getAlignment())
  3902. GV->setAlignment(Alignment.getQuantity());
  3903. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  3904. Alignment);
  3905. }
  3906. }
  3907. SmallString<256> MangledNameBuffer;
  3908. StringRef GlobalVariableName;
  3909. llvm::GlobalValue::LinkageTypes LT;
  3910. // Mangle the string literal if that's how the ABI merges duplicate strings.
  3911. // Don't do it if they are writable, since we don't want writes in one TU to
  3912. // affect strings in another.
  3913. if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
  3914. !LangOpts.WritableStrings) {
  3915. llvm::raw_svector_ostream Out(MangledNameBuffer);
  3916. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  3917. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  3918. GlobalVariableName = MangledNameBuffer;
  3919. } else {
  3920. LT = llvm::GlobalValue::PrivateLinkage;
  3921. GlobalVariableName = Name;
  3922. }
  3923. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  3924. if (Entry)
  3925. *Entry = GV;
  3926. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  3927. QualType());
  3928. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  3929. Alignment);
  3930. }
  3931. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  3932. /// array for the given ObjCEncodeExpr node.
  3933. ConstantAddress
  3934. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  3935. std::string Str;
  3936. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  3937. return GetAddrOfConstantCString(Str);
  3938. }
  3939. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  3940. /// the literal and a terminating '\0' character.
  3941. /// The result has pointer to array type.
  3942. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  3943. const std::string &Str, const char *GlobalName) {
  3944. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  3945. CharUnits Alignment =
  3946. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  3947. llvm::Constant *C =
  3948. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  3949. // Don't share any string literals if strings aren't constant.
  3950. llvm::GlobalVariable **Entry = nullptr;
  3951. if (!LangOpts.WritableStrings) {
  3952. Entry = &ConstantStringMap[C];
  3953. if (auto GV = *Entry) {
  3954. if (Alignment.getQuantity() > GV->getAlignment())
  3955. GV->setAlignment(Alignment.getQuantity());
  3956. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  3957. Alignment);
  3958. }
  3959. }
  3960. // Get the default prefix if a name wasn't specified.
  3961. if (!GlobalName)
  3962. GlobalName = ".str";
  3963. // Create a global variable for this.
  3964. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  3965. GlobalName, Alignment);
  3966. if (Entry)
  3967. *Entry = GV;
  3968. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  3969. Alignment);
  3970. }
  3971. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  3972. const MaterializeTemporaryExpr *E, const Expr *Init) {
  3973. assert((E->getStorageDuration() == SD_Static ||
  3974. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  3975. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  3976. // If we're not materializing a subobject of the temporary, keep the
  3977. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  3978. QualType MaterializedType = Init->getType();
  3979. if (Init == E->GetTemporaryExpr())
  3980. MaterializedType = E->getType();
  3981. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  3982. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  3983. return ConstantAddress(Slot, Align);
  3984. // FIXME: If an externally-visible declaration extends multiple temporaries,
  3985. // we need to give each temporary the same name in every translation unit (and
  3986. // we also need to make the temporaries externally-visible).
  3987. SmallString<256> Name;
  3988. llvm::raw_svector_ostream Out(Name);
  3989. getCXXABI().getMangleContext().mangleReferenceTemporary(
  3990. VD, E->getManglingNumber(), Out);
  3991. APValue *Value = nullptr;
  3992. if (E->getStorageDuration() == SD_Static) {
  3993. // We might have a cached constant initializer for this temporary. Note
  3994. // that this might have a different value from the value computed by
  3995. // evaluating the initializer if the surrounding constant expression
  3996. // modifies the temporary.
  3997. Value = getContext().getMaterializedTemporaryValue(E, false);
  3998. if (Value && Value->isUninit())
  3999. Value = nullptr;
  4000. }
  4001. // Try evaluating it now, it might have a constant initializer.
  4002. Expr::EvalResult EvalResult;
  4003. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  4004. !EvalResult.hasSideEffects())
  4005. Value = &EvalResult.Val;
  4006. LangAS AddrSpace =
  4007. VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
  4008. Optional<ConstantEmitter> emitter;
  4009. llvm::Constant *InitialValue = nullptr;
  4010. bool Constant = false;
  4011. llvm::Type *Type;
  4012. if (Value) {
  4013. // The temporary has a constant initializer, use it.
  4014. emitter.emplace(*this);
  4015. InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
  4016. MaterializedType);
  4017. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  4018. Type = InitialValue->getType();
  4019. } else {
  4020. // No initializer, the initialization will be provided when we
  4021. // initialize the declaration which performed lifetime extension.
  4022. Type = getTypes().ConvertTypeForMem(MaterializedType);
  4023. }
  4024. // Create a global variable for this lifetime-extended temporary.
  4025. llvm::GlobalValue::LinkageTypes Linkage =
  4026. getLLVMLinkageVarDefinition(VD, Constant);
  4027. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  4028. const VarDecl *InitVD;
  4029. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  4030. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  4031. // Temporaries defined inside a class get linkonce_odr linkage because the
  4032. // class can be defined in multiple translation units.
  4033. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  4034. } else {
  4035. // There is no need for this temporary to have external linkage if the
  4036. // VarDecl has external linkage.
  4037. Linkage = llvm::GlobalVariable::InternalLinkage;
  4038. }
  4039. }
  4040. auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
  4041. auto *GV = new llvm::GlobalVariable(
  4042. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  4043. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  4044. if (emitter) emitter->finalize(GV);
  4045. setGVProperties(GV, VD);
  4046. GV->setAlignment(Align.getQuantity());
  4047. if (supportsCOMDAT() && GV->isWeakForLinker())
  4048. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  4049. if (VD->getTLSKind())
  4050. setTLSMode(GV, *VD);
  4051. llvm::Constant *CV = GV;
  4052. if (AddrSpace != LangAS::Default)
  4053. CV = getTargetCodeGenInfo().performAddrSpaceCast(
  4054. *this, GV, AddrSpace, LangAS::Default,
  4055. Type->getPointerTo(
  4056. getContext().getTargetAddressSpace(LangAS::Default)));
  4057. MaterializedGlobalTemporaryMap[E] = CV;
  4058. return ConstantAddress(CV, Align);
  4059. }
  4060. /// EmitObjCPropertyImplementations - Emit information for synthesized
  4061. /// properties for an implementation.
  4062. void CodeGenModule::EmitObjCPropertyImplementations(const
  4063. ObjCImplementationDecl *D) {
  4064. for (const auto *PID : D->property_impls()) {
  4065. // Dynamic is just for type-checking.
  4066. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  4067. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  4068. // Determine which methods need to be implemented, some may have
  4069. // been overridden. Note that ::isPropertyAccessor is not the method
  4070. // we want, that just indicates if the decl came from a
  4071. // property. What we want to know is if the method is defined in
  4072. // this implementation.
  4073. if (!D->getInstanceMethod(PD->getGetterName()))
  4074. CodeGenFunction(*this).GenerateObjCGetter(
  4075. const_cast<ObjCImplementationDecl *>(D), PID);
  4076. if (!PD->isReadOnly() &&
  4077. !D->getInstanceMethod(PD->getSetterName()))
  4078. CodeGenFunction(*this).GenerateObjCSetter(
  4079. const_cast<ObjCImplementationDecl *>(D), PID);
  4080. }
  4081. }
  4082. }
  4083. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  4084. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  4085. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  4086. ivar; ivar = ivar->getNextIvar())
  4087. if (ivar->getType().isDestructedType())
  4088. return true;
  4089. return false;
  4090. }
  4091. static bool AllTrivialInitializers(CodeGenModule &CGM,
  4092. ObjCImplementationDecl *D) {
  4093. CodeGenFunction CGF(CGM);
  4094. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  4095. E = D->init_end(); B != E; ++B) {
  4096. CXXCtorInitializer *CtorInitExp = *B;
  4097. Expr *Init = CtorInitExp->getInit();
  4098. if (!CGF.isTrivialInitializer(Init))
  4099. return false;
  4100. }
  4101. return true;
  4102. }
  4103. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  4104. /// for an implementation.
  4105. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  4106. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  4107. if (needsDestructMethod(D)) {
  4108. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  4109. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  4110. ObjCMethodDecl *DTORMethod =
  4111. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  4112. cxxSelector, getContext().VoidTy, nullptr, D,
  4113. /*isInstance=*/true, /*isVariadic=*/false,
  4114. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  4115. /*isDefined=*/false, ObjCMethodDecl::Required);
  4116. D->addInstanceMethod(DTORMethod);
  4117. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  4118. D->setHasDestructors(true);
  4119. }
  4120. // If the implementation doesn't have any ivar initializers, we don't need
  4121. // a .cxx_construct.
  4122. if (D->getNumIvarInitializers() == 0 ||
  4123. AllTrivialInitializers(*this, D))
  4124. return;
  4125. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  4126. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  4127. // The constructor returns 'self'.
  4128. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  4129. D->getLocation(),
  4130. D->getLocation(),
  4131. cxxSelector,
  4132. getContext().getObjCIdType(),
  4133. nullptr, D, /*isInstance=*/true,
  4134. /*isVariadic=*/false,
  4135. /*isPropertyAccessor=*/true,
  4136. /*isImplicitlyDeclared=*/true,
  4137. /*isDefined=*/false,
  4138. ObjCMethodDecl::Required);
  4139. D->addInstanceMethod(CTORMethod);
  4140. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  4141. D->setHasNonZeroConstructors(true);
  4142. }
  4143. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  4144. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  4145. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  4146. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  4147. ErrorUnsupported(LSD, "linkage spec");
  4148. return;
  4149. }
  4150. EmitDeclContext(LSD);
  4151. }
  4152. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  4153. for (auto *I : DC->decls()) {
  4154. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  4155. // are themselves considered "top-level", so EmitTopLevelDecl on an
  4156. // ObjCImplDecl does not recursively visit them. We need to do that in
  4157. // case they're nested inside another construct (LinkageSpecDecl /
  4158. // ExportDecl) that does stop them from being considered "top-level".
  4159. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  4160. for (auto *M : OID->methods())
  4161. EmitTopLevelDecl(M);
  4162. }
  4163. EmitTopLevelDecl(I);
  4164. }
  4165. }
  4166. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  4167. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  4168. // Ignore dependent declarations.
  4169. if (D->isTemplated())
  4170. return;
  4171. switch (D->getKind()) {
  4172. case Decl::CXXConversion:
  4173. case Decl::CXXMethod:
  4174. case Decl::Function:
  4175. EmitGlobal(cast<FunctionDecl>(D));
  4176. // Always provide some coverage mapping
  4177. // even for the functions that aren't emitted.
  4178. AddDeferredUnusedCoverageMapping(D);
  4179. break;
  4180. case Decl::CXXDeductionGuide:
  4181. // Function-like, but does not result in code emission.
  4182. break;
  4183. case Decl::Var:
  4184. case Decl::Decomposition:
  4185. case Decl::VarTemplateSpecialization:
  4186. EmitGlobal(cast<VarDecl>(D));
  4187. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  4188. for (auto *B : DD->bindings())
  4189. if (auto *HD = B->getHoldingVar())
  4190. EmitGlobal(HD);
  4191. break;
  4192. // Indirect fields from global anonymous structs and unions can be
  4193. // ignored; only the actual variable requires IR gen support.
  4194. case Decl::IndirectField:
  4195. break;
  4196. // C++ Decls
  4197. case Decl::Namespace:
  4198. EmitDeclContext(cast<NamespaceDecl>(D));
  4199. break;
  4200. case Decl::ClassTemplateSpecialization: {
  4201. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  4202. if (DebugInfo &&
  4203. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  4204. Spec->hasDefinition())
  4205. DebugInfo->completeTemplateDefinition(*Spec);
  4206. } LLVM_FALLTHROUGH;
  4207. case Decl::CXXRecord:
  4208. if (DebugInfo) {
  4209. if (auto *ES = D->getASTContext().getExternalSource())
  4210. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  4211. DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
  4212. }
  4213. // Emit any static data members, they may be definitions.
  4214. for (auto *I : cast<CXXRecordDecl>(D)->decls())
  4215. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  4216. EmitTopLevelDecl(I);
  4217. break;
  4218. // No code generation needed.
  4219. case Decl::UsingShadow:
  4220. case Decl::ClassTemplate:
  4221. case Decl::VarTemplate:
  4222. case Decl::VarTemplatePartialSpecialization:
  4223. case Decl::FunctionTemplate:
  4224. case Decl::TypeAliasTemplate:
  4225. case Decl::Block:
  4226. case Decl::Empty:
  4227. case Decl::Binding:
  4228. break;
  4229. case Decl::Using: // using X; [C++]
  4230. if (CGDebugInfo *DI = getModuleDebugInfo())
  4231. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  4232. return;
  4233. case Decl::NamespaceAlias:
  4234. if (CGDebugInfo *DI = getModuleDebugInfo())
  4235. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  4236. return;
  4237. case Decl::UsingDirective: // using namespace X; [C++]
  4238. if (CGDebugInfo *DI = getModuleDebugInfo())
  4239. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  4240. return;
  4241. case Decl::CXXConstructor:
  4242. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  4243. break;
  4244. case Decl::CXXDestructor:
  4245. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  4246. break;
  4247. case Decl::StaticAssert:
  4248. // Nothing to do.
  4249. break;
  4250. // Objective-C Decls
  4251. // Forward declarations, no (immediate) code generation.
  4252. case Decl::ObjCInterface:
  4253. case Decl::ObjCCategory:
  4254. break;
  4255. case Decl::ObjCProtocol: {
  4256. auto *Proto = cast<ObjCProtocolDecl>(D);
  4257. if (Proto->isThisDeclarationADefinition())
  4258. ObjCRuntime->GenerateProtocol(Proto);
  4259. break;
  4260. }
  4261. case Decl::ObjCCategoryImpl:
  4262. // Categories have properties but don't support synthesize so we
  4263. // can ignore them here.
  4264. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  4265. break;
  4266. case Decl::ObjCImplementation: {
  4267. auto *OMD = cast<ObjCImplementationDecl>(D);
  4268. EmitObjCPropertyImplementations(OMD);
  4269. EmitObjCIvarInitializations(OMD);
  4270. ObjCRuntime->GenerateClass(OMD);
  4271. // Emit global variable debug information.
  4272. if (CGDebugInfo *DI = getModuleDebugInfo())
  4273. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  4274. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  4275. OMD->getClassInterface()), OMD->getLocation());
  4276. break;
  4277. }
  4278. case Decl::ObjCMethod: {
  4279. auto *OMD = cast<ObjCMethodDecl>(D);
  4280. // If this is not a prototype, emit the body.
  4281. if (OMD->getBody())
  4282. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  4283. break;
  4284. }
  4285. case Decl::ObjCCompatibleAlias:
  4286. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  4287. break;
  4288. case Decl::PragmaComment: {
  4289. const auto *PCD = cast<PragmaCommentDecl>(D);
  4290. switch (PCD->getCommentKind()) {
  4291. case PCK_Unknown:
  4292. llvm_unreachable("unexpected pragma comment kind");
  4293. case PCK_Linker:
  4294. AppendLinkerOptions(PCD->getArg());
  4295. break;
  4296. case PCK_Lib:
  4297. if (getTarget().getTriple().isOSBinFormatELF() &&
  4298. !getTarget().getTriple().isPS4())
  4299. AddELFLibDirective(PCD->getArg());
  4300. else
  4301. AddDependentLib(PCD->getArg());
  4302. break;
  4303. case PCK_Compiler:
  4304. case PCK_ExeStr:
  4305. case PCK_User:
  4306. break; // We ignore all of these.
  4307. }
  4308. break;
  4309. }
  4310. case Decl::PragmaDetectMismatch: {
  4311. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  4312. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  4313. break;
  4314. }
  4315. case Decl::LinkageSpec:
  4316. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  4317. break;
  4318. case Decl::FileScopeAsm: {
  4319. // File-scope asm is ignored during device-side CUDA compilation.
  4320. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  4321. break;
  4322. // File-scope asm is ignored during device-side OpenMP compilation.
  4323. if (LangOpts.OpenMPIsDevice)
  4324. break;
  4325. auto *AD = cast<FileScopeAsmDecl>(D);
  4326. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  4327. break;
  4328. }
  4329. case Decl::Import: {
  4330. auto *Import = cast<ImportDecl>(D);
  4331. // If we've already imported this module, we're done.
  4332. if (!ImportedModules.insert(Import->getImportedModule()))
  4333. break;
  4334. // Emit debug information for direct imports.
  4335. if (!Import->getImportedOwningModule()) {
  4336. if (CGDebugInfo *DI = getModuleDebugInfo())
  4337. DI->EmitImportDecl(*Import);
  4338. }
  4339. // Find all of the submodules and emit the module initializers.
  4340. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  4341. SmallVector<clang::Module *, 16> Stack;
  4342. Visited.insert(Import->getImportedModule());
  4343. Stack.push_back(Import->getImportedModule());
  4344. while (!Stack.empty()) {
  4345. clang::Module *Mod = Stack.pop_back_val();
  4346. if (!EmittedModuleInitializers.insert(Mod).second)
  4347. continue;
  4348. for (auto *D : Context.getModuleInitializers(Mod))
  4349. EmitTopLevelDecl(D);
  4350. // Visit the submodules of this module.
  4351. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  4352. SubEnd = Mod->submodule_end();
  4353. Sub != SubEnd; ++Sub) {
  4354. // Skip explicit children; they need to be explicitly imported to emit
  4355. // the initializers.
  4356. if ((*Sub)->IsExplicit)
  4357. continue;
  4358. if (Visited.insert(*Sub).second)
  4359. Stack.push_back(*Sub);
  4360. }
  4361. }
  4362. break;
  4363. }
  4364. case Decl::Export:
  4365. EmitDeclContext(cast<ExportDecl>(D));
  4366. break;
  4367. case Decl::OMPThreadPrivate:
  4368. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  4369. break;
  4370. case Decl::OMPAllocate:
  4371. break;
  4372. case Decl::OMPDeclareReduction:
  4373. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  4374. break;
  4375. case Decl::OMPDeclareMapper:
  4376. EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
  4377. break;
  4378. case Decl::OMPRequires:
  4379. EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
  4380. break;
  4381. default:
  4382. // Make sure we handled everything we should, every other kind is a
  4383. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  4384. // function. Need to recode Decl::Kind to do that easily.
  4385. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  4386. break;
  4387. }
  4388. }
  4389. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  4390. // Do we need to generate coverage mapping?
  4391. if (!CodeGenOpts.CoverageMapping)
  4392. return;
  4393. switch (D->getKind()) {
  4394. case Decl::CXXConversion:
  4395. case Decl::CXXMethod:
  4396. case Decl::Function:
  4397. case Decl::ObjCMethod:
  4398. case Decl::CXXConstructor:
  4399. case Decl::CXXDestructor: {
  4400. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  4401. return;
  4402. SourceManager &SM = getContext().getSourceManager();
  4403. if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
  4404. return;
  4405. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  4406. if (I == DeferredEmptyCoverageMappingDecls.end())
  4407. DeferredEmptyCoverageMappingDecls[D] = true;
  4408. break;
  4409. }
  4410. default:
  4411. break;
  4412. };
  4413. }
  4414. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  4415. // Do we need to generate coverage mapping?
  4416. if (!CodeGenOpts.CoverageMapping)
  4417. return;
  4418. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  4419. if (Fn->isTemplateInstantiation())
  4420. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  4421. }
  4422. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  4423. if (I == DeferredEmptyCoverageMappingDecls.end())
  4424. DeferredEmptyCoverageMappingDecls[D] = false;
  4425. else
  4426. I->second = false;
  4427. }
  4428. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  4429. // We call takeVector() here to avoid use-after-free.
  4430. // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
  4431. // we deserialize function bodies to emit coverage info for them, and that
  4432. // deserializes more declarations. How should we handle that case?
  4433. for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
  4434. if (!Entry.second)
  4435. continue;
  4436. const Decl *D = Entry.first;
  4437. switch (D->getKind()) {
  4438. case Decl::CXXConversion:
  4439. case Decl::CXXMethod:
  4440. case Decl::Function:
  4441. case Decl::ObjCMethod: {
  4442. CodeGenPGO PGO(*this);
  4443. GlobalDecl GD(cast<FunctionDecl>(D));
  4444. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4445. getFunctionLinkage(GD));
  4446. break;
  4447. }
  4448. case Decl::CXXConstructor: {
  4449. CodeGenPGO PGO(*this);
  4450. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  4451. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4452. getFunctionLinkage(GD));
  4453. break;
  4454. }
  4455. case Decl::CXXDestructor: {
  4456. CodeGenPGO PGO(*this);
  4457. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  4458. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4459. getFunctionLinkage(GD));
  4460. break;
  4461. }
  4462. default:
  4463. break;
  4464. };
  4465. }
  4466. }
  4467. /// Turns the given pointer into a constant.
  4468. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  4469. const void *Ptr) {
  4470. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  4471. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  4472. return llvm::ConstantInt::get(i64, PtrInt);
  4473. }
  4474. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  4475. llvm::NamedMDNode *&GlobalMetadata,
  4476. GlobalDecl D,
  4477. llvm::GlobalValue *Addr) {
  4478. if (!GlobalMetadata)
  4479. GlobalMetadata =
  4480. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  4481. // TODO: should we report variant information for ctors/dtors?
  4482. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  4483. llvm::ConstantAsMetadata::get(GetPointerConstant(
  4484. CGM.getLLVMContext(), D.getDecl()))};
  4485. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  4486. }
  4487. /// For each function which is declared within an extern "C" region and marked
  4488. /// as 'used', but has internal linkage, create an alias from the unmangled
  4489. /// name to the mangled name if possible. People expect to be able to refer
  4490. /// to such functions with an unmangled name from inline assembly within the
  4491. /// same translation unit.
  4492. void CodeGenModule::EmitStaticExternCAliases() {
  4493. if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
  4494. return;
  4495. for (auto &I : StaticExternCValues) {
  4496. IdentifierInfo *Name = I.first;
  4497. llvm::GlobalValue *Val = I.second;
  4498. if (Val && !getModule().getNamedValue(Name->getName()))
  4499. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  4500. }
  4501. }
  4502. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  4503. GlobalDecl &Result) const {
  4504. auto Res = Manglings.find(MangledName);
  4505. if (Res == Manglings.end())
  4506. return false;
  4507. Result = Res->getValue();
  4508. return true;
  4509. }
  4510. /// Emits metadata nodes associating all the global values in the
  4511. /// current module with the Decls they came from. This is useful for
  4512. /// projects using IR gen as a subroutine.
  4513. ///
  4514. /// Since there's currently no way to associate an MDNode directly
  4515. /// with an llvm::GlobalValue, we create a global named metadata
  4516. /// with the name 'clang.global.decl.ptrs'.
  4517. void CodeGenModule::EmitDeclMetadata() {
  4518. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4519. for (auto &I : MangledDeclNames) {
  4520. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  4521. // Some mangled names don't necessarily have an associated GlobalValue
  4522. // in this module, e.g. if we mangled it for DebugInfo.
  4523. if (Addr)
  4524. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  4525. }
  4526. }
  4527. /// Emits metadata nodes for all the local variables in the current
  4528. /// function.
  4529. void CodeGenFunction::EmitDeclMetadata() {
  4530. if (LocalDeclMap.empty()) return;
  4531. llvm::LLVMContext &Context = getLLVMContext();
  4532. // Find the unique metadata ID for this name.
  4533. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  4534. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4535. for (auto &I : LocalDeclMap) {
  4536. const Decl *D = I.first;
  4537. llvm::Value *Addr = I.second.getPointer();
  4538. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  4539. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  4540. Alloca->setMetadata(
  4541. DeclPtrKind, llvm::MDNode::get(
  4542. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  4543. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  4544. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  4545. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  4546. }
  4547. }
  4548. }
  4549. void CodeGenModule::EmitVersionIdentMetadata() {
  4550. llvm::NamedMDNode *IdentMetadata =
  4551. TheModule.getOrInsertNamedMetadata("llvm.ident");
  4552. std::string Version = getClangFullVersion();
  4553. llvm::LLVMContext &Ctx = TheModule.getContext();
  4554. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  4555. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  4556. }
  4557. void CodeGenModule::EmitCommandLineMetadata() {
  4558. llvm::NamedMDNode *CommandLineMetadata =
  4559. TheModule.getOrInsertNamedMetadata("llvm.commandline");
  4560. std::string CommandLine = getCodeGenOpts().RecordCommandLine;
  4561. llvm::LLVMContext &Ctx = TheModule.getContext();
  4562. llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
  4563. CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
  4564. }
  4565. void CodeGenModule::EmitTargetMetadata() {
  4566. // Warning, new MangledDeclNames may be appended within this loop.
  4567. // We rely on MapVector insertions adding new elements to the end
  4568. // of the container.
  4569. // FIXME: Move this loop into the one target that needs it, and only
  4570. // loop over those declarations for which we couldn't emit the target
  4571. // metadata when we emitted the declaration.
  4572. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  4573. auto Val = *(MangledDeclNames.begin() + I);
  4574. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  4575. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  4576. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  4577. }
  4578. }
  4579. void CodeGenModule::EmitCoverageFile() {
  4580. if (getCodeGenOpts().CoverageDataFile.empty() &&
  4581. getCodeGenOpts().CoverageNotesFile.empty())
  4582. return;
  4583. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  4584. if (!CUNode)
  4585. return;
  4586. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  4587. llvm::LLVMContext &Ctx = TheModule.getContext();
  4588. auto *CoverageDataFile =
  4589. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  4590. auto *CoverageNotesFile =
  4591. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  4592. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  4593. llvm::MDNode *CU = CUNode->getOperand(i);
  4594. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  4595. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  4596. }
  4597. }
  4598. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  4599. // Sema has checked that all uuid strings are of the form
  4600. // "12345678-1234-1234-1234-1234567890ab".
  4601. assert(Uuid.size() == 36);
  4602. for (unsigned i = 0; i < 36; ++i) {
  4603. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  4604. else assert(isHexDigit(Uuid[i]));
  4605. }
  4606. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  4607. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  4608. llvm::Constant *Field3[8];
  4609. for (unsigned Idx = 0; Idx < 8; ++Idx)
  4610. Field3[Idx] = llvm::ConstantInt::get(
  4611. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  4612. llvm::Constant *Fields[4] = {
  4613. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  4614. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  4615. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  4616. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  4617. };
  4618. return llvm::ConstantStruct::getAnon(Fields);
  4619. }
  4620. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  4621. bool ForEH) {
  4622. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  4623. // FIXME: should we even be calling this method if RTTI is disabled
  4624. // and it's not for EH?
  4625. if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
  4626. return llvm::Constant::getNullValue(Int8PtrTy);
  4627. if (ForEH && Ty->isObjCObjectPointerType() &&
  4628. LangOpts.ObjCRuntime.isGNUFamily())
  4629. return ObjCRuntime->GetEHType(Ty);
  4630. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  4631. }
  4632. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  4633. // Do not emit threadprivates in simd-only mode.
  4634. if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
  4635. return;
  4636. for (auto RefExpr : D->varlists()) {
  4637. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  4638. bool PerformInit =
  4639. VD->getAnyInitializer() &&
  4640. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  4641. /*ForRef=*/false);
  4642. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  4643. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  4644. VD, Addr, RefExpr->getBeginLoc(), PerformInit))
  4645. CXXGlobalInits.push_back(InitFunction);
  4646. }
  4647. }
  4648. llvm::Metadata *
  4649. CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
  4650. StringRef Suffix) {
  4651. llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
  4652. if (InternalId)
  4653. return InternalId;
  4654. if (isExternallyVisible(T->getLinkage())) {
  4655. std::string OutName;
  4656. llvm::raw_string_ostream Out(OutName);
  4657. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  4658. Out << Suffix;
  4659. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  4660. } else {
  4661. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  4662. llvm::ArrayRef<llvm::Metadata *>());
  4663. }
  4664. return InternalId;
  4665. }
  4666. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  4667. return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
  4668. }
  4669. llvm::Metadata *
  4670. CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
  4671. return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
  4672. }
  4673. // Generalize pointer types to a void pointer with the qualifiers of the
  4674. // originally pointed-to type, e.g. 'const char *' and 'char * const *'
  4675. // generalize to 'const void *' while 'char *' and 'const char **' generalize to
  4676. // 'void *'.
  4677. static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
  4678. if (!Ty->isPointerType())
  4679. return Ty;
  4680. return Ctx.getPointerType(
  4681. QualType(Ctx.VoidTy).withCVRQualifiers(
  4682. Ty->getPointeeType().getCVRQualifiers()));
  4683. }
  4684. // Apply type generalization to a FunctionType's return and argument types
  4685. static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
  4686. if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
  4687. SmallVector<QualType, 8> GeneralizedParams;
  4688. for (auto &Param : FnType->param_types())
  4689. GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
  4690. return Ctx.getFunctionType(
  4691. GeneralizeType(Ctx, FnType->getReturnType()),
  4692. GeneralizedParams, FnType->getExtProtoInfo());
  4693. }
  4694. if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
  4695. return Ctx.getFunctionNoProtoType(
  4696. GeneralizeType(Ctx, FnType->getReturnType()));
  4697. llvm_unreachable("Encountered unknown FunctionType");
  4698. }
  4699. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
  4700. return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
  4701. GeneralizedMetadataIdMap, ".generalized");
  4702. }
  4703. /// Returns whether this module needs the "all-vtables" type identifier.
  4704. bool CodeGenModule::NeedAllVtablesTypeId() const {
  4705. // Returns true if at least one of vtable-based CFI checkers is enabled and
  4706. // is not in the trapping mode.
  4707. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  4708. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  4709. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  4710. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  4711. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  4712. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  4713. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  4714. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  4715. }
  4716. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  4717. CharUnits Offset,
  4718. const CXXRecordDecl *RD) {
  4719. llvm::Metadata *MD =
  4720. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  4721. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4722. if (CodeGenOpts.SanitizeCfiCrossDso)
  4723. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  4724. VTable->addTypeMetadata(Offset.getQuantity(),
  4725. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  4726. if (NeedAllVtablesTypeId()) {
  4727. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  4728. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4729. }
  4730. }
  4731. TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
  4732. assert(TD != nullptr);
  4733. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  4734. ParsedAttr.Features.erase(
  4735. llvm::remove_if(ParsedAttr.Features,
  4736. [&](const std::string &Feat) {
  4737. return !Target.isValidFeatureName(
  4738. StringRef{Feat}.substr(1));
  4739. }),
  4740. ParsedAttr.Features.end());
  4741. return ParsedAttr;
  4742. }
  4743. // Fills in the supplied string map with the set of target features for the
  4744. // passed in function.
  4745. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  4746. GlobalDecl GD) {
  4747. StringRef TargetCPU = Target.getTargetOpts().CPU;
  4748. const FunctionDecl *FD = GD.getDecl()->getAsFunction();
  4749. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  4750. TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
  4751. // Make a copy of the features as passed on the command line into the
  4752. // beginning of the additional features from the function to override.
  4753. ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
  4754. Target.getTargetOpts().FeaturesAsWritten.begin(),
  4755. Target.getTargetOpts().FeaturesAsWritten.end());
  4756. if (ParsedAttr.Architecture != "" &&
  4757. Target.isValidCPUName(ParsedAttr.Architecture))
  4758. TargetCPU = ParsedAttr.Architecture;
  4759. // Now populate the feature map, first with the TargetCPU which is either
  4760. // the default or a new one from the target attribute string. Then we'll use
  4761. // the passed in features (FeaturesAsWritten) along with the new ones from
  4762. // the attribute.
  4763. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4764. ParsedAttr.Features);
  4765. } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
  4766. llvm::SmallVector<StringRef, 32> FeaturesTmp;
  4767. Target.getCPUSpecificCPUDispatchFeatures(
  4768. SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
  4769. std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
  4770. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
  4771. } else {
  4772. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4773. Target.getTargetOpts().Features);
  4774. }
  4775. }
  4776. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  4777. if (!SanStats)
  4778. SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
  4779. return *SanStats;
  4780. }
  4781. llvm::Value *
  4782. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  4783. CodeGenFunction &CGF) {
  4784. llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
  4785. auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
  4786. auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  4787. return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
  4788. "__translate_sampler_initializer"),
  4789. {C});
  4790. }