CodeGenModule.cpp 132 KB

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