CodeGenModule.cpp 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This coordinates the per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.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 "CodeGenFunction.h"
  22. #include "CodeGenPGO.h"
  23. #include "CodeGenTBAA.h"
  24. #include "CoverageMappingGen.h"
  25. #include "TargetInfo.h"
  26. #include "clang/AST/ASTContext.h"
  27. #include "clang/AST/CharUnits.h"
  28. #include "clang/AST/DeclCXX.h"
  29. #include "clang/AST/DeclObjC.h"
  30. #include "clang/AST/DeclTemplate.h"
  31. #include "clang/AST/Mangle.h"
  32. #include "clang/AST/RecordLayout.h"
  33. #include "clang/AST/RecursiveASTVisitor.h"
  34. #include "clang/Basic/Builtins.h"
  35. #include "clang/Basic/CharInfo.h"
  36. #include "clang/Basic/Diagnostic.h"
  37. #include "clang/Basic/Module.h"
  38. #include "clang/Basic/SourceManager.h"
  39. #include "clang/Basic/TargetInfo.h"
  40. #include "clang/Basic/Version.h"
  41. #include "clang/Frontend/CodeGenOptions.h"
  42. #include "clang/Sema/SemaDiagnostic.h"
  43. #include "llvm/ADT/APSInt.h"
  44. #include "llvm/ADT/Triple.h"
  45. #include "llvm/IR/CallSite.h"
  46. #include "llvm/IR/CallingConv.h"
  47. #include "llvm/IR/DataLayout.h"
  48. #include "llvm/IR/Intrinsics.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/Module.h"
  51. #include "llvm/ProfileData/InstrProfReader.h"
  52. #include "llvm/Support/ConvertUTF.h"
  53. #include "llvm/Support/ErrorHandling.h"
  54. using namespace clang;
  55. using namespace CodeGen;
  56. static const char AnnotationSection[] = "llvm.metadata";
  57. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  58. switch (CGM.getTarget().getCXXABI().getKind()) {
  59. case TargetCXXABI::GenericAArch64:
  60. case TargetCXXABI::GenericARM:
  61. case TargetCXXABI::iOS:
  62. case TargetCXXABI::iOS64:
  63. case TargetCXXABI::GenericMIPS:
  64. case TargetCXXABI::GenericItanium:
  65. return CreateItaniumCXXABI(CGM);
  66. case TargetCXXABI::Microsoft:
  67. return CreateMicrosoftCXXABI(CGM);
  68. }
  69. llvm_unreachable("invalid C++ ABI kind");
  70. }
  71. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  72. llvm::Module &M, const llvm::DataLayout &TD,
  73. DiagnosticsEngine &diags,
  74. CoverageSourceInfo *CoverageInfo)
  75. : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
  76. Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
  77. ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
  78. TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
  79. ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
  80. CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
  81. NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
  82. CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
  83. NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
  84. NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
  85. BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
  86. GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
  87. LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
  88. // Initialize the type cache.
  89. llvm::LLVMContext &LLVMContext = M.getContext();
  90. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  91. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  92. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  93. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  94. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  95. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  96. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  97. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  98. PointerAlignInBytes =
  99. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  100. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  101. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  102. Int8PtrTy = Int8Ty->getPointerTo(0);
  103. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  104. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  105. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  106. if (LangOpts.ObjC1)
  107. createObjCRuntime();
  108. if (LangOpts.OpenCL)
  109. createOpenCLRuntime();
  110. if (LangOpts.OpenMP)
  111. createOpenMPRuntime();
  112. if (LangOpts.CUDA)
  113. createCUDARuntime();
  114. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  115. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  116. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  117. TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  118. getCXXABI().getMangleContext());
  119. // If debug info or coverage generation is enabled, create the CGDebugInfo
  120. // object.
  121. if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
  122. CodeGenOpts.EmitGcovArcs ||
  123. CodeGenOpts.EmitGcovNotes)
  124. DebugInfo = new CGDebugInfo(*this);
  125. Block.GlobalUniqueCount = 0;
  126. if (C.getLangOpts().ObjCAutoRefCount)
  127. ARCData = new ARCEntrypoints();
  128. RRData = new RREntrypoints();
  129. if (!CodeGenOpts.InstrProfileInput.empty()) {
  130. auto ReaderOrErr =
  131. llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
  132. if (std::error_code EC = ReaderOrErr.getError()) {
  133. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  134. "Could not read profile: %0");
  135. getDiags().Report(DiagID) << EC.message();
  136. } else
  137. PGOReader = std::move(ReaderOrErr.get());
  138. }
  139. // If coverage mapping generation is enabled, create the
  140. // CoverageMappingModuleGen object.
  141. if (CodeGenOpts.CoverageMapping)
  142. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  143. }
  144. CodeGenModule::~CodeGenModule() {
  145. delete ObjCRuntime;
  146. delete OpenCLRuntime;
  147. delete OpenMPRuntime;
  148. delete CUDARuntime;
  149. delete TheTargetCodeGenInfo;
  150. delete TBAA;
  151. delete DebugInfo;
  152. delete ARCData;
  153. delete RRData;
  154. }
  155. void CodeGenModule::createObjCRuntime() {
  156. // This is just isGNUFamily(), but we want to force implementors of
  157. // new ABIs to decide how best to do this.
  158. switch (LangOpts.ObjCRuntime.getKind()) {
  159. case ObjCRuntime::GNUstep:
  160. case ObjCRuntime::GCC:
  161. case ObjCRuntime::ObjFW:
  162. ObjCRuntime = CreateGNUObjCRuntime(*this);
  163. return;
  164. case ObjCRuntime::FragileMacOSX:
  165. case ObjCRuntime::MacOSX:
  166. case ObjCRuntime::iOS:
  167. ObjCRuntime = CreateMacObjCRuntime(*this);
  168. return;
  169. }
  170. llvm_unreachable("bad runtime kind");
  171. }
  172. void CodeGenModule::createOpenCLRuntime() {
  173. OpenCLRuntime = new CGOpenCLRuntime(*this);
  174. }
  175. void CodeGenModule::createOpenMPRuntime() {
  176. OpenMPRuntime = new CGOpenMPRuntime(*this);
  177. }
  178. void CodeGenModule::createCUDARuntime() {
  179. CUDARuntime = CreateNVCUDARuntime(*this);
  180. }
  181. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  182. Replacements[Name] = C;
  183. }
  184. void CodeGenModule::applyReplacements() {
  185. for (ReplacementsTy::iterator I = Replacements.begin(),
  186. E = Replacements.end();
  187. I != E; ++I) {
  188. StringRef MangledName = I->first();
  189. llvm::Constant *Replacement = I->second;
  190. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  191. if (!Entry)
  192. continue;
  193. auto *OldF = cast<llvm::Function>(Entry);
  194. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  195. if (!NewF) {
  196. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  197. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  198. } else {
  199. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  200. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  201. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  202. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  203. }
  204. }
  205. // Replace old with new, but keep the old order.
  206. OldF->replaceAllUsesWith(Replacement);
  207. if (NewF) {
  208. NewF->removeFromParent();
  209. OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
  210. }
  211. OldF->eraseFromParent();
  212. }
  213. }
  214. // This is only used in aliases that we created and we know they have a
  215. // linear structure.
  216. static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
  217. llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
  218. const llvm::Constant *C = &GA;
  219. for (;;) {
  220. C = C->stripPointerCasts();
  221. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  222. return GO;
  223. // stripPointerCasts will not walk over weak aliases.
  224. auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
  225. if (!GA2)
  226. return nullptr;
  227. if (!Visited.insert(GA2).second)
  228. return nullptr;
  229. C = GA2->getAliasee();
  230. }
  231. }
  232. void CodeGenModule::checkAliases() {
  233. // Check if the constructed aliases are well formed. It is really unfortunate
  234. // that we have to do this in CodeGen, but we only construct mangled names
  235. // and aliases during codegen.
  236. bool Error = false;
  237. DiagnosticsEngine &Diags = getDiags();
  238. for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
  239. E = Aliases.end(); I != E; ++I) {
  240. const GlobalDecl &GD = *I;
  241. const auto *D = cast<ValueDecl>(GD.getDecl());
  242. const AliasAttr *AA = D->getAttr<AliasAttr>();
  243. StringRef MangledName = getMangledName(GD);
  244. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  245. auto *Alias = cast<llvm::GlobalAlias>(Entry);
  246. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  247. if (!GV) {
  248. Error = true;
  249. Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
  250. } else if (GV->isDeclaration()) {
  251. Error = true;
  252. Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
  253. }
  254. llvm::Constant *Aliasee = Alias->getAliasee();
  255. llvm::GlobalValue *AliaseeGV;
  256. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  257. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  258. else
  259. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  260. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  261. StringRef AliasSection = SA->getName();
  262. if (AliasSection != AliaseeGV->getSection())
  263. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  264. << AliasSection;
  265. }
  266. // We have to handle alias to weak aliases in here. LLVM itself disallows
  267. // this since the object semantics would not match the IL one. For
  268. // compatibility with gcc we implement it by just pointing the alias
  269. // to its aliasee's aliasee. We also warn, since the user is probably
  270. // expecting the link to be weak.
  271. if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
  272. if (GA->mayBeOverridden()) {
  273. Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
  274. << GV->getName() << GA->getName();
  275. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  276. GA->getAliasee(), Alias->getType());
  277. Alias->setAliasee(Aliasee);
  278. }
  279. }
  280. }
  281. if (!Error)
  282. return;
  283. for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
  284. E = Aliases.end(); I != E; ++I) {
  285. const GlobalDecl &GD = *I;
  286. StringRef MangledName = getMangledName(GD);
  287. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  288. auto *Alias = cast<llvm::GlobalAlias>(Entry);
  289. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  290. Alias->eraseFromParent();
  291. }
  292. }
  293. void CodeGenModule::clear() {
  294. DeferredDeclsToEmit.clear();
  295. if (OpenMPRuntime)
  296. OpenMPRuntime->clear();
  297. }
  298. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  299. StringRef MainFile) {
  300. if (!hasDiagnostics())
  301. return;
  302. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  303. if (MainFile.empty())
  304. MainFile = "<stdin>";
  305. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  306. } else
  307. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
  308. << Mismatched;
  309. }
  310. void CodeGenModule::Release() {
  311. EmitDeferred();
  312. applyReplacements();
  313. checkAliases();
  314. EmitCXXGlobalInitFunc();
  315. EmitCXXGlobalDtorFunc();
  316. EmitCXXThreadLocalInitFunc();
  317. if (ObjCRuntime)
  318. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  319. AddGlobalCtor(ObjCInitFunction);
  320. if (PGOReader && PGOStats.hasDiagnostics())
  321. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  322. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  323. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  324. EmitGlobalAnnotations();
  325. EmitStaticExternCAliases();
  326. EmitDeferredUnusedCoverageMappings();
  327. if (CoverageMapping)
  328. CoverageMapping->emit();
  329. emitLLVMUsed();
  330. if (CodeGenOpts.Autolink &&
  331. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  332. EmitModuleLinkOptions();
  333. }
  334. if (CodeGenOpts.DwarfVersion)
  335. // We actually want the latest version when there are conflicts.
  336. // We can change from Warning to Latest if such mode is supported.
  337. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  338. CodeGenOpts.DwarfVersion);
  339. if (DebugInfo)
  340. // We support a single version in the linked module. The LLVM
  341. // parser will drop debug info with a different version number
  342. // (and warn about it, too).
  343. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  344. llvm::DEBUG_METADATA_VERSION);
  345. // We need to record the widths of enums and wchar_t, so that we can generate
  346. // the correct build attributes in the ARM backend.
  347. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  348. if ( Arch == llvm::Triple::arm
  349. || Arch == llvm::Triple::armeb
  350. || Arch == llvm::Triple::thumb
  351. || Arch == llvm::Triple::thumbeb) {
  352. // Width of wchar_t in bytes
  353. uint64_t WCharWidth =
  354. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  355. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  356. // The minimum width of an enum in bytes
  357. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  358. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  359. }
  360. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  361. llvm::PICLevel::Level PL = llvm::PICLevel::Default;
  362. switch (PLevel) {
  363. case 0: break;
  364. case 1: PL = llvm::PICLevel::Small; break;
  365. case 2: PL = llvm::PICLevel::Large; break;
  366. default: llvm_unreachable("Invalid PIC Level");
  367. }
  368. getModule().setPICLevel(PL);
  369. }
  370. SimplifyPersonality();
  371. if (getCodeGenOpts().EmitDeclMetadata)
  372. EmitDeclMetadata();
  373. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  374. EmitCoverageFile();
  375. if (DebugInfo)
  376. DebugInfo->finalize();
  377. EmitVersionIdentMetadata();
  378. EmitTargetMetadata();
  379. }
  380. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  381. // Make sure that this type is translated.
  382. Types.UpdateCompletedType(TD);
  383. }
  384. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  385. if (!TBAA)
  386. return nullptr;
  387. return TBAA->getTBAAInfo(QTy);
  388. }
  389. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  390. if (!TBAA)
  391. return nullptr;
  392. return TBAA->getTBAAInfoForVTablePtr();
  393. }
  394. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  395. if (!TBAA)
  396. return nullptr;
  397. return TBAA->getTBAAStructInfo(QTy);
  398. }
  399. llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
  400. if (!TBAA)
  401. return nullptr;
  402. return TBAA->getTBAAStructTypeInfo(QTy);
  403. }
  404. llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
  405. llvm::MDNode *AccessN,
  406. uint64_t O) {
  407. if (!TBAA)
  408. return nullptr;
  409. return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
  410. }
  411. /// Decorate the instruction with a TBAA tag. For both scalar TBAA
  412. /// and struct-path aware TBAA, the tag has the same format:
  413. /// base type, access type and offset.
  414. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  415. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  416. llvm::MDNode *TBAAInfo,
  417. bool ConvertTypeToTag) {
  418. if (ConvertTypeToTag && TBAA)
  419. Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
  420. TBAA->getTBAAScalarTagInfo(TBAAInfo));
  421. else
  422. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  423. }
  424. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  425. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  426. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  427. }
  428. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  429. /// specified stmt yet.
  430. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  431. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  432. "cannot compile this %0 yet");
  433. std::string Msg = Type;
  434. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  435. << Msg << S->getSourceRange();
  436. }
  437. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  438. /// specified decl yet.
  439. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  440. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  441. "cannot compile this %0 yet");
  442. std::string Msg = Type;
  443. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  444. }
  445. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  446. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  447. }
  448. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  449. const NamedDecl *D) const {
  450. // Internal definitions always have default visibility.
  451. if (GV->hasLocalLinkage()) {
  452. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  453. return;
  454. }
  455. // Set visibility for definitions.
  456. LinkageInfo LV = D->getLinkageAndVisibility();
  457. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  458. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  459. }
  460. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  461. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  462. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  463. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  464. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  465. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  466. }
  467. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  468. CodeGenOptions::TLSModel M) {
  469. switch (M) {
  470. case CodeGenOptions::GeneralDynamicTLSModel:
  471. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  472. case CodeGenOptions::LocalDynamicTLSModel:
  473. return llvm::GlobalVariable::LocalDynamicTLSModel;
  474. case CodeGenOptions::InitialExecTLSModel:
  475. return llvm::GlobalVariable::InitialExecTLSModel;
  476. case CodeGenOptions::LocalExecTLSModel:
  477. return llvm::GlobalVariable::LocalExecTLSModel;
  478. }
  479. llvm_unreachable("Invalid TLS model!");
  480. }
  481. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  482. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  483. llvm::GlobalValue::ThreadLocalMode TLM;
  484. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  485. // Override the TLS model if it is explicitly specified.
  486. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  487. TLM = GetLLVMTLSModel(Attr->getModel());
  488. }
  489. GV->setThreadLocalMode(TLM);
  490. }
  491. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  492. StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
  493. if (!FoundStr.empty())
  494. return FoundStr;
  495. const auto *ND = cast<NamedDecl>(GD.getDecl());
  496. SmallString<256> Buffer;
  497. StringRef Str;
  498. if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  499. llvm::raw_svector_ostream Out(Buffer);
  500. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  501. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  502. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  503. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  504. else
  505. getCXXABI().getMangleContext().mangleName(ND, Out);
  506. Str = Out.str();
  507. } else {
  508. IdentifierInfo *II = ND->getIdentifier();
  509. assert(II && "Attempt to mangle unnamed decl.");
  510. Str = II->getName();
  511. }
  512. // Keep the first result in the case of a mangling collision.
  513. auto Result = Manglings.insert(std::make_pair(Str, GD));
  514. return FoundStr = Result.first->first();
  515. }
  516. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  517. const BlockDecl *BD) {
  518. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  519. const Decl *D = GD.getDecl();
  520. SmallString<256> Buffer;
  521. llvm::raw_svector_ostream Out(Buffer);
  522. if (!D)
  523. MangleCtx.mangleGlobalBlock(BD,
  524. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  525. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  526. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  527. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  528. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  529. else
  530. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  531. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  532. return Result.first->first();
  533. }
  534. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  535. return getModule().getNamedValue(Name);
  536. }
  537. /// AddGlobalCtor - Add a function to the list that will be called before
  538. /// main() runs.
  539. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  540. llvm::Constant *AssociatedData) {
  541. // FIXME: Type coercion of void()* types.
  542. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  543. }
  544. /// AddGlobalDtor - Add a function to the list that will be called
  545. /// when the module is unloaded.
  546. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  547. // FIXME: Type coercion of void()* types.
  548. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  549. }
  550. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  551. // Ctor function type is void()*.
  552. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  553. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  554. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  555. llvm::StructType *CtorStructTy = llvm::StructType::get(
  556. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
  557. // Construct the constructor and destructor arrays.
  558. SmallVector<llvm::Constant*, 8> Ctors;
  559. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  560. llvm::Constant *S[] = {
  561. llvm::ConstantInt::get(Int32Ty, I->Priority, false),
  562. llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
  563. (I->AssociatedData
  564. ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
  565. : llvm::Constant::getNullValue(VoidPtrTy))
  566. };
  567. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  568. }
  569. if (!Ctors.empty()) {
  570. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  571. new llvm::GlobalVariable(TheModule, AT, false,
  572. llvm::GlobalValue::AppendingLinkage,
  573. llvm::ConstantArray::get(AT, Ctors),
  574. GlobalName);
  575. }
  576. }
  577. llvm::GlobalValue::LinkageTypes
  578. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  579. const auto *D = cast<FunctionDecl>(GD.getDecl());
  580. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  581. if (isa<CXXDestructorDecl>(D) &&
  582. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  583. GD.getDtorType())) {
  584. // Destructor variants in the Microsoft C++ ABI are always internal or
  585. // linkonce_odr thunks emitted on an as-needed basis.
  586. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  587. : llvm::GlobalValue::LinkOnceODRLinkage;
  588. }
  589. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  590. }
  591. void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
  592. llvm::Function *F) {
  593. setNonAliasAttributes(D, F);
  594. }
  595. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  596. const CGFunctionInfo &Info,
  597. llvm::Function *F) {
  598. unsigned CallingConv;
  599. AttributeListType AttributeList;
  600. ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
  601. F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
  602. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  603. }
  604. /// Determines whether the language options require us to model
  605. /// unwind exceptions. We treat -fexceptions as mandating this
  606. /// except under the fragile ObjC ABI with only ObjC exceptions
  607. /// enabled. This means, for example, that C with -fexceptions
  608. /// enables this.
  609. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  610. // If exceptions are completely disabled, obviously this is false.
  611. if (!LangOpts.Exceptions) return false;
  612. // If C++ exceptions are enabled, this is true.
  613. if (LangOpts.CXXExceptions) return true;
  614. // If ObjC exceptions are enabled, this depends on the ABI.
  615. if (LangOpts.ObjCExceptions) {
  616. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  617. }
  618. return true;
  619. }
  620. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  621. llvm::Function *F) {
  622. llvm::AttrBuilder B;
  623. if (CodeGenOpts.UnwindTables)
  624. B.addAttribute(llvm::Attribute::UWTable);
  625. if (!hasUnwindExceptions(LangOpts))
  626. B.addAttribute(llvm::Attribute::NoUnwind);
  627. if (D->hasAttr<NakedAttr>()) {
  628. // Naked implies noinline: we should not be inlining such functions.
  629. B.addAttribute(llvm::Attribute::Naked);
  630. B.addAttribute(llvm::Attribute::NoInline);
  631. } else if (D->hasAttr<NoDuplicateAttr>()) {
  632. B.addAttribute(llvm::Attribute::NoDuplicate);
  633. } else if (D->hasAttr<NoInlineAttr>()) {
  634. B.addAttribute(llvm::Attribute::NoInline);
  635. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  636. !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
  637. llvm::Attribute::NoInline)) {
  638. // (noinline wins over always_inline, and we can't specify both in IR)
  639. B.addAttribute(llvm::Attribute::AlwaysInline);
  640. }
  641. if (D->hasAttr<ColdAttr>()) {
  642. if (!D->hasAttr<OptimizeNoneAttr>())
  643. B.addAttribute(llvm::Attribute::OptimizeForSize);
  644. B.addAttribute(llvm::Attribute::Cold);
  645. }
  646. if (D->hasAttr<MinSizeAttr>())
  647. B.addAttribute(llvm::Attribute::MinSize);
  648. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  649. B.addAttribute(llvm::Attribute::StackProtect);
  650. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  651. B.addAttribute(llvm::Attribute::StackProtectStrong);
  652. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  653. B.addAttribute(llvm::Attribute::StackProtectReq);
  654. // Add sanitizer attributes if function is not blacklisted.
  655. if (!isInSanitizerBlacklist(F, D->getLocation())) {
  656. // When AddressSanitizer is enabled, set SanitizeAddress attribute
  657. // unless __attribute__((no_sanitize_address)) is used.
  658. if (LangOpts.Sanitize.has(SanitizerKind::Address) &&
  659. !D->hasAttr<NoSanitizeAddressAttr>())
  660. B.addAttribute(llvm::Attribute::SanitizeAddress);
  661. // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
  662. if (LangOpts.Sanitize.has(SanitizerKind::Thread) &&
  663. !D->hasAttr<NoSanitizeThreadAttr>())
  664. B.addAttribute(llvm::Attribute::SanitizeThread);
  665. // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
  666. if (LangOpts.Sanitize.has(SanitizerKind::Memory) &&
  667. !D->hasAttr<NoSanitizeMemoryAttr>())
  668. B.addAttribute(llvm::Attribute::SanitizeMemory);
  669. }
  670. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  671. llvm::AttributeSet::get(
  672. F->getContext(), llvm::AttributeSet::FunctionIndex, B));
  673. if (D->hasAttr<OptimizeNoneAttr>()) {
  674. // OptimizeNone implies noinline; we should not be inlining such functions.
  675. F->addFnAttr(llvm::Attribute::OptimizeNone);
  676. F->addFnAttr(llvm::Attribute::NoInline);
  677. // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
  678. assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
  679. "OptimizeNone and OptimizeForSize on same function!");
  680. assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
  681. "OptimizeNone and MinSize on same function!");
  682. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  683. "OptimizeNone and AlwaysInline on same function!");
  684. // Attribute 'inlinehint' has no effect on 'optnone' functions.
  685. // Explicitly remove it from the set of function attributes.
  686. F->removeFnAttr(llvm::Attribute::InlineHint);
  687. }
  688. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  689. F->setUnnamedAddr(true);
  690. else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
  691. if (MD->isVirtual())
  692. F->setUnnamedAddr(true);
  693. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  694. if (alignment)
  695. F->setAlignment(alignment);
  696. // C++ ABI requires 2-byte alignment for member functions.
  697. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  698. F->setAlignment(2);
  699. }
  700. void CodeGenModule::SetCommonAttributes(const Decl *D,
  701. llvm::GlobalValue *GV) {
  702. if (const auto *ND = dyn_cast<NamedDecl>(D))
  703. setGlobalVisibility(GV, ND);
  704. else
  705. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  706. if (D->hasAttr<UsedAttr>())
  707. addUsedGlobal(GV);
  708. }
  709. void CodeGenModule::setAliasAttributes(const Decl *D,
  710. llvm::GlobalValue *GV) {
  711. SetCommonAttributes(D, GV);
  712. // Process the dllexport attribute based on whether the original definition
  713. // (not necessarily the aliasee) was exported.
  714. if (D->hasAttr<DLLExportAttr>())
  715. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  716. }
  717. void CodeGenModule::setNonAliasAttributes(const Decl *D,
  718. llvm::GlobalObject *GO) {
  719. SetCommonAttributes(D, GO);
  720. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  721. GO->setSection(SA->getName());
  722. getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
  723. }
  724. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  725. llvm::Function *F,
  726. const CGFunctionInfo &FI) {
  727. SetLLVMFunctionAttributes(D, FI, F);
  728. SetLLVMFunctionAttributesForDefinition(D, F);
  729. F->setLinkage(llvm::Function::InternalLinkage);
  730. setNonAliasAttributes(D, F);
  731. }
  732. static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
  733. const NamedDecl *ND) {
  734. // Set linkage and visibility in case we never see a definition.
  735. LinkageInfo LV = ND->getLinkageAndVisibility();
  736. if (LV.getLinkage() != ExternalLinkage) {
  737. // Don't set internal linkage on declarations.
  738. } else {
  739. if (ND->hasAttr<DLLImportAttr>()) {
  740. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  741. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  742. } else if (ND->hasAttr<DLLExportAttr>()) {
  743. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  744. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  745. } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
  746. // "extern_weak" is overloaded in LLVM; we probably should have
  747. // separate linkage types for this.
  748. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  749. }
  750. // Set visibility on a declaration only if it's explicit.
  751. if (LV.isVisibilityExplicit())
  752. GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
  753. }
  754. }
  755. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  756. bool IsIncompleteFunction,
  757. bool IsThunk) {
  758. if (unsigned IID = F->getIntrinsicID()) {
  759. // If this is an intrinsic function, set the function's attributes
  760. // to the intrinsic's attributes.
  761. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
  762. (llvm::Intrinsic::ID)IID));
  763. return;
  764. }
  765. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  766. if (!IsIncompleteFunction)
  767. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  768. // Add the Returned attribute for "this", except for iOS 5 and earlier
  769. // where substantial code, including the libstdc++ dylib, was compiled with
  770. // GCC and does not actually return "this".
  771. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  772. !(getTarget().getTriple().isiOS() &&
  773. getTarget().getTriple().isOSVersionLT(6))) {
  774. assert(!F->arg_empty() &&
  775. F->arg_begin()->getType()
  776. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  777. "unexpected this return");
  778. F->addAttribute(1, llvm::Attribute::Returned);
  779. }
  780. // Only a few attributes are set on declarations; these may later be
  781. // overridden by a definition.
  782. setLinkageAndVisibilityForGV(F, FD);
  783. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
  784. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  785. // Don't dllexport/import destructor thunks.
  786. F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  787. }
  788. }
  789. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  790. F->setSection(SA->getName());
  791. // A replaceable global allocation function does not act like a builtin by
  792. // default, only if it is invoked by a new-expression or delete-expression.
  793. if (FD->isReplaceableGlobalAllocationFunction())
  794. F->addAttribute(llvm::AttributeSet::FunctionIndex,
  795. llvm::Attribute::NoBuiltin);
  796. }
  797. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  798. assert(!GV->isDeclaration() &&
  799. "Only globals with definition can force usage.");
  800. LLVMUsed.push_back(GV);
  801. }
  802. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  803. assert(!GV->isDeclaration() &&
  804. "Only globals with definition can force usage.");
  805. LLVMCompilerUsed.push_back(GV);
  806. }
  807. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  808. std::vector<llvm::WeakVH> &List) {
  809. // Don't create llvm.used if there is no need.
  810. if (List.empty())
  811. return;
  812. // Convert List to what ConstantArray needs.
  813. SmallVector<llvm::Constant*, 8> UsedArray;
  814. UsedArray.resize(List.size());
  815. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  816. UsedArray[i] =
  817. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  818. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  819. }
  820. if (UsedArray.empty())
  821. return;
  822. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  823. auto *GV = new llvm::GlobalVariable(
  824. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  825. llvm::ConstantArray::get(ATy, UsedArray), Name);
  826. GV->setSection("llvm.metadata");
  827. }
  828. void CodeGenModule::emitLLVMUsed() {
  829. emitUsed(*this, "llvm.used", LLVMUsed);
  830. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  831. }
  832. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  833. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  834. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  835. }
  836. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  837. llvm::SmallString<32> Opt;
  838. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  839. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  840. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  841. }
  842. void CodeGenModule::AddDependentLib(StringRef Lib) {
  843. llvm::SmallString<24> Opt;
  844. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  845. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  846. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  847. }
  848. /// \brief Add link options implied by the given module, including modules
  849. /// it depends on, using a postorder walk.
  850. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  851. SmallVectorImpl<llvm::Metadata *> &Metadata,
  852. llvm::SmallPtrSet<Module *, 16> &Visited) {
  853. // Import this module's parent.
  854. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  855. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  856. }
  857. // Import this module's dependencies.
  858. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  859. if (Visited.insert(Mod->Imports[I - 1]).second)
  860. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  861. }
  862. // Add linker options to link against the libraries/frameworks
  863. // described by this module.
  864. llvm::LLVMContext &Context = CGM.getLLVMContext();
  865. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  866. // Link against a framework. Frameworks are currently Darwin only, so we
  867. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  868. if (Mod->LinkLibraries[I-1].IsFramework) {
  869. llvm::Metadata *Args[2] = {
  870. llvm::MDString::get(Context, "-framework"),
  871. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  872. Metadata.push_back(llvm::MDNode::get(Context, Args));
  873. continue;
  874. }
  875. // Link against a library.
  876. llvm::SmallString<24> Opt;
  877. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  878. Mod->LinkLibraries[I-1].Library, Opt);
  879. auto *OptString = llvm::MDString::get(Context, Opt);
  880. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  881. }
  882. }
  883. void CodeGenModule::EmitModuleLinkOptions() {
  884. // Collect the set of all of the modules we want to visit to emit link
  885. // options, which is essentially the imported modules and all of their
  886. // non-explicit child modules.
  887. llvm::SetVector<clang::Module *> LinkModules;
  888. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  889. SmallVector<clang::Module *, 16> Stack;
  890. // Seed the stack with imported modules.
  891. for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
  892. MEnd = ImportedModules.end();
  893. M != MEnd; ++M) {
  894. if (Visited.insert(*M).second)
  895. Stack.push_back(*M);
  896. }
  897. // Find all of the modules to import, making a little effort to prune
  898. // non-leaf modules.
  899. while (!Stack.empty()) {
  900. clang::Module *Mod = Stack.pop_back_val();
  901. bool AnyChildren = false;
  902. // Visit the submodules of this module.
  903. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  904. SubEnd = Mod->submodule_end();
  905. Sub != SubEnd; ++Sub) {
  906. // Skip explicit children; they need to be explicitly imported to be
  907. // linked against.
  908. if ((*Sub)->IsExplicit)
  909. continue;
  910. if (Visited.insert(*Sub).second) {
  911. Stack.push_back(*Sub);
  912. AnyChildren = true;
  913. }
  914. }
  915. // We didn't find any children, so add this module to the list of
  916. // modules to link against.
  917. if (!AnyChildren) {
  918. LinkModules.insert(Mod);
  919. }
  920. }
  921. // Add link options for all of the imported modules in reverse topological
  922. // order. We don't do anything to try to order import link flags with respect
  923. // to linker options inserted by things like #pragma comment().
  924. SmallVector<llvm::Metadata *, 16> MetadataArgs;
  925. Visited.clear();
  926. for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
  927. MEnd = LinkModules.end();
  928. M != MEnd; ++M) {
  929. if (Visited.insert(*M).second)
  930. addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
  931. }
  932. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  933. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  934. // Add the linker options metadata flag.
  935. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  936. llvm::MDNode::get(getLLVMContext(),
  937. LinkerOptionsMetadata));
  938. }
  939. void CodeGenModule::EmitDeferred() {
  940. // Emit code for any potentially referenced deferred decls. Since a
  941. // previously unused static decl may become used during the generation of code
  942. // for a static function, iterate until no changes are made.
  943. if (!DeferredVTables.empty()) {
  944. EmitDeferredVTables();
  945. // Emitting a v-table doesn't directly cause more v-tables to
  946. // become deferred, although it can cause functions to be
  947. // emitted that then need those v-tables.
  948. assert(DeferredVTables.empty());
  949. }
  950. // Stop if we're out of both deferred v-tables and deferred declarations.
  951. if (DeferredDeclsToEmit.empty())
  952. return;
  953. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  954. // work, it will not interfere with this.
  955. std::vector<DeferredGlobal> CurDeclsToEmit;
  956. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  957. for (DeferredGlobal &G : CurDeclsToEmit) {
  958. GlobalDecl D = G.GD;
  959. llvm::GlobalValue *GV = G.GV;
  960. G.GV = nullptr;
  961. assert(!GV || GV == GetGlobalValue(getMangledName(D)));
  962. if (!GV)
  963. GV = GetGlobalValue(getMangledName(D));
  964. // Check to see if we've already emitted this. This is necessary
  965. // for a couple of reasons: first, decls can end up in the
  966. // deferred-decls queue multiple times, and second, decls can end
  967. // up with definitions in unusual ways (e.g. by an extern inline
  968. // function acquiring a strong function redefinition). Just
  969. // ignore these cases.
  970. if (GV && !GV->isDeclaration())
  971. continue;
  972. // Otherwise, emit the definition and move on to the next one.
  973. EmitGlobalDefinition(D, GV);
  974. // If we found out that we need to emit more decls, do that recursively.
  975. // This has the advantage that the decls are emitted in a DFS and related
  976. // ones are close together, which is convenient for testing.
  977. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  978. EmitDeferred();
  979. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  980. }
  981. }
  982. }
  983. void CodeGenModule::EmitGlobalAnnotations() {
  984. if (Annotations.empty())
  985. return;
  986. // Create a new global variable for the ConstantStruct in the Module.
  987. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  988. Annotations[0]->getType(), Annotations.size()), Annotations);
  989. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  990. llvm::GlobalValue::AppendingLinkage,
  991. Array, "llvm.global.annotations");
  992. gv->setSection(AnnotationSection);
  993. }
  994. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  995. llvm::Constant *&AStr = AnnotationStrings[Str];
  996. if (AStr)
  997. return AStr;
  998. // Not found yet, create a new global.
  999. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1000. auto *gv =
  1001. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1002. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1003. gv->setSection(AnnotationSection);
  1004. gv->setUnnamedAddr(true);
  1005. AStr = gv;
  1006. return gv;
  1007. }
  1008. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1009. SourceManager &SM = getContext().getSourceManager();
  1010. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1011. if (PLoc.isValid())
  1012. return EmitAnnotationString(PLoc.getFilename());
  1013. return EmitAnnotationString(SM.getBufferName(Loc));
  1014. }
  1015. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1016. SourceManager &SM = getContext().getSourceManager();
  1017. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1018. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1019. SM.getExpansionLineNumber(L);
  1020. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1021. }
  1022. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1023. const AnnotateAttr *AA,
  1024. SourceLocation L) {
  1025. // Get the globals for file name, annotation, and the line number.
  1026. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1027. *UnitGV = EmitAnnotationUnit(L),
  1028. *LineNoCst = EmitAnnotationLineNo(L);
  1029. // Create the ConstantStruct for the global annotation.
  1030. llvm::Constant *Fields[4] = {
  1031. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1032. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1033. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1034. LineNoCst
  1035. };
  1036. return llvm::ConstantStruct::getAnon(Fields);
  1037. }
  1038. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1039. llvm::GlobalValue *GV) {
  1040. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1041. // Get the struct elements for these annotations.
  1042. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1043. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1044. }
  1045. bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
  1046. SourceLocation Loc) const {
  1047. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1048. // Blacklist by function name.
  1049. if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
  1050. return true;
  1051. // Blacklist by location.
  1052. if (!Loc.isInvalid())
  1053. return SanitizerBL.isBlacklistedLocation(Loc);
  1054. // If location is unknown, this may be a compiler-generated function. Assume
  1055. // it's located in the main file.
  1056. auto &SM = Context.getSourceManager();
  1057. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1058. return SanitizerBL.isBlacklistedFile(MainFile->getName());
  1059. }
  1060. return false;
  1061. }
  1062. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1063. SourceLocation Loc, QualType Ty,
  1064. StringRef Category) const {
  1065. // For now globals can be blacklisted only in ASan.
  1066. if (!LangOpts.Sanitize.has(SanitizerKind::Address))
  1067. return false;
  1068. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1069. if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
  1070. return true;
  1071. if (SanitizerBL.isBlacklistedLocation(Loc, Category))
  1072. return true;
  1073. // Check global type.
  1074. if (!Ty.isNull()) {
  1075. // Drill down the array types: if global variable of a fixed type is
  1076. // blacklisted, we also don't instrument arrays of them.
  1077. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1078. Ty = AT->getElementType();
  1079. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1080. // We allow to blacklist only record types (classes, structs etc.)
  1081. if (Ty->isRecordType()) {
  1082. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1083. if (SanitizerBL.isBlacklistedType(TypeStr, Category))
  1084. return true;
  1085. }
  1086. }
  1087. return false;
  1088. }
  1089. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1090. // Never defer when EmitAllDecls is specified.
  1091. if (LangOpts.EmitAllDecls)
  1092. return true;
  1093. return getContext().DeclMustBeEmitted(Global);
  1094. }
  1095. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1096. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1097. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1098. // Implicit template instantiations may change linkage if they are later
  1099. // explicitly instantiated, so they should not be emitted eagerly.
  1100. return false;
  1101. return true;
  1102. }
  1103. llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
  1104. const CXXUuidofExpr* E) {
  1105. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1106. // well-formed.
  1107. StringRef Uuid = E->getUuidAsStringRef(Context);
  1108. std::string Name = "_GUID_" + Uuid.lower();
  1109. std::replace(Name.begin(), Name.end(), '-', '_');
  1110. // Look for an existing global.
  1111. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1112. return GV;
  1113. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1114. assert(Init && "failed to initialize as constant");
  1115. auto *GV = new llvm::GlobalVariable(
  1116. getModule(), Init->getType(),
  1117. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1118. if (supportsCOMDAT())
  1119. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1120. return GV;
  1121. }
  1122. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1123. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1124. assert(AA && "No alias?");
  1125. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1126. // See if there is already something with the target's name in the module.
  1127. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1128. if (Entry) {
  1129. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1130. return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1131. }
  1132. llvm::Constant *Aliasee;
  1133. if (isa<llvm::FunctionType>(DeclTy))
  1134. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1135. GlobalDecl(cast<FunctionDecl>(VD)),
  1136. /*ForVTable=*/false);
  1137. else
  1138. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1139. llvm::PointerType::getUnqual(DeclTy),
  1140. nullptr);
  1141. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1142. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1143. WeakRefReferences.insert(F);
  1144. return Aliasee;
  1145. }
  1146. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1147. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1148. // Weak references don't produce any output by themselves.
  1149. if (Global->hasAttr<WeakRefAttr>())
  1150. return;
  1151. // If this is an alias definition (which otherwise looks like a declaration)
  1152. // emit it now.
  1153. if (Global->hasAttr<AliasAttr>())
  1154. return EmitAliasDefinition(GD);
  1155. // If this is CUDA, be selective about which declarations we emit.
  1156. if (LangOpts.CUDA) {
  1157. if (LangOpts.CUDAIsDevice) {
  1158. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1159. !Global->hasAttr<CUDAGlobalAttr>() &&
  1160. !Global->hasAttr<CUDAConstantAttr>() &&
  1161. !Global->hasAttr<CUDASharedAttr>())
  1162. return;
  1163. } else {
  1164. if (!Global->hasAttr<CUDAHostAttr>() && (
  1165. Global->hasAttr<CUDADeviceAttr>() ||
  1166. Global->hasAttr<CUDAConstantAttr>() ||
  1167. Global->hasAttr<CUDASharedAttr>()))
  1168. return;
  1169. }
  1170. }
  1171. // Ignore declarations, they will be emitted on their first use.
  1172. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1173. // Forward declarations are emitted lazily on first use.
  1174. if (!FD->doesThisDeclarationHaveABody()) {
  1175. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1176. return;
  1177. StringRef MangledName = getMangledName(GD);
  1178. // Compute the function info and LLVM type.
  1179. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1180. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1181. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1182. /*DontDefer=*/false);
  1183. return;
  1184. }
  1185. } else {
  1186. const auto *VD = cast<VarDecl>(Global);
  1187. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1188. if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1189. !Context.isMSStaticDataMemberInlineDefinition(VD))
  1190. return;
  1191. }
  1192. // Defer code generation to first use when possible, e.g. if this is an inline
  1193. // function. If the global must always be emitted, do it eagerly if possible
  1194. // to benefit from cache locality.
  1195. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1196. // Emit the definition if it can't be deferred.
  1197. EmitGlobalDefinition(GD);
  1198. return;
  1199. }
  1200. // If we're deferring emission of a C++ variable with an
  1201. // initializer, remember the order in which it appeared in the file.
  1202. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1203. cast<VarDecl>(Global)->hasInit()) {
  1204. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1205. CXXGlobalInits.push_back(nullptr);
  1206. }
  1207. StringRef MangledName = getMangledName(GD);
  1208. if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
  1209. // The value has already been used and should therefore be emitted.
  1210. addDeferredDeclToEmit(GV, GD);
  1211. } else if (MustBeEmitted(Global)) {
  1212. // The value must be emitted, but cannot be emitted eagerly.
  1213. assert(!MayBeEmittedEagerly(Global));
  1214. addDeferredDeclToEmit(/*GV=*/nullptr, GD);
  1215. } else {
  1216. // Otherwise, remember that we saw a deferred decl with this name. The
  1217. // first use of the mangled name will cause it to move into
  1218. // DeferredDeclsToEmit.
  1219. DeferredDecls[MangledName] = GD;
  1220. }
  1221. }
  1222. namespace {
  1223. struct FunctionIsDirectlyRecursive :
  1224. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1225. const StringRef Name;
  1226. const Builtin::Context &BI;
  1227. bool Result;
  1228. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1229. Name(N), BI(C), Result(false) {
  1230. }
  1231. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1232. bool TraverseCallExpr(CallExpr *E) {
  1233. const FunctionDecl *FD = E->getDirectCallee();
  1234. if (!FD)
  1235. return true;
  1236. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1237. if (Attr && Name == Attr->getLabel()) {
  1238. Result = true;
  1239. return false;
  1240. }
  1241. unsigned BuiltinID = FD->getBuiltinID();
  1242. if (!BuiltinID)
  1243. return true;
  1244. StringRef BuiltinName = BI.GetName(BuiltinID);
  1245. if (BuiltinName.startswith("__builtin_") &&
  1246. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1247. Result = true;
  1248. return false;
  1249. }
  1250. return true;
  1251. }
  1252. };
  1253. }
  1254. // isTriviallyRecursive - Check if this function calls another
  1255. // decl that, because of the asm attribute or the other decl being a builtin,
  1256. // ends up pointing to itself.
  1257. bool
  1258. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1259. StringRef Name;
  1260. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1261. // asm labels are a special kind of mangling we have to support.
  1262. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1263. if (!Attr)
  1264. return false;
  1265. Name = Attr->getLabel();
  1266. } else {
  1267. Name = FD->getName();
  1268. }
  1269. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1270. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1271. return Walker.Result;
  1272. }
  1273. bool
  1274. CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1275. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1276. return true;
  1277. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1278. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1279. return false;
  1280. // PR9614. Avoid cases where the source code is lying to us. An available
  1281. // externally function should have an equivalent function somewhere else,
  1282. // but a function that calls itself is clearly not equivalent to the real
  1283. // implementation.
  1284. // This happens in glibc's btowc and in some configure checks.
  1285. return !isTriviallyRecursive(F);
  1286. }
  1287. /// If the type for the method's class was generated by
  1288. /// CGDebugInfo::createContextChain(), the cache contains only a
  1289. /// limited DIType without any declarations. Since EmitFunctionStart()
  1290. /// needs to find the canonical declaration for each method, we need
  1291. /// to construct the complete type prior to emitting the method.
  1292. void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
  1293. if (!D->isInstance())
  1294. return;
  1295. if (CGDebugInfo *DI = getModuleDebugInfo())
  1296. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
  1297. const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
  1298. DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
  1299. }
  1300. }
  1301. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1302. const auto *D = cast<ValueDecl>(GD.getDecl());
  1303. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1304. Context.getSourceManager(),
  1305. "Generating code for declaration");
  1306. if (isa<FunctionDecl>(D)) {
  1307. // At -O0, don't generate IR for functions with available_externally
  1308. // linkage.
  1309. if (!shouldEmitFunction(GD))
  1310. return;
  1311. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1312. CompleteDIClassType(Method);
  1313. // Make sure to emit the definition(s) before we emit the thunks.
  1314. // This is necessary for the generation of certain thunks.
  1315. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1316. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1317. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1318. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1319. else
  1320. EmitGlobalFunctionDefinition(GD, GV);
  1321. if (Method->isVirtual())
  1322. getVTables().EmitThunks(GD);
  1323. return;
  1324. }
  1325. return EmitGlobalFunctionDefinition(GD, GV);
  1326. }
  1327. if (const auto *VD = dyn_cast<VarDecl>(D))
  1328. return EmitGlobalVarDefinition(VD);
  1329. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1330. }
  1331. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1332. /// module, create and return an llvm Function with the specified type. If there
  1333. /// is something in the module with the specified name, return it potentially
  1334. /// bitcasted to the right type.
  1335. ///
  1336. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1337. /// to set the attributes on the function when it is first created.
  1338. llvm::Constant *
  1339. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  1340. llvm::Type *Ty,
  1341. GlobalDecl GD, bool ForVTable,
  1342. bool DontDefer, bool IsThunk,
  1343. llvm::AttributeSet ExtraAttrs) {
  1344. const Decl *D = GD.getDecl();
  1345. // Lookup the entry, lazily creating it if necessary.
  1346. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1347. if (Entry) {
  1348. if (WeakRefReferences.erase(Entry)) {
  1349. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1350. if (FD && !FD->hasAttr<WeakAttr>())
  1351. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1352. }
  1353. // Handle dropped DLL attributes.
  1354. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1355. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1356. if (Entry->getType()->getElementType() == Ty)
  1357. return Entry;
  1358. // Make sure the result is of the correct type.
  1359. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1360. }
  1361. // This function doesn't have a complete type (for example, the return
  1362. // type is an incomplete struct). Use a fake type instead, and make
  1363. // sure not to try to set attributes.
  1364. bool IsIncompleteFunction = false;
  1365. llvm::FunctionType *FTy;
  1366. if (isa<llvm::FunctionType>(Ty)) {
  1367. FTy = cast<llvm::FunctionType>(Ty);
  1368. } else {
  1369. FTy = llvm::FunctionType::get(VoidTy, false);
  1370. IsIncompleteFunction = true;
  1371. }
  1372. llvm::Function *F = llvm::Function::Create(FTy,
  1373. llvm::Function::ExternalLinkage,
  1374. MangledName, &getModule());
  1375. assert(F->getName() == MangledName && "name was uniqued!");
  1376. if (D)
  1377. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  1378. if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
  1379. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
  1380. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  1381. llvm::AttributeSet::get(VMContext,
  1382. llvm::AttributeSet::FunctionIndex,
  1383. B));
  1384. }
  1385. if (!DontDefer) {
  1386. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1387. // each other bottoming out with the base dtor. Therefore we emit non-base
  1388. // dtors on usage, even if there is no dtor definition in the TU.
  1389. if (D && isa<CXXDestructorDecl>(D) &&
  1390. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1391. GD.getDtorType()))
  1392. addDeferredDeclToEmit(F, GD);
  1393. // This is the first use or definition of a mangled name. If there is a
  1394. // deferred decl with this name, remember that we need to emit it at the end
  1395. // of the file.
  1396. auto DDI = DeferredDecls.find(MangledName);
  1397. if (DDI != DeferredDecls.end()) {
  1398. // Move the potentially referenced deferred decl to the
  1399. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  1400. // don't need it anymore).
  1401. addDeferredDeclToEmit(F, DDI->second);
  1402. DeferredDecls.erase(DDI);
  1403. // Otherwise, there are cases we have to worry about where we're
  1404. // using a declaration for which we must emit a definition but where
  1405. // we might not find a top-level definition:
  1406. // - member functions defined inline in their classes
  1407. // - friend functions defined inline in some class
  1408. // - special member functions with implicit definitions
  1409. // If we ever change our AST traversal to walk into class methods,
  1410. // this will be unnecessary.
  1411. //
  1412. // We also don't emit a definition for a function if it's going to be an
  1413. // entry in a vtable, unless it's already marked as used.
  1414. } else if (getLangOpts().CPlusPlus && D) {
  1415. // Look for a declaration that's lexically in a record.
  1416. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  1417. FD = FD->getPreviousDecl()) {
  1418. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1419. if (FD->doesThisDeclarationHaveABody()) {
  1420. addDeferredDeclToEmit(F, GD.getWithDecl(FD));
  1421. break;
  1422. }
  1423. }
  1424. }
  1425. }
  1426. }
  1427. // Make sure the result is of the requested type.
  1428. if (!IsIncompleteFunction) {
  1429. assert(F->getType()->getElementType() == Ty);
  1430. return F;
  1431. }
  1432. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1433. return llvm::ConstantExpr::getBitCast(F, PTy);
  1434. }
  1435. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1436. /// non-null, then this function will use the specified type if it has to
  1437. /// create it (this occurs when we see a definition of the function).
  1438. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1439. llvm::Type *Ty,
  1440. bool ForVTable,
  1441. bool DontDefer) {
  1442. // If there was no specific requested type, just convert it now.
  1443. if (!Ty)
  1444. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  1445. StringRef MangledName = getMangledName(GD);
  1446. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
  1447. }
  1448. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1449. /// type and name.
  1450. llvm::Constant *
  1451. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  1452. StringRef Name,
  1453. llvm::AttributeSet ExtraAttrs) {
  1454. llvm::Constant *C =
  1455. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1456. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1457. if (auto *F = dyn_cast<llvm::Function>(C))
  1458. if (F->empty())
  1459. F->setCallingConv(getRuntimeCC());
  1460. return C;
  1461. }
  1462. /// CreateBuiltinFunction - Create a new builtin function with the specified
  1463. /// type and name.
  1464. llvm::Constant *
  1465. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
  1466. StringRef Name,
  1467. llvm::AttributeSet ExtraAttrs) {
  1468. llvm::Constant *C =
  1469. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1470. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1471. if (auto *F = dyn_cast<llvm::Function>(C))
  1472. if (F->empty())
  1473. F->setCallingConv(getBuiltinCC());
  1474. return C;
  1475. }
  1476. /// isTypeConstant - Determine whether an object of this type can be emitted
  1477. /// as a constant.
  1478. ///
  1479. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1480. /// will not be considered. The caller will need to verify that the object is
  1481. /// not written to during its construction.
  1482. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1483. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1484. return false;
  1485. if (Context.getLangOpts().CPlusPlus) {
  1486. if (const CXXRecordDecl *Record
  1487. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1488. return ExcludeCtor && !Record->hasMutableFields() &&
  1489. Record->hasTrivialDestructor();
  1490. }
  1491. return true;
  1492. }
  1493. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1494. /// create and return an llvm GlobalVariable with the specified type. If there
  1495. /// is something in the module with the specified name, return it potentially
  1496. /// bitcasted to the right type.
  1497. ///
  1498. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1499. /// to set the attributes on the global when it is first created.
  1500. llvm::Constant *
  1501. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1502. llvm::PointerType *Ty,
  1503. const VarDecl *D) {
  1504. // Lookup the entry, lazily creating it if necessary.
  1505. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1506. if (Entry) {
  1507. if (WeakRefReferences.erase(Entry)) {
  1508. if (D && !D->hasAttr<WeakAttr>())
  1509. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1510. }
  1511. // Handle dropped DLL attributes.
  1512. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1513. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1514. if (Entry->getType() == Ty)
  1515. return Entry;
  1516. // Make sure the result is of the correct type.
  1517. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  1518. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  1519. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1520. }
  1521. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1522. auto *GV = new llvm::GlobalVariable(
  1523. getModule(), Ty->getElementType(), false,
  1524. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  1525. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1526. // This is the first use or definition of a mangled name. If there is a
  1527. // deferred decl with this name, remember that we need to emit it at the end
  1528. // of the file.
  1529. auto DDI = DeferredDecls.find(MangledName);
  1530. if (DDI != DeferredDecls.end()) {
  1531. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1532. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1533. addDeferredDeclToEmit(GV, DDI->second);
  1534. DeferredDecls.erase(DDI);
  1535. }
  1536. // Handle things which are present even on external declarations.
  1537. if (D) {
  1538. // FIXME: This code is overly simple and should be merged with other global
  1539. // handling.
  1540. GV->setConstant(isTypeConstant(D->getType(), false));
  1541. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1542. setLinkageAndVisibilityForGV(GV, D);
  1543. if (D->getTLSKind()) {
  1544. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1545. CXXThreadLocals.push_back(std::make_pair(D, GV));
  1546. setTLSMode(GV, *D);
  1547. }
  1548. // If required by the ABI, treat declarations of static data members with
  1549. // inline initializers as definitions.
  1550. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  1551. EmitGlobalVarDefinition(D);
  1552. }
  1553. // Handle XCore specific ABI requirements.
  1554. if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
  1555. D->getLanguageLinkage() == CLanguageLinkage &&
  1556. D->getType().isConstant(Context) &&
  1557. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  1558. GV->setSection(".cp.rodata");
  1559. }
  1560. if (AddrSpace != Ty->getAddressSpace())
  1561. return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
  1562. return GV;
  1563. }
  1564. llvm::GlobalVariable *
  1565. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1566. llvm::Type *Ty,
  1567. llvm::GlobalValue::LinkageTypes Linkage) {
  1568. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1569. llvm::GlobalVariable *OldGV = nullptr;
  1570. if (GV) {
  1571. // Check if the variable has the right type.
  1572. if (GV->getType()->getElementType() == Ty)
  1573. return GV;
  1574. // Because C++ name mangling, the only way we can end up with an already
  1575. // existing global with the same name is if it has been declared extern "C".
  1576. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1577. OldGV = GV;
  1578. }
  1579. // Create a new variable.
  1580. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1581. Linkage, nullptr, Name);
  1582. if (OldGV) {
  1583. // Replace occurrences of the old variable if needed.
  1584. GV->takeName(OldGV);
  1585. if (!OldGV->use_empty()) {
  1586. llvm::Constant *NewPtrForOldDecl =
  1587. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1588. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1589. }
  1590. OldGV->eraseFromParent();
  1591. }
  1592. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  1593. !GV->hasAvailableExternallyLinkage())
  1594. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1595. return GV;
  1596. }
  1597. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1598. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1599. /// then it will be created with the specified type instead of whatever the
  1600. /// normal requested type would be.
  1601. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1602. llvm::Type *Ty) {
  1603. assert(D->hasGlobalStorage() && "Not a global variable");
  1604. QualType ASTTy = D->getType();
  1605. if (!Ty)
  1606. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1607. llvm::PointerType *PTy =
  1608. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1609. StringRef MangledName = getMangledName(D);
  1610. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1611. }
  1612. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1613. /// specified type and name.
  1614. llvm::Constant *
  1615. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1616. StringRef Name) {
  1617. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  1618. }
  1619. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1620. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1621. if (!MustBeEmitted(D)) {
  1622. // If we have not seen a reference to this variable yet, place it
  1623. // into the deferred declarations table to be emitted if needed
  1624. // later.
  1625. StringRef MangledName = getMangledName(D);
  1626. if (!GetGlobalValue(MangledName)) {
  1627. DeferredDecls[MangledName] = D;
  1628. return;
  1629. }
  1630. }
  1631. // The tentative definition is the only definition.
  1632. EmitGlobalVarDefinition(D);
  1633. }
  1634. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1635. return Context.toCharUnitsFromBits(
  1636. TheDataLayout.getTypeStoreSizeInBits(Ty));
  1637. }
  1638. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1639. unsigned AddrSpace) {
  1640. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  1641. if (D->hasAttr<CUDAConstantAttr>())
  1642. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1643. else if (D->hasAttr<CUDASharedAttr>())
  1644. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1645. else
  1646. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1647. }
  1648. return AddrSpace;
  1649. }
  1650. template<typename SomeDecl>
  1651. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  1652. llvm::GlobalValue *GV) {
  1653. if (!getLangOpts().CPlusPlus)
  1654. return;
  1655. // Must have 'used' attribute, or else inline assembly can't rely on
  1656. // the name existing.
  1657. if (!D->template hasAttr<UsedAttr>())
  1658. return;
  1659. // Must have internal linkage and an ordinary name.
  1660. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  1661. return;
  1662. // Must be in an extern "C" context. Entities declared directly within
  1663. // a record are not extern "C" even if the record is in such a context.
  1664. const SomeDecl *First = D->getFirstDecl();
  1665. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  1666. return;
  1667. // OK, this is an internal linkage entity inside an extern "C" linkage
  1668. // specification. Make a note of that so we can give it the "expected"
  1669. // mangled name if nothing else is using that name.
  1670. std::pair<StaticExternCMap::iterator, bool> R =
  1671. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  1672. // If we have multiple internal linkage entities with the same name
  1673. // in extern "C" regions, none of them gets that name.
  1674. if (!R.second)
  1675. R.first->second = nullptr;
  1676. }
  1677. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  1678. if (!CGM.supportsCOMDAT())
  1679. return false;
  1680. if (D.hasAttr<SelectAnyAttr>())
  1681. return true;
  1682. GVALinkage Linkage;
  1683. if (auto *VD = dyn_cast<VarDecl>(&D))
  1684. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  1685. else
  1686. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  1687. switch (Linkage) {
  1688. case GVA_Internal:
  1689. case GVA_AvailableExternally:
  1690. case GVA_StrongExternal:
  1691. return false;
  1692. case GVA_DiscardableODR:
  1693. case GVA_StrongODR:
  1694. return true;
  1695. }
  1696. llvm_unreachable("No such linkage");
  1697. }
  1698. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  1699. llvm::GlobalObject &GO) {
  1700. if (!shouldBeInCOMDAT(*this, D))
  1701. return;
  1702. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  1703. }
  1704. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1705. llvm::Constant *Init = nullptr;
  1706. QualType ASTTy = D->getType();
  1707. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1708. bool NeedsGlobalCtor = false;
  1709. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1710. const VarDecl *InitDecl;
  1711. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1712. if (!InitExpr) {
  1713. // This is a tentative definition; tentative definitions are
  1714. // implicitly initialized with { 0 }.
  1715. //
  1716. // Note that tentative definitions are only emitted at the end of
  1717. // a translation unit, so they should never have incomplete
  1718. // type. In addition, EmitTentativeDefinition makes sure that we
  1719. // never attempt to emit a tentative definition if a real one
  1720. // exists. A use may still exists, however, so we still may need
  1721. // to do a RAUW.
  1722. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1723. Init = EmitNullConstant(D->getType());
  1724. } else {
  1725. initializedGlobalDecl = GlobalDecl(D);
  1726. Init = EmitConstantInit(*InitDecl);
  1727. if (!Init) {
  1728. QualType T = InitExpr->getType();
  1729. if (D->getType()->isReferenceType())
  1730. T = D->getType();
  1731. if (getLangOpts().CPlusPlus) {
  1732. Init = EmitNullConstant(T);
  1733. NeedsGlobalCtor = true;
  1734. } else {
  1735. ErrorUnsupported(D, "static initializer");
  1736. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1737. }
  1738. } else {
  1739. // We don't need an initializer, so remove the entry for the delayed
  1740. // initializer position (just in case this entry was delayed) if we
  1741. // also don't need to register a destructor.
  1742. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1743. DelayedCXXInitPosition.erase(D);
  1744. }
  1745. }
  1746. llvm::Type* InitType = Init->getType();
  1747. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1748. // Strip off a bitcast if we got one back.
  1749. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1750. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1751. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  1752. // All zero index gep.
  1753. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1754. Entry = CE->getOperand(0);
  1755. }
  1756. // Entry is now either a Function or GlobalVariable.
  1757. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1758. // We have a definition after a declaration with the wrong type.
  1759. // We must make a new GlobalVariable* and update everything that used OldGV
  1760. // (a declaration or tentative definition) with the new GlobalVariable*
  1761. // (which will be a definition).
  1762. //
  1763. // This happens if there is a prototype for a global (e.g.
  1764. // "extern int x[];") and then a definition of a different type (e.g.
  1765. // "int x[10];"). This also happens when an initializer has a different type
  1766. // from the type of the global (this happens with unions).
  1767. if (!GV ||
  1768. GV->getType()->getElementType() != InitType ||
  1769. GV->getType()->getAddressSpace() !=
  1770. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  1771. // Move the old entry aside so that we'll create a new one.
  1772. Entry->setName(StringRef());
  1773. // Make a new global with the correct type, this is now guaranteed to work.
  1774. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1775. // Replace all uses of the old global with the new global
  1776. llvm::Constant *NewPtrForOldDecl =
  1777. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1778. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1779. // Erase the old global, since it is no longer used.
  1780. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1781. }
  1782. MaybeHandleStaticInExternC(D, GV);
  1783. if (D->hasAttr<AnnotateAttr>())
  1784. AddGlobalAnnotations(D, GV);
  1785. GV->setInitializer(Init);
  1786. // If it is safe to mark the global 'constant', do so now.
  1787. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1788. isTypeConstant(D->getType(), true));
  1789. // If it is in a read-only section, mark it 'constant'.
  1790. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  1791. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  1792. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  1793. GV->setConstant(true);
  1794. }
  1795. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1796. // Set the llvm linkage type as appropriate.
  1797. llvm::GlobalValue::LinkageTypes Linkage =
  1798. getLLVMLinkageVarDefinition(D, GV->isConstant());
  1799. // On Darwin, the backing variable for a C++11 thread_local variable always
  1800. // has internal linkage; all accesses should just be calls to the
  1801. // Itanium-specified entry point, which has the normal linkage of the
  1802. // variable.
  1803. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  1804. Context.getTargetInfo().getTriple().isMacOSX())
  1805. Linkage = llvm::GlobalValue::InternalLinkage;
  1806. GV->setLinkage(Linkage);
  1807. if (D->hasAttr<DLLImportAttr>())
  1808. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  1809. else if (D->hasAttr<DLLExportAttr>())
  1810. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  1811. else
  1812. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  1813. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1814. // common vars aren't constant even if declared const.
  1815. GV->setConstant(false);
  1816. setNonAliasAttributes(D, GV);
  1817. if (D->getTLSKind() && !GV->isThreadLocal()) {
  1818. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1819. CXXThreadLocals.push_back(std::make_pair(D, GV));
  1820. setTLSMode(GV, *D);
  1821. }
  1822. maybeSetTrivialComdat(*D, *GV);
  1823. // Emit the initializer function if necessary.
  1824. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1825. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1826. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  1827. // Emit global variable debug information.
  1828. if (CGDebugInfo *DI = getModuleDebugInfo())
  1829. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1830. DI->EmitGlobalVariable(GV, D);
  1831. }
  1832. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  1833. CodeGenModule &CGM, const VarDecl *D,
  1834. bool NoCommon) {
  1835. // Don't give variables common linkage if -fno-common was specified unless it
  1836. // was overridden by a NoCommon attribute.
  1837. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  1838. return true;
  1839. // C11 6.9.2/2:
  1840. // A declaration of an identifier for an object that has file scope without
  1841. // an initializer, and without a storage-class specifier or with the
  1842. // storage-class specifier static, constitutes a tentative definition.
  1843. if (D->getInit() || D->hasExternalStorage())
  1844. return true;
  1845. // A variable cannot be both common and exist in a section.
  1846. if (D->hasAttr<SectionAttr>())
  1847. return true;
  1848. // Thread local vars aren't considered common linkage.
  1849. if (D->getTLSKind())
  1850. return true;
  1851. // Tentative definitions marked with WeakImportAttr are true definitions.
  1852. if (D->hasAttr<WeakImportAttr>())
  1853. return true;
  1854. // A variable cannot be both common and exist in a comdat.
  1855. if (shouldBeInCOMDAT(CGM, *D))
  1856. return true;
  1857. // Declarations with a required alignment do not have common linakge in MSVC
  1858. // mode.
  1859. if (Context.getLangOpts().MSVCCompat) {
  1860. if (D->hasAttr<AlignedAttr>())
  1861. return true;
  1862. QualType VarType = D->getType();
  1863. if (Context.isAlignmentRequired(VarType))
  1864. return true;
  1865. if (const auto *RT = VarType->getAs<RecordType>()) {
  1866. const RecordDecl *RD = RT->getDecl();
  1867. for (const FieldDecl *FD : RD->fields()) {
  1868. if (FD->isBitField())
  1869. continue;
  1870. if (FD->hasAttr<AlignedAttr>())
  1871. return true;
  1872. if (Context.isAlignmentRequired(FD->getType()))
  1873. return true;
  1874. }
  1875. }
  1876. }
  1877. return false;
  1878. }
  1879. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  1880. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  1881. if (Linkage == GVA_Internal)
  1882. return llvm::Function::InternalLinkage;
  1883. if (D->hasAttr<WeakAttr>()) {
  1884. if (IsConstantVariable)
  1885. return llvm::GlobalVariable::WeakODRLinkage;
  1886. else
  1887. return llvm::GlobalVariable::WeakAnyLinkage;
  1888. }
  1889. // We are guaranteed to have a strong definition somewhere else,
  1890. // so we can use available_externally linkage.
  1891. if (Linkage == GVA_AvailableExternally)
  1892. return llvm::Function::AvailableExternallyLinkage;
  1893. // Note that Apple's kernel linker doesn't support symbol
  1894. // coalescing, so we need to avoid linkonce and weak linkages there.
  1895. // Normally, this means we just map to internal, but for explicit
  1896. // instantiations we'll map to external.
  1897. // In C++, the compiler has to emit a definition in every translation unit
  1898. // that references the function. We should use linkonce_odr because
  1899. // a) if all references in this translation unit are optimized away, we
  1900. // don't need to codegen it. b) if the function persists, it needs to be
  1901. // merged with other definitions. c) C++ has the ODR, so we know the
  1902. // definition is dependable.
  1903. if (Linkage == GVA_DiscardableODR)
  1904. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  1905. : llvm::Function::InternalLinkage;
  1906. // An explicit instantiation of a template has weak linkage, since
  1907. // explicit instantiations can occur in multiple translation units
  1908. // and must all be equivalent. However, we are not allowed to
  1909. // throw away these explicit instantiations.
  1910. if (Linkage == GVA_StrongODR)
  1911. return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
  1912. : llvm::Function::ExternalLinkage;
  1913. // C++ doesn't have tentative definitions and thus cannot have common
  1914. // linkage.
  1915. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  1916. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  1917. CodeGenOpts.NoCommon))
  1918. return llvm::GlobalVariable::CommonLinkage;
  1919. // selectany symbols are externally visible, so use weak instead of
  1920. // linkonce. MSVC optimizes away references to const selectany globals, so
  1921. // all definitions should be the same and ODR linkage should be used.
  1922. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  1923. if (D->hasAttr<SelectAnyAttr>())
  1924. return llvm::GlobalVariable::WeakODRLinkage;
  1925. // Otherwise, we have strong external linkage.
  1926. assert(Linkage == GVA_StrongExternal);
  1927. return llvm::GlobalVariable::ExternalLinkage;
  1928. }
  1929. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  1930. const VarDecl *VD, bool IsConstant) {
  1931. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  1932. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  1933. }
  1934. /// Replace the uses of a function that was declared with a non-proto type.
  1935. /// We want to silently drop extra arguments from call sites
  1936. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  1937. llvm::Function *newFn) {
  1938. // Fast path.
  1939. if (old->use_empty()) return;
  1940. llvm::Type *newRetTy = newFn->getReturnType();
  1941. SmallVector<llvm::Value*, 4> newArgs;
  1942. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  1943. ui != ue; ) {
  1944. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  1945. llvm::User *user = use->getUser();
  1946. // Recognize and replace uses of bitcasts. Most calls to
  1947. // unprototyped functions will use bitcasts.
  1948. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  1949. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  1950. replaceUsesOfNonProtoConstant(bitcast, newFn);
  1951. continue;
  1952. }
  1953. // Recognize calls to the function.
  1954. llvm::CallSite callSite(user);
  1955. if (!callSite) continue;
  1956. if (!callSite.isCallee(&*use)) continue;
  1957. // If the return types don't match exactly, then we can't
  1958. // transform this call unless it's dead.
  1959. if (callSite->getType() != newRetTy && !callSite->use_empty())
  1960. continue;
  1961. // Get the call site's attribute list.
  1962. SmallVector<llvm::AttributeSet, 8> newAttrs;
  1963. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  1964. // Collect any return attributes from the call.
  1965. if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
  1966. newAttrs.push_back(
  1967. llvm::AttributeSet::get(newFn->getContext(),
  1968. oldAttrs.getRetAttributes()));
  1969. // If the function was passed too few arguments, don't transform.
  1970. unsigned newNumArgs = newFn->arg_size();
  1971. if (callSite.arg_size() < newNumArgs) continue;
  1972. // If extra arguments were passed, we silently drop them.
  1973. // If any of the types mismatch, we don't transform.
  1974. unsigned argNo = 0;
  1975. bool dontTransform = false;
  1976. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  1977. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  1978. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  1979. dontTransform = true;
  1980. break;
  1981. }
  1982. // Add any parameter attributes.
  1983. if (oldAttrs.hasAttributes(argNo + 1))
  1984. newAttrs.
  1985. push_back(llvm::
  1986. AttributeSet::get(newFn->getContext(),
  1987. oldAttrs.getParamAttributes(argNo + 1)));
  1988. }
  1989. if (dontTransform)
  1990. continue;
  1991. if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
  1992. newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
  1993. oldAttrs.getFnAttributes()));
  1994. // Okay, we can transform this. Create the new call instruction and copy
  1995. // over the required information.
  1996. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  1997. llvm::CallSite newCall;
  1998. if (callSite.isCall()) {
  1999. newCall = llvm::CallInst::Create(newFn, newArgs, "",
  2000. callSite.getInstruction());
  2001. } else {
  2002. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  2003. newCall = llvm::InvokeInst::Create(newFn,
  2004. oldInvoke->getNormalDest(),
  2005. oldInvoke->getUnwindDest(),
  2006. newArgs, "",
  2007. callSite.getInstruction());
  2008. }
  2009. newArgs.clear(); // for the next iteration
  2010. if (!newCall->getType()->isVoidTy())
  2011. newCall->takeName(callSite.getInstruction());
  2012. newCall.setAttributes(
  2013. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  2014. newCall.setCallingConv(callSite.getCallingConv());
  2015. // Finally, remove the old call, replacing any uses with the new one.
  2016. if (!callSite->use_empty())
  2017. callSite->replaceAllUsesWith(newCall.getInstruction());
  2018. // Copy debug location attached to CI.
  2019. if (callSite->getDebugLoc())
  2020. newCall->setDebugLoc(callSite->getDebugLoc());
  2021. callSite->eraseFromParent();
  2022. }
  2023. }
  2024. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  2025. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  2026. /// existing call uses of the old function in the module, this adjusts them to
  2027. /// call the new function directly.
  2028. ///
  2029. /// This is not just a cleanup: the always_inline pass requires direct calls to
  2030. /// functions to be able to inline them. If there is a bitcast in the way, it
  2031. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  2032. /// run at -O0.
  2033. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2034. llvm::Function *NewFn) {
  2035. // If we're redefining a global as a function, don't transform it.
  2036. if (!isa<llvm::Function>(Old)) return;
  2037. replaceUsesOfNonProtoConstant(Old, NewFn);
  2038. }
  2039. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  2040. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  2041. // If we have a definition, this might be a deferred decl. If the
  2042. // instantiation is explicit, make sure we emit it at the end.
  2043. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  2044. GetAddrOfGlobalVar(VD);
  2045. EmitTopLevelDecl(VD);
  2046. }
  2047. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  2048. llvm::GlobalValue *GV) {
  2049. const auto *D = cast<FunctionDecl>(GD.getDecl());
  2050. // Compute the function info and LLVM type.
  2051. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2052. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2053. // Get or create the prototype for the function.
  2054. if (!GV) {
  2055. llvm::Constant *C =
  2056. GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
  2057. // Strip off a bitcast if we got one back.
  2058. if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
  2059. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  2060. GV = cast<llvm::GlobalValue>(CE->getOperand(0));
  2061. } else {
  2062. GV = cast<llvm::GlobalValue>(C);
  2063. }
  2064. }
  2065. if (!GV->isDeclaration()) {
  2066. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
  2067. GlobalDecl OldGD = Manglings.lookup(GV->getName());
  2068. if (auto *Prev = OldGD.getDecl())
  2069. getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
  2070. return;
  2071. }
  2072. if (GV->getType()->getElementType() != Ty) {
  2073. // If the types mismatch then we have to rewrite the definition.
  2074. assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
  2075. // F is the Function* for the one with the wrong type, we must make a new
  2076. // Function* and update everything that used F (a declaration) with the new
  2077. // Function* (which will be a definition).
  2078. //
  2079. // This happens if there is a prototype for a function
  2080. // (e.g. "int f()") and then a definition of a different type
  2081. // (e.g. "int f(int x)"). Move the old function aside so that it
  2082. // doesn't interfere with GetAddrOfFunction.
  2083. GV->setName(StringRef());
  2084. auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  2085. // This might be an implementation of a function without a
  2086. // prototype, in which case, try to do special replacement of
  2087. // calls which match the new prototype. The really key thing here
  2088. // is that we also potentially drop arguments from the call site
  2089. // so as to make a direct call, which makes the inliner happier
  2090. // and suppresses a number of optimizer warnings (!) about
  2091. // dropping arguments.
  2092. if (!GV->use_empty()) {
  2093. ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
  2094. GV->removeDeadConstantUsers();
  2095. }
  2096. // Replace uses of F with the Function we will endow with a body.
  2097. if (!GV->use_empty()) {
  2098. llvm::Constant *NewPtrForOldDecl =
  2099. llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
  2100. GV->replaceAllUsesWith(NewPtrForOldDecl);
  2101. }
  2102. // Ok, delete the old function now, which is dead.
  2103. GV->eraseFromParent();
  2104. GV = NewFn;
  2105. }
  2106. // We need to set linkage and visibility on the function before
  2107. // generating code for it because various parts of IR generation
  2108. // want to propagate this information down (e.g. to local static
  2109. // declarations).
  2110. auto *Fn = cast<llvm::Function>(GV);
  2111. setFunctionLinkage(GD, Fn);
  2112. if (D->hasAttr<DLLImportAttr>())
  2113. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  2114. else if (D->hasAttr<DLLExportAttr>())
  2115. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  2116. else
  2117. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  2118. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  2119. setGlobalVisibility(Fn, D);
  2120. MaybeHandleStaticInExternC(D, Fn);
  2121. maybeSetTrivialComdat(*D, *Fn);
  2122. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  2123. setFunctionDefinitionAttributes(D, Fn);
  2124. SetLLVMFunctionAttributesForDefinition(D, Fn);
  2125. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  2126. AddGlobalCtor(Fn, CA->getPriority());
  2127. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  2128. AddGlobalDtor(Fn, DA->getPriority());
  2129. if (D->hasAttr<AnnotateAttr>())
  2130. AddGlobalAnnotations(D, Fn);
  2131. }
  2132. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  2133. const auto *D = cast<ValueDecl>(GD.getDecl());
  2134. const AliasAttr *AA = D->getAttr<AliasAttr>();
  2135. assert(AA && "Not an alias?");
  2136. StringRef MangledName = getMangledName(GD);
  2137. // If there is a definition in the module, then it wins over the alias.
  2138. // This is dubious, but allow it to be safe. Just ignore the alias.
  2139. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2140. if (Entry && !Entry->isDeclaration())
  2141. return;
  2142. Aliases.push_back(GD);
  2143. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2144. // Create a reference to the named value. This ensures that it is emitted
  2145. // if a deferred decl.
  2146. llvm::Constant *Aliasee;
  2147. if (isa<llvm::FunctionType>(DeclTy))
  2148. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  2149. /*ForVTable=*/false);
  2150. else
  2151. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  2152. llvm::PointerType::getUnqual(DeclTy),
  2153. /*D=*/nullptr);
  2154. // Create the new alias itself, but don't set a name yet.
  2155. auto *GA = llvm::GlobalAlias::create(
  2156. cast<llvm::PointerType>(Aliasee->getType()),
  2157. llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  2158. if (Entry) {
  2159. if (GA->getAliasee() == Entry) {
  2160. Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
  2161. return;
  2162. }
  2163. assert(Entry->isDeclaration());
  2164. // If there is a declaration in the module, then we had an extern followed
  2165. // by the alias, as in:
  2166. // extern int test6();
  2167. // ...
  2168. // int test6() __attribute__((alias("test7")));
  2169. //
  2170. // Remove it and replace uses of it with the alias.
  2171. GA->takeName(Entry);
  2172. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  2173. Entry->getType()));
  2174. Entry->eraseFromParent();
  2175. } else {
  2176. GA->setName(MangledName);
  2177. }
  2178. // Set attributes which are particular to an alias; this is a
  2179. // specialization of the attributes which may be set on a global
  2180. // variable/function.
  2181. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  2182. D->isWeakImported()) {
  2183. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  2184. }
  2185. if (const auto *VD = dyn_cast<VarDecl>(D))
  2186. if (VD->getTLSKind())
  2187. setTLSMode(GA, *VD);
  2188. setAliasAttributes(D, GA);
  2189. }
  2190. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  2191. ArrayRef<llvm::Type*> Tys) {
  2192. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  2193. Tys);
  2194. }
  2195. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2196. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2197. const StringLiteral *Literal, bool TargetIsLSB,
  2198. bool &IsUTF16, unsigned &StringLength) {
  2199. StringRef String = Literal->getString();
  2200. unsigned NumBytes = String.size();
  2201. // Check for simple case.
  2202. if (!Literal->containsNonAsciiOrNull()) {
  2203. StringLength = NumBytes;
  2204. return *Map.insert(std::make_pair(String, nullptr)).first;
  2205. }
  2206. // Otherwise, convert the UTF8 literals into a string of shorts.
  2207. IsUTF16 = true;
  2208. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  2209. const UTF8 *FromPtr = (const UTF8 *)String.data();
  2210. UTF16 *ToPtr = &ToBuf[0];
  2211. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  2212. &ToPtr, ToPtr + NumBytes,
  2213. strictConversion);
  2214. // ConvertUTF8toUTF16 returns the length in ToPtr.
  2215. StringLength = ToPtr - &ToBuf[0];
  2216. // Add an explicit null.
  2217. *ToPtr = 0;
  2218. return *Map.insert(std::make_pair(
  2219. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  2220. (StringLength + 1) * 2),
  2221. nullptr)).first;
  2222. }
  2223. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2224. GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2225. const StringLiteral *Literal, unsigned &StringLength) {
  2226. StringRef String = Literal->getString();
  2227. StringLength = String.size();
  2228. return *Map.insert(std::make_pair(String, nullptr)).first;
  2229. }
  2230. llvm::Constant *
  2231. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  2232. unsigned StringLength = 0;
  2233. bool isUTF16 = false;
  2234. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2235. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  2236. getDataLayout().isLittleEndian(), isUTF16,
  2237. StringLength);
  2238. if (auto *C = Entry.second)
  2239. return C;
  2240. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2241. llvm::Constant *Zeros[] = { Zero, Zero };
  2242. llvm::Value *V;
  2243. // If we don't already have it, get __CFConstantStringClassReference.
  2244. if (!CFConstantStringClassRef) {
  2245. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2246. Ty = llvm::ArrayType::get(Ty, 0);
  2247. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  2248. "__CFConstantStringClassReference");
  2249. // Decay array -> ptr
  2250. V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  2251. CFConstantStringClassRef = V;
  2252. }
  2253. else
  2254. V = CFConstantStringClassRef;
  2255. QualType CFTy = getContext().getCFConstantStringType();
  2256. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  2257. llvm::Constant *Fields[4];
  2258. // Class pointer.
  2259. Fields[0] = cast<llvm::ConstantExpr>(V);
  2260. // Flags.
  2261. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2262. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  2263. llvm::ConstantInt::get(Ty, 0x07C8);
  2264. // String pointer.
  2265. llvm::Constant *C = nullptr;
  2266. if (isUTF16) {
  2267. ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
  2268. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  2269. Entry.first().size() / 2);
  2270. C = llvm::ConstantDataArray::get(VMContext, Arr);
  2271. } else {
  2272. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2273. }
  2274. // Note: -fwritable-strings doesn't make the backing store strings of
  2275. // CFStrings writable. (See <rdar://problem/10657500>)
  2276. auto *GV =
  2277. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  2278. llvm::GlobalValue::PrivateLinkage, C, ".str");
  2279. GV->setUnnamedAddr(true);
  2280. // Don't enforce the target's minimum global alignment, since the only use
  2281. // of the string is via this class initializer.
  2282. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
  2283. // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
  2284. // that changes the section it ends in, which surprises ld64.
  2285. if (isUTF16) {
  2286. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  2287. GV->setAlignment(Align.getQuantity());
  2288. GV->setSection("__TEXT,__ustring");
  2289. } else {
  2290. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2291. GV->setAlignment(Align.getQuantity());
  2292. GV->setSection("__TEXT,__cstring,cstring_literals");
  2293. }
  2294. // String.
  2295. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV->getType(), GV, Zeros);
  2296. if (isUTF16)
  2297. // Cast the UTF16 string to the correct type.
  2298. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  2299. // String length.
  2300. Ty = getTypes().ConvertType(getContext().LongTy);
  2301. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  2302. // The struct.
  2303. C = llvm::ConstantStruct::get(STy, Fields);
  2304. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2305. llvm::GlobalVariable::PrivateLinkage, C,
  2306. "_unnamed_cfstring_");
  2307. GV->setSection("__DATA,__cfstring");
  2308. Entry.second = GV;
  2309. return GV;
  2310. }
  2311. llvm::GlobalVariable *
  2312. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  2313. unsigned StringLength = 0;
  2314. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2315. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  2316. if (auto *C = Entry.second)
  2317. return C;
  2318. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2319. llvm::Constant *Zeros[] = { Zero, Zero };
  2320. llvm::Value *V;
  2321. // If we don't already have it, get _NSConstantStringClassReference.
  2322. if (!ConstantStringClassRef) {
  2323. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  2324. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2325. llvm::Constant *GV;
  2326. if (LangOpts.ObjCRuntime.isNonFragile()) {
  2327. std::string str =
  2328. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  2329. : "OBJC_CLASS_$_" + StringClass;
  2330. GV = getObjCRuntime().GetClassGlobal(str);
  2331. // Make sure the result is of the correct type.
  2332. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2333. V = llvm::ConstantExpr::getBitCast(GV, PTy);
  2334. ConstantStringClassRef = V;
  2335. } else {
  2336. std::string str =
  2337. StringClass.empty() ? "_NSConstantStringClassReference"
  2338. : "_" + StringClass + "ClassReference";
  2339. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  2340. GV = CreateRuntimeVariable(PTy, str);
  2341. // Decay array -> ptr
  2342. V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
  2343. ConstantStringClassRef = V;
  2344. }
  2345. } else
  2346. V = ConstantStringClassRef;
  2347. if (!NSConstantStringType) {
  2348. // Construct the type for a constant NSString.
  2349. RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
  2350. D->startDefinition();
  2351. QualType FieldTypes[3];
  2352. // const int *isa;
  2353. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  2354. // const char *str;
  2355. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  2356. // unsigned int length;
  2357. FieldTypes[2] = Context.UnsignedIntTy;
  2358. // Create fields
  2359. for (unsigned i = 0; i < 3; ++i) {
  2360. FieldDecl *Field = FieldDecl::Create(Context, D,
  2361. SourceLocation(),
  2362. SourceLocation(), nullptr,
  2363. FieldTypes[i], /*TInfo=*/nullptr,
  2364. /*BitWidth=*/nullptr,
  2365. /*Mutable=*/false,
  2366. ICIS_NoInit);
  2367. Field->setAccess(AS_public);
  2368. D->addDecl(Field);
  2369. }
  2370. D->completeDefinition();
  2371. QualType NSTy = Context.getTagDeclType(D);
  2372. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  2373. }
  2374. llvm::Constant *Fields[3];
  2375. // Class pointer.
  2376. Fields[0] = cast<llvm::ConstantExpr>(V);
  2377. // String pointer.
  2378. llvm::Constant *C =
  2379. llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2380. llvm::GlobalValue::LinkageTypes Linkage;
  2381. bool isConstant;
  2382. Linkage = llvm::GlobalValue::PrivateLinkage;
  2383. isConstant = !LangOpts.WritableStrings;
  2384. auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
  2385. Linkage, C, ".str");
  2386. GV->setUnnamedAddr(true);
  2387. // Don't enforce the target's minimum global alignment, since the only use
  2388. // of the string is via this class initializer.
  2389. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2390. GV->setAlignment(Align.getQuantity());
  2391. Fields[1] =
  2392. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  2393. // String length.
  2394. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2395. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  2396. // The struct.
  2397. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  2398. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2399. llvm::GlobalVariable::PrivateLinkage, C,
  2400. "_unnamed_nsstring_");
  2401. const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
  2402. const char *NSStringNonFragileABISection =
  2403. "__DATA,__objc_stringobj,regular,no_dead_strip";
  2404. // FIXME. Fix section.
  2405. GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
  2406. ? NSStringNonFragileABISection
  2407. : NSStringSection);
  2408. Entry.second = GV;
  2409. return GV;
  2410. }
  2411. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2412. if (ObjCFastEnumerationStateType.isNull()) {
  2413. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  2414. D->startDefinition();
  2415. QualType FieldTypes[] = {
  2416. Context.UnsignedLongTy,
  2417. Context.getPointerType(Context.getObjCIdType()),
  2418. Context.getPointerType(Context.UnsignedLongTy),
  2419. Context.getConstantArrayType(Context.UnsignedLongTy,
  2420. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2421. };
  2422. for (size_t i = 0; i < 4; ++i) {
  2423. FieldDecl *Field = FieldDecl::Create(Context,
  2424. D,
  2425. SourceLocation(),
  2426. SourceLocation(), nullptr,
  2427. FieldTypes[i], /*TInfo=*/nullptr,
  2428. /*BitWidth=*/nullptr,
  2429. /*Mutable=*/false,
  2430. ICIS_NoInit);
  2431. Field->setAccess(AS_public);
  2432. D->addDecl(Field);
  2433. }
  2434. D->completeDefinition();
  2435. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2436. }
  2437. return ObjCFastEnumerationStateType;
  2438. }
  2439. llvm::Constant *
  2440. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2441. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2442. // Don't emit it as the address of the string, emit the string data itself
  2443. // as an inline array.
  2444. if (E->getCharByteWidth() == 1) {
  2445. SmallString<64> Str(E->getString());
  2446. // Resize the string to the right size, which is indicated by its type.
  2447. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2448. Str.resize(CAT->getSize().getZExtValue());
  2449. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2450. }
  2451. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2452. llvm::Type *ElemTy = AType->getElementType();
  2453. unsigned NumElements = AType->getNumElements();
  2454. // Wide strings have either 2-byte or 4-byte elements.
  2455. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2456. SmallVector<uint16_t, 32> Elements;
  2457. Elements.reserve(NumElements);
  2458. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2459. Elements.push_back(E->getCodeUnit(i));
  2460. Elements.resize(NumElements);
  2461. return llvm::ConstantDataArray::get(VMContext, Elements);
  2462. }
  2463. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2464. SmallVector<uint32_t, 32> Elements;
  2465. Elements.reserve(NumElements);
  2466. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2467. Elements.push_back(E->getCodeUnit(i));
  2468. Elements.resize(NumElements);
  2469. return llvm::ConstantDataArray::get(VMContext, Elements);
  2470. }
  2471. static llvm::GlobalVariable *
  2472. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  2473. CodeGenModule &CGM, StringRef GlobalName,
  2474. unsigned Alignment) {
  2475. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  2476. unsigned AddrSpace = 0;
  2477. if (CGM.getLangOpts().OpenCL)
  2478. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  2479. llvm::Module &M = CGM.getModule();
  2480. // Create a global variable for this string
  2481. auto *GV = new llvm::GlobalVariable(
  2482. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  2483. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  2484. GV->setAlignment(Alignment);
  2485. GV->setUnnamedAddr(true);
  2486. if (GV->isWeakForLinker()) {
  2487. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  2488. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  2489. }
  2490. return GV;
  2491. }
  2492. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2493. /// constant array for the given string literal.
  2494. llvm::GlobalVariable *
  2495. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  2496. StringRef Name) {
  2497. auto Alignment =
  2498. getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
  2499. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2500. llvm::GlobalVariable **Entry = nullptr;
  2501. if (!LangOpts.WritableStrings) {
  2502. Entry = &ConstantStringMap[C];
  2503. if (auto GV = *Entry) {
  2504. if (Alignment > GV->getAlignment())
  2505. GV->setAlignment(Alignment);
  2506. return GV;
  2507. }
  2508. }
  2509. SmallString<256> MangledNameBuffer;
  2510. StringRef GlobalVariableName;
  2511. llvm::GlobalValue::LinkageTypes LT;
  2512. // Mangle the string literal if the ABI allows for it. However, we cannot
  2513. // do this if we are compiling with ASan or -fwritable-strings because they
  2514. // rely on strings having normal linkage.
  2515. if (!LangOpts.WritableStrings &&
  2516. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  2517. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  2518. llvm::raw_svector_ostream Out(MangledNameBuffer);
  2519. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  2520. Out.flush();
  2521. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  2522. GlobalVariableName = MangledNameBuffer;
  2523. } else {
  2524. LT = llvm::GlobalValue::PrivateLinkage;
  2525. GlobalVariableName = Name;
  2526. }
  2527. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  2528. if (Entry)
  2529. *Entry = GV;
  2530. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  2531. QualType());
  2532. return GV;
  2533. }
  2534. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2535. /// array for the given ObjCEncodeExpr node.
  2536. llvm::GlobalVariable *
  2537. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2538. std::string Str;
  2539. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2540. return GetAddrOfConstantCString(Str);
  2541. }
  2542. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  2543. /// the literal and a terminating '\0' character.
  2544. /// The result has pointer to array type.
  2545. llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
  2546. const std::string &Str, const char *GlobalName, unsigned Alignment) {
  2547. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2548. if (Alignment == 0) {
  2549. Alignment = getContext()
  2550. .getAlignOfGlobalVarInChars(getContext().CharTy)
  2551. .getQuantity();
  2552. }
  2553. llvm::Constant *C =
  2554. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  2555. // Don't share any string literals if strings aren't constant.
  2556. llvm::GlobalVariable **Entry = nullptr;
  2557. if (!LangOpts.WritableStrings) {
  2558. Entry = &ConstantStringMap[C];
  2559. if (auto GV = *Entry) {
  2560. if (Alignment > GV->getAlignment())
  2561. GV->setAlignment(Alignment);
  2562. return GV;
  2563. }
  2564. }
  2565. // Get the default prefix if a name wasn't specified.
  2566. if (!GlobalName)
  2567. GlobalName = ".str";
  2568. // Create a global variable for this.
  2569. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  2570. GlobalName, Alignment);
  2571. if (Entry)
  2572. *Entry = GV;
  2573. return GV;
  2574. }
  2575. llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
  2576. const MaterializeTemporaryExpr *E, const Expr *Init) {
  2577. assert((E->getStorageDuration() == SD_Static ||
  2578. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  2579. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  2580. // If we're not materializing a subobject of the temporary, keep the
  2581. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  2582. QualType MaterializedType = Init->getType();
  2583. if (Init == E->GetTemporaryExpr())
  2584. MaterializedType = E->getType();
  2585. llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
  2586. if (Slot)
  2587. return Slot;
  2588. // FIXME: If an externally-visible declaration extends multiple temporaries,
  2589. // we need to give each temporary the same name in every translation unit (and
  2590. // we also need to make the temporaries externally-visible).
  2591. SmallString<256> Name;
  2592. llvm::raw_svector_ostream Out(Name);
  2593. getCXXABI().getMangleContext().mangleReferenceTemporary(
  2594. VD, E->getManglingNumber(), Out);
  2595. Out.flush();
  2596. APValue *Value = nullptr;
  2597. if (E->getStorageDuration() == SD_Static) {
  2598. // We might have a cached constant initializer for this temporary. Note
  2599. // that this might have a different value from the value computed by
  2600. // evaluating the initializer if the surrounding constant expression
  2601. // modifies the temporary.
  2602. Value = getContext().getMaterializedTemporaryValue(E, false);
  2603. if (Value && Value->isUninit())
  2604. Value = nullptr;
  2605. }
  2606. // Try evaluating it now, it might have a constant initializer.
  2607. Expr::EvalResult EvalResult;
  2608. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  2609. !EvalResult.hasSideEffects())
  2610. Value = &EvalResult.Val;
  2611. llvm::Constant *InitialValue = nullptr;
  2612. bool Constant = false;
  2613. llvm::Type *Type;
  2614. if (Value) {
  2615. // The temporary has a constant initializer, use it.
  2616. InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
  2617. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  2618. Type = InitialValue->getType();
  2619. } else {
  2620. // No initializer, the initialization will be provided when we
  2621. // initialize the declaration which performed lifetime extension.
  2622. Type = getTypes().ConvertTypeForMem(MaterializedType);
  2623. }
  2624. // Create a global variable for this lifetime-extended temporary.
  2625. llvm::GlobalValue::LinkageTypes Linkage =
  2626. getLLVMLinkageVarDefinition(VD, Constant);
  2627. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  2628. const VarDecl *InitVD;
  2629. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  2630. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  2631. // Temporaries defined inside a class get linkonce_odr linkage because the
  2632. // class can be defined in multipe translation units.
  2633. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  2634. } else {
  2635. // There is no need for this temporary to have external linkage if the
  2636. // VarDecl has external linkage.
  2637. Linkage = llvm::GlobalVariable::InternalLinkage;
  2638. }
  2639. }
  2640. unsigned AddrSpace = GetGlobalVarAddressSpace(
  2641. VD, getContext().getTargetAddressSpace(MaterializedType));
  2642. auto *GV = new llvm::GlobalVariable(
  2643. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  2644. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
  2645. AddrSpace);
  2646. setGlobalVisibility(GV, VD);
  2647. GV->setAlignment(
  2648. getContext().getTypeAlignInChars(MaterializedType).getQuantity());
  2649. if (supportsCOMDAT() && GV->isWeakForLinker())
  2650. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2651. if (VD->getTLSKind())
  2652. setTLSMode(GV, *VD);
  2653. Slot = GV;
  2654. return GV;
  2655. }
  2656. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2657. /// properties for an implementation.
  2658. void CodeGenModule::EmitObjCPropertyImplementations(const
  2659. ObjCImplementationDecl *D) {
  2660. for (const auto *PID : D->property_impls()) {
  2661. // Dynamic is just for type-checking.
  2662. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2663. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2664. // Determine which methods need to be implemented, some may have
  2665. // been overridden. Note that ::isPropertyAccessor is not the method
  2666. // we want, that just indicates if the decl came from a
  2667. // property. What we want to know is if the method is defined in
  2668. // this implementation.
  2669. if (!D->getInstanceMethod(PD->getGetterName()))
  2670. CodeGenFunction(*this).GenerateObjCGetter(
  2671. const_cast<ObjCImplementationDecl *>(D), PID);
  2672. if (!PD->isReadOnly() &&
  2673. !D->getInstanceMethod(PD->getSetterName()))
  2674. CodeGenFunction(*this).GenerateObjCSetter(
  2675. const_cast<ObjCImplementationDecl *>(D), PID);
  2676. }
  2677. }
  2678. }
  2679. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2680. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2681. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2682. ivar; ivar = ivar->getNextIvar())
  2683. if (ivar->getType().isDestructedType())
  2684. return true;
  2685. return false;
  2686. }
  2687. static bool AllTrivialInitializers(CodeGenModule &CGM,
  2688. ObjCImplementationDecl *D) {
  2689. CodeGenFunction CGF(CGM);
  2690. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  2691. E = D->init_end(); B != E; ++B) {
  2692. CXXCtorInitializer *CtorInitExp = *B;
  2693. Expr *Init = CtorInitExp->getInit();
  2694. if (!CGF.isTrivialInitializer(Init))
  2695. return false;
  2696. }
  2697. return true;
  2698. }
  2699. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2700. /// for an implementation.
  2701. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2702. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2703. if (needsDestructMethod(D)) {
  2704. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2705. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2706. ObjCMethodDecl *DTORMethod =
  2707. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2708. cxxSelector, getContext().VoidTy, nullptr, D,
  2709. /*isInstance=*/true, /*isVariadic=*/false,
  2710. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  2711. /*isDefined=*/false, ObjCMethodDecl::Required);
  2712. D->addInstanceMethod(DTORMethod);
  2713. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2714. D->setHasDestructors(true);
  2715. }
  2716. // If the implementation doesn't have any ivar initializers, we don't need
  2717. // a .cxx_construct.
  2718. if (D->getNumIvarInitializers() == 0 ||
  2719. AllTrivialInitializers(*this, D))
  2720. return;
  2721. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2722. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2723. // The constructor returns 'self'.
  2724. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2725. D->getLocation(),
  2726. D->getLocation(),
  2727. cxxSelector,
  2728. getContext().getObjCIdType(),
  2729. nullptr, D, /*isInstance=*/true,
  2730. /*isVariadic=*/false,
  2731. /*isPropertyAccessor=*/true,
  2732. /*isImplicitlyDeclared=*/true,
  2733. /*isDefined=*/false,
  2734. ObjCMethodDecl::Required);
  2735. D->addInstanceMethod(CTORMethod);
  2736. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2737. D->setHasNonZeroConstructors(true);
  2738. }
  2739. /// EmitNamespace - Emit all declarations in a namespace.
  2740. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2741. for (auto *I : ND->decls()) {
  2742. if (const auto *VD = dyn_cast<VarDecl>(I))
  2743. if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
  2744. VD->getTemplateSpecializationKind() != TSK_Undeclared)
  2745. continue;
  2746. EmitTopLevelDecl(I);
  2747. }
  2748. }
  2749. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2750. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2751. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2752. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2753. ErrorUnsupported(LSD, "linkage spec");
  2754. return;
  2755. }
  2756. for (auto *I : LSD->decls()) {
  2757. // Meta-data for ObjC class includes references to implemented methods.
  2758. // Generate class's method definitions first.
  2759. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  2760. for (auto *M : OID->methods())
  2761. EmitTopLevelDecl(M);
  2762. }
  2763. EmitTopLevelDecl(I);
  2764. }
  2765. }
  2766. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2767. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2768. // Ignore dependent declarations.
  2769. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2770. return;
  2771. switch (D->getKind()) {
  2772. case Decl::CXXConversion:
  2773. case Decl::CXXMethod:
  2774. case Decl::Function:
  2775. // Skip function templates
  2776. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2777. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2778. return;
  2779. EmitGlobal(cast<FunctionDecl>(D));
  2780. // Always provide some coverage mapping
  2781. // even for the functions that aren't emitted.
  2782. AddDeferredUnusedCoverageMapping(D);
  2783. break;
  2784. case Decl::Var:
  2785. // Skip variable templates
  2786. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  2787. return;
  2788. case Decl::VarTemplateSpecialization:
  2789. EmitGlobal(cast<VarDecl>(D));
  2790. break;
  2791. // Indirect fields from global anonymous structs and unions can be
  2792. // ignored; only the actual variable requires IR gen support.
  2793. case Decl::IndirectField:
  2794. break;
  2795. // C++ Decls
  2796. case Decl::Namespace:
  2797. EmitNamespace(cast<NamespaceDecl>(D));
  2798. break;
  2799. // No code generation needed.
  2800. case Decl::UsingShadow:
  2801. case Decl::ClassTemplate:
  2802. case Decl::VarTemplate:
  2803. case Decl::VarTemplatePartialSpecialization:
  2804. case Decl::FunctionTemplate:
  2805. case Decl::TypeAliasTemplate:
  2806. case Decl::Block:
  2807. case Decl::Empty:
  2808. break;
  2809. case Decl::Using: // using X; [C++]
  2810. if (CGDebugInfo *DI = getModuleDebugInfo())
  2811. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  2812. return;
  2813. case Decl::NamespaceAlias:
  2814. if (CGDebugInfo *DI = getModuleDebugInfo())
  2815. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  2816. return;
  2817. case Decl::UsingDirective: // using namespace X; [C++]
  2818. if (CGDebugInfo *DI = getModuleDebugInfo())
  2819. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  2820. return;
  2821. case Decl::CXXConstructor:
  2822. // Skip function templates
  2823. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2824. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2825. return;
  2826. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2827. break;
  2828. case Decl::CXXDestructor:
  2829. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2830. return;
  2831. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2832. break;
  2833. case Decl::StaticAssert:
  2834. // Nothing to do.
  2835. break;
  2836. // Objective-C Decls
  2837. // Forward declarations, no (immediate) code generation.
  2838. case Decl::ObjCInterface:
  2839. case Decl::ObjCCategory:
  2840. break;
  2841. case Decl::ObjCProtocol: {
  2842. auto *Proto = cast<ObjCProtocolDecl>(D);
  2843. if (Proto->isThisDeclarationADefinition())
  2844. ObjCRuntime->GenerateProtocol(Proto);
  2845. break;
  2846. }
  2847. case Decl::ObjCCategoryImpl:
  2848. // Categories have properties but don't support synthesize so we
  2849. // can ignore them here.
  2850. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2851. break;
  2852. case Decl::ObjCImplementation: {
  2853. auto *OMD = cast<ObjCImplementationDecl>(D);
  2854. EmitObjCPropertyImplementations(OMD);
  2855. EmitObjCIvarInitializations(OMD);
  2856. ObjCRuntime->GenerateClass(OMD);
  2857. // Emit global variable debug information.
  2858. if (CGDebugInfo *DI = getModuleDebugInfo())
  2859. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  2860. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  2861. OMD->getClassInterface()), OMD->getLocation());
  2862. break;
  2863. }
  2864. case Decl::ObjCMethod: {
  2865. auto *OMD = cast<ObjCMethodDecl>(D);
  2866. // If this is not a prototype, emit the body.
  2867. if (OMD->getBody())
  2868. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2869. break;
  2870. }
  2871. case Decl::ObjCCompatibleAlias:
  2872. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2873. break;
  2874. case Decl::LinkageSpec:
  2875. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2876. break;
  2877. case Decl::FileScopeAsm: {
  2878. // File-scope asm is ignored during device-side CUDA compilation.
  2879. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  2880. break;
  2881. auto *AD = cast<FileScopeAsmDecl>(D);
  2882. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  2883. break;
  2884. }
  2885. case Decl::Import: {
  2886. auto *Import = cast<ImportDecl>(D);
  2887. // Ignore import declarations that come from imported modules.
  2888. if (clang::Module *Owner = Import->getOwningModule()) {
  2889. if (getLangOpts().CurrentModule.empty() ||
  2890. Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
  2891. break;
  2892. }
  2893. ImportedModules.insert(Import->getImportedModule());
  2894. break;
  2895. }
  2896. case Decl::OMPThreadPrivate:
  2897. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  2898. break;
  2899. case Decl::ClassTemplateSpecialization: {
  2900. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  2901. if (DebugInfo &&
  2902. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  2903. Spec->hasDefinition())
  2904. DebugInfo->completeTemplateDefinition(*Spec);
  2905. break;
  2906. }
  2907. default:
  2908. // Make sure we handled everything we should, every other kind is a
  2909. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  2910. // function. Need to recode Decl::Kind to do that easily.
  2911. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  2912. break;
  2913. }
  2914. }
  2915. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  2916. // Do we need to generate coverage mapping?
  2917. if (!CodeGenOpts.CoverageMapping)
  2918. return;
  2919. switch (D->getKind()) {
  2920. case Decl::CXXConversion:
  2921. case Decl::CXXMethod:
  2922. case Decl::Function:
  2923. case Decl::ObjCMethod:
  2924. case Decl::CXXConstructor:
  2925. case Decl::CXXDestructor: {
  2926. if (!cast<FunctionDecl>(D)->hasBody())
  2927. return;
  2928. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  2929. if (I == DeferredEmptyCoverageMappingDecls.end())
  2930. DeferredEmptyCoverageMappingDecls[D] = true;
  2931. break;
  2932. }
  2933. default:
  2934. break;
  2935. };
  2936. }
  2937. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  2938. // Do we need to generate coverage mapping?
  2939. if (!CodeGenOpts.CoverageMapping)
  2940. return;
  2941. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  2942. if (Fn->isTemplateInstantiation())
  2943. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  2944. }
  2945. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  2946. if (I == DeferredEmptyCoverageMappingDecls.end())
  2947. DeferredEmptyCoverageMappingDecls[D] = false;
  2948. else
  2949. I->second = false;
  2950. }
  2951. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  2952. std::vector<const Decl *> DeferredDecls;
  2953. for (const auto &I : DeferredEmptyCoverageMappingDecls) {
  2954. if (!I.second)
  2955. continue;
  2956. DeferredDecls.push_back(I.first);
  2957. }
  2958. // Sort the declarations by their location to make sure that the tests get a
  2959. // predictable order for the coverage mapping for the unused declarations.
  2960. if (CodeGenOpts.DumpCoverageMapping)
  2961. std::sort(DeferredDecls.begin(), DeferredDecls.end(),
  2962. [] (const Decl *LHS, const Decl *RHS) {
  2963. return LHS->getLocStart() < RHS->getLocStart();
  2964. });
  2965. for (const auto *D : DeferredDecls) {
  2966. switch (D->getKind()) {
  2967. case Decl::CXXConversion:
  2968. case Decl::CXXMethod:
  2969. case Decl::Function:
  2970. case Decl::ObjCMethod: {
  2971. CodeGenPGO PGO(*this);
  2972. GlobalDecl GD(cast<FunctionDecl>(D));
  2973. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  2974. getFunctionLinkage(GD));
  2975. break;
  2976. }
  2977. case Decl::CXXConstructor: {
  2978. CodeGenPGO PGO(*this);
  2979. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  2980. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  2981. getFunctionLinkage(GD));
  2982. break;
  2983. }
  2984. case Decl::CXXDestructor: {
  2985. CodeGenPGO PGO(*this);
  2986. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  2987. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  2988. getFunctionLinkage(GD));
  2989. break;
  2990. }
  2991. default:
  2992. break;
  2993. };
  2994. }
  2995. }
  2996. /// Turns the given pointer into a constant.
  2997. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  2998. const void *Ptr) {
  2999. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  3000. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  3001. return llvm::ConstantInt::get(i64, PtrInt);
  3002. }
  3003. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  3004. llvm::NamedMDNode *&GlobalMetadata,
  3005. GlobalDecl D,
  3006. llvm::GlobalValue *Addr) {
  3007. if (!GlobalMetadata)
  3008. GlobalMetadata =
  3009. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  3010. // TODO: should we report variant information for ctors/dtors?
  3011. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  3012. llvm::ConstantAsMetadata::get(GetPointerConstant(
  3013. CGM.getLLVMContext(), D.getDecl()))};
  3014. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  3015. }
  3016. /// For each function which is declared within an extern "C" region and marked
  3017. /// as 'used', but has internal linkage, create an alias from the unmangled
  3018. /// name to the mangled name if possible. People expect to be able to refer
  3019. /// to such functions with an unmangled name from inline assembly within the
  3020. /// same translation unit.
  3021. void CodeGenModule::EmitStaticExternCAliases() {
  3022. for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
  3023. E = StaticExternCValues.end();
  3024. I != E; ++I) {
  3025. IdentifierInfo *Name = I->first;
  3026. llvm::GlobalValue *Val = I->second;
  3027. if (Val && !getModule().getNamedValue(Name->getName()))
  3028. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  3029. }
  3030. }
  3031. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  3032. GlobalDecl &Result) const {
  3033. auto Res = Manglings.find(MangledName);
  3034. if (Res == Manglings.end())
  3035. return false;
  3036. Result = Res->getValue();
  3037. return true;
  3038. }
  3039. /// Emits metadata nodes associating all the global values in the
  3040. /// current module with the Decls they came from. This is useful for
  3041. /// projects using IR gen as a subroutine.
  3042. ///
  3043. /// Since there's currently no way to associate an MDNode directly
  3044. /// with an llvm::GlobalValue, we create a global named metadata
  3045. /// with the name 'clang.global.decl.ptrs'.
  3046. void CodeGenModule::EmitDeclMetadata() {
  3047. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3048. // StaticLocalDeclMap
  3049. for (auto &I : MangledDeclNames) {
  3050. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  3051. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  3052. }
  3053. }
  3054. /// Emits metadata nodes for all the local variables in the current
  3055. /// function.
  3056. void CodeGenFunction::EmitDeclMetadata() {
  3057. if (LocalDeclMap.empty()) return;
  3058. llvm::LLVMContext &Context = getLLVMContext();
  3059. // Find the unique metadata ID for this name.
  3060. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  3061. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3062. for (auto &I : LocalDeclMap) {
  3063. const Decl *D = I.first;
  3064. llvm::Value *Addr = I.second;
  3065. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  3066. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  3067. Alloca->setMetadata(
  3068. DeclPtrKind, llvm::MDNode::get(
  3069. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  3070. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  3071. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  3072. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  3073. }
  3074. }
  3075. }
  3076. void CodeGenModule::EmitVersionIdentMetadata() {
  3077. llvm::NamedMDNode *IdentMetadata =
  3078. TheModule.getOrInsertNamedMetadata("llvm.ident");
  3079. std::string Version = getClangFullVersion();
  3080. llvm::LLVMContext &Ctx = TheModule.getContext();
  3081. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  3082. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  3083. }
  3084. void CodeGenModule::EmitTargetMetadata() {
  3085. // Warning, new MangledDeclNames may be appended within this loop.
  3086. // We rely on MapVector insertions adding new elements to the end
  3087. // of the container.
  3088. // FIXME: Move this loop into the one target that needs it, and only
  3089. // loop over those declarations for which we couldn't emit the target
  3090. // metadata when we emitted the declaration.
  3091. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  3092. auto Val = *(MangledDeclNames.begin() + I);
  3093. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  3094. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  3095. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  3096. }
  3097. }
  3098. void CodeGenModule::EmitCoverageFile() {
  3099. if (!getCodeGenOpts().CoverageFile.empty()) {
  3100. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  3101. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  3102. llvm::LLVMContext &Ctx = TheModule.getContext();
  3103. llvm::MDString *CoverageFile =
  3104. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  3105. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  3106. llvm::MDNode *CU = CUNode->getOperand(i);
  3107. llvm::Metadata *Elts[] = {CoverageFile, CU};
  3108. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  3109. }
  3110. }
  3111. }
  3112. }
  3113. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  3114. // Sema has checked that all uuid strings are of the form
  3115. // "12345678-1234-1234-1234-1234567890ab".
  3116. assert(Uuid.size() == 36);
  3117. for (unsigned i = 0; i < 36; ++i) {
  3118. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  3119. else assert(isHexDigit(Uuid[i]));
  3120. }
  3121. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  3122. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  3123. llvm::Constant *Field3[8];
  3124. for (unsigned Idx = 0; Idx < 8; ++Idx)
  3125. Field3[Idx] = llvm::ConstantInt::get(
  3126. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  3127. llvm::Constant *Fields[4] = {
  3128. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  3129. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  3130. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  3131. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  3132. };
  3133. return llvm::ConstantStruct::getAnon(Fields);
  3134. }
  3135. llvm::Constant *
  3136. CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty,
  3137. QualType CatchHandlerType) {
  3138. return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType);
  3139. }
  3140. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  3141. bool ForEH) {
  3142. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  3143. // FIXME: should we even be calling this method if RTTI is disabled
  3144. // and it's not for EH?
  3145. if (!ForEH && !getLangOpts().RTTI)
  3146. return llvm::Constant::getNullValue(Int8PtrTy);
  3147. if (ForEH && Ty->isObjCObjectPointerType() &&
  3148. LangOpts.ObjCRuntime.isGNUFamily())
  3149. return ObjCRuntime->GetEHType(Ty);
  3150. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  3151. }
  3152. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  3153. for (auto RefExpr : D->varlists()) {
  3154. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  3155. bool PerformInit =
  3156. VD->getAnyInitializer() &&
  3157. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  3158. /*ForRef=*/false);
  3159. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  3160. VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), PerformInit))
  3161. CXXGlobalInits.push_back(InitFunction);
  3162. }
  3163. }