CodeGenModule.h 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This is the internal per-translation-unit state used for llvm translation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
  15. #include "CGVTables.h"
  16. #include "CodeGenTypeCache.h"
  17. #include "CodeGenTypes.h"
  18. #include "SanitizerMetadata.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclOpenMP.h"
  23. #include "clang/AST/GlobalDecl.h"
  24. #include "clang/AST/Mangle.h"
  25. #include "clang/Basic/ABI.h"
  26. #include "clang/Basic/LangOptions.h"
  27. #include "clang/Basic/Module.h"
  28. #include "clang/Basic/SanitizerBlacklist.h"
  29. #include "llvm/ADT/DenseMap.h"
  30. #include "llvm/ADT/SetVector.h"
  31. #include "llvm/ADT/SmallPtrSet.h"
  32. #include "llvm/ADT/StringMap.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/ValueHandle.h"
  35. #include "llvm/Transforms/Utils/SanitizerStats.h"
  36. namespace llvm {
  37. class Module;
  38. class Constant;
  39. class ConstantInt;
  40. class Function;
  41. class GlobalValue;
  42. class DataLayout;
  43. class FunctionType;
  44. class LLVMContext;
  45. class IndexedInstrProfReader;
  46. }
  47. namespace clang {
  48. class TargetCodeGenInfo;
  49. class ASTContext;
  50. class AtomicType;
  51. class FunctionDecl;
  52. class IdentifierInfo;
  53. class ObjCMethodDecl;
  54. class ObjCImplementationDecl;
  55. class ObjCCategoryImplDecl;
  56. class ObjCProtocolDecl;
  57. class ObjCEncodeExpr;
  58. class BlockExpr;
  59. class CharUnits;
  60. class Decl;
  61. class Expr;
  62. class Stmt;
  63. class InitListExpr;
  64. class StringLiteral;
  65. class NamedDecl;
  66. class ValueDecl;
  67. class VarDecl;
  68. class LangOptions;
  69. class CodeGenOptions;
  70. class HeaderSearchOptions;
  71. class PreprocessorOptions;
  72. class DiagnosticsEngine;
  73. class AnnotateAttr;
  74. class CXXDestructorDecl;
  75. class Module;
  76. class CoverageSourceInfo;
  77. namespace CodeGen {
  78. class CallArgList;
  79. class CodeGenFunction;
  80. class CodeGenTBAA;
  81. class CGCXXABI;
  82. class CGDebugInfo;
  83. class CGObjCRuntime;
  84. class CGOpenCLRuntime;
  85. class CGOpenMPRuntime;
  86. class CGCUDARuntime;
  87. class BlockFieldFlags;
  88. class FunctionArgList;
  89. class CoverageMappingModuleGen;
  90. struct OrderGlobalInits {
  91. unsigned int priority;
  92. unsigned int lex_order;
  93. OrderGlobalInits(unsigned int p, unsigned int l)
  94. : priority(p), lex_order(l) {}
  95. bool operator==(const OrderGlobalInits &RHS) const {
  96. return priority == RHS.priority && lex_order == RHS.lex_order;
  97. }
  98. bool operator<(const OrderGlobalInits &RHS) const {
  99. return std::tie(priority, lex_order) <
  100. std::tie(RHS.priority, RHS.lex_order);
  101. }
  102. };
  103. struct ObjCEntrypoints {
  104. ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
  105. /// void objc_autoreleasePoolPop(void*);
  106. llvm::Constant *objc_autoreleasePoolPop;
  107. /// void *objc_autoreleasePoolPush(void);
  108. llvm::Constant *objc_autoreleasePoolPush;
  109. /// id objc_autorelease(id);
  110. llvm::Constant *objc_autorelease;
  111. /// id objc_autoreleaseReturnValue(id);
  112. llvm::Constant *objc_autoreleaseReturnValue;
  113. /// void objc_copyWeak(id *dest, id *src);
  114. llvm::Constant *objc_copyWeak;
  115. /// void objc_destroyWeak(id*);
  116. llvm::Constant *objc_destroyWeak;
  117. /// id objc_initWeak(id*, id);
  118. llvm::Constant *objc_initWeak;
  119. /// id objc_loadWeak(id*);
  120. llvm::Constant *objc_loadWeak;
  121. /// id objc_loadWeakRetained(id*);
  122. llvm::Constant *objc_loadWeakRetained;
  123. /// void objc_moveWeak(id *dest, id *src);
  124. llvm::Constant *objc_moveWeak;
  125. /// id objc_retain(id);
  126. llvm::Constant *objc_retain;
  127. /// id objc_retainAutorelease(id);
  128. llvm::Constant *objc_retainAutorelease;
  129. /// id objc_retainAutoreleaseReturnValue(id);
  130. llvm::Constant *objc_retainAutoreleaseReturnValue;
  131. /// id objc_retainAutoreleasedReturnValue(id);
  132. llvm::Constant *objc_retainAutoreleasedReturnValue;
  133. /// id objc_retainBlock(id);
  134. llvm::Constant *objc_retainBlock;
  135. /// void objc_release(id);
  136. llvm::Constant *objc_release;
  137. /// id objc_storeStrong(id*, id);
  138. llvm::Constant *objc_storeStrong;
  139. /// id objc_storeWeak(id*, id);
  140. llvm::Constant *objc_storeWeak;
  141. /// id objc_unsafeClaimAutoreleasedReturnValue(id);
  142. llvm::Constant *objc_unsafeClaimAutoreleasedReturnValue;
  143. /// A void(void) inline asm to use to mark that the return value of
  144. /// a call will be immediately retain.
  145. llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
  146. /// void clang.arc.use(...);
  147. llvm::Constant *clang_arc_use;
  148. };
  149. /// This class records statistics on instrumentation based profiling.
  150. class InstrProfStats {
  151. uint32_t VisitedInMainFile;
  152. uint32_t MissingInMainFile;
  153. uint32_t Visited;
  154. uint32_t Missing;
  155. uint32_t Mismatched;
  156. public:
  157. InstrProfStats()
  158. : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
  159. Mismatched(0) {}
  160. /// Record that we've visited a function and whether or not that function was
  161. /// in the main source file.
  162. void addVisited(bool MainFile) {
  163. if (MainFile)
  164. ++VisitedInMainFile;
  165. ++Visited;
  166. }
  167. /// Record that a function we've visited has no profile data.
  168. void addMissing(bool MainFile) {
  169. if (MainFile)
  170. ++MissingInMainFile;
  171. ++Missing;
  172. }
  173. /// Record that a function we've visited has mismatched profile data.
  174. void addMismatched(bool MainFile) { ++Mismatched; }
  175. /// Whether or not the stats we've gathered indicate any potential problems.
  176. bool hasDiagnostics() { return Missing || Mismatched; }
  177. /// Report potential problems we've found to \c Diags.
  178. void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
  179. };
  180. /// A pair of helper functions for a __block variable.
  181. class BlockByrefHelpers : public llvm::FoldingSetNode {
  182. // MSVC requires this type to be complete in order to process this
  183. // header.
  184. public:
  185. llvm::Constant *CopyHelper;
  186. llvm::Constant *DisposeHelper;
  187. /// The alignment of the field. This is important because
  188. /// different offsets to the field within the byref struct need to
  189. /// have different helper functions.
  190. CharUnits Alignment;
  191. BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
  192. BlockByrefHelpers(const BlockByrefHelpers &) = default;
  193. virtual ~BlockByrefHelpers();
  194. void Profile(llvm::FoldingSetNodeID &id) const {
  195. id.AddInteger(Alignment.getQuantity());
  196. profileImpl(id);
  197. }
  198. virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
  199. virtual bool needsCopy() const { return true; }
  200. virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
  201. virtual bool needsDispose() const { return true; }
  202. virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
  203. };
  204. /// This class organizes the cross-function state that is used while generating
  205. /// LLVM code.
  206. class CodeGenModule : public CodeGenTypeCache {
  207. CodeGenModule(const CodeGenModule &) = delete;
  208. void operator=(const CodeGenModule &) = delete;
  209. public:
  210. struct Structor {
  211. Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
  212. Structor(int Priority, llvm::Constant *Initializer,
  213. llvm::Constant *AssociatedData)
  214. : Priority(Priority), Initializer(Initializer),
  215. AssociatedData(AssociatedData) {}
  216. int Priority;
  217. llvm::Constant *Initializer;
  218. llvm::Constant *AssociatedData;
  219. };
  220. typedef std::vector<Structor> CtorList;
  221. private:
  222. ASTContext &Context;
  223. const LangOptions &LangOpts;
  224. const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
  225. const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
  226. const CodeGenOptions &CodeGenOpts;
  227. llvm::Module &TheModule;
  228. DiagnosticsEngine &Diags;
  229. const TargetInfo &Target;
  230. std::unique_ptr<CGCXXABI> ABI;
  231. llvm::LLVMContext &VMContext;
  232. CodeGenTBAA *TBAA;
  233. mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
  234. // This should not be moved earlier, since its initialization depends on some
  235. // of the previous reference members being already initialized and also checks
  236. // if TheTargetCodeGenInfo is NULL
  237. CodeGenTypes Types;
  238. /// Holds information about C++ vtables.
  239. CodeGenVTables VTables;
  240. CGObjCRuntime* ObjCRuntime;
  241. CGOpenCLRuntime* OpenCLRuntime;
  242. CGOpenMPRuntime* OpenMPRuntime;
  243. CGCUDARuntime* CUDARuntime;
  244. CGDebugInfo* DebugInfo;
  245. ObjCEntrypoints *ObjCData;
  246. llvm::MDNode *NoObjCARCExceptionsMetadata;
  247. std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
  248. InstrProfStats PGOStats;
  249. std::unique_ptr<llvm::SanitizerStatReport> SanStats;
  250. // A set of references that have only been seen via a weakref so far. This is
  251. // used to remove the weak of the reference if we ever see a direct reference
  252. // or a definition.
  253. llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
  254. /// This contains all the decls which have definitions but/ which are deferred
  255. /// for emission and therefore should only be output if they are actually
  256. /// used. If a decl is in this, then it is known to have not been referenced
  257. /// yet.
  258. std::map<StringRef, GlobalDecl> DeferredDecls;
  259. /// This is a list of deferred decls which we have seen that *are* actually
  260. /// referenced. These get code generated when the module is done.
  261. struct DeferredGlobal {
  262. DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
  263. llvm::TrackingVH<llvm::GlobalValue> GV;
  264. GlobalDecl GD;
  265. };
  266. std::vector<DeferredGlobal> DeferredDeclsToEmit;
  267. void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
  268. DeferredDeclsToEmit.emplace_back(GV, GD);
  269. }
  270. /// List of alias we have emitted. Used to make sure that what they point to
  271. /// is defined once we get to the end of the of the translation unit.
  272. std::vector<GlobalDecl> Aliases;
  273. typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
  274. ReplacementsTy Replacements;
  275. /// List of global values to be replaced with something else. Used when we
  276. /// want to replace a GlobalValue but can't identify it by its mangled name
  277. /// anymore (because the name is already taken).
  278. llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
  279. GlobalValReplacements;
  280. /// Set of global decls for which we already diagnosed mangled name conflict.
  281. /// Required to not issue a warning (on a mangling conflict) multiple times
  282. /// for the same decl.
  283. llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
  284. /// A queue of (optional) vtables to consider emitting.
  285. std::vector<const CXXRecordDecl*> DeferredVTables;
  286. /// List of global values which are required to be present in the object file;
  287. /// bitcast to i8*. This is used for forcing visibility of symbols which may
  288. /// otherwise be optimized out.
  289. std::vector<llvm::WeakVH> LLVMUsed;
  290. std::vector<llvm::WeakVH> LLVMCompilerUsed;
  291. /// Store the list of global constructors and their respective priorities to
  292. /// be emitted when the translation unit is complete.
  293. CtorList GlobalCtors;
  294. /// Store the list of global destructors and their respective priorities to be
  295. /// emitted when the translation unit is complete.
  296. CtorList GlobalDtors;
  297. /// An ordered map of canonical GlobalDecls to their mangled names.
  298. llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
  299. llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
  300. /// Global annotations.
  301. std::vector<llvm::Constant*> Annotations;
  302. /// Map used to get unique annotation strings.
  303. llvm::StringMap<llvm::Constant*> AnnotationStrings;
  304. llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
  305. llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
  306. llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
  307. llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
  308. llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
  309. llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
  310. llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
  311. /// Map used to get unique type descriptor constants for sanitizers.
  312. llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
  313. /// Map used to track internal linkage functions declared within
  314. /// extern "C" regions.
  315. typedef llvm::MapVector<IdentifierInfo *,
  316. llvm::GlobalValue *> StaticExternCMap;
  317. StaticExternCMap StaticExternCValues;
  318. /// \brief thread_local variables defined or used in this TU.
  319. std::vector<const VarDecl *> CXXThreadLocals;
  320. /// \brief thread_local variables with initializers that need to run
  321. /// before any thread_local variable in this TU is odr-used.
  322. std::vector<llvm::Function *> CXXThreadLocalInits;
  323. std::vector<const VarDecl *> CXXThreadLocalInitVars;
  324. /// Global variables with initializers that need to run before main.
  325. std::vector<llvm::Function *> CXXGlobalInits;
  326. /// When a C++ decl with an initializer is deferred, null is
  327. /// appended to CXXGlobalInits, and the index of that null is placed
  328. /// here so that the initializer will be performed in the correct
  329. /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
  330. /// that we don't re-emit the initializer.
  331. llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
  332. typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
  333. struct GlobalInitPriorityCmp {
  334. bool operator()(const GlobalInitData &LHS,
  335. const GlobalInitData &RHS) const {
  336. return LHS.first.priority < RHS.first.priority;
  337. }
  338. };
  339. /// Global variables with initializers whose order of initialization is set by
  340. /// init_priority attribute.
  341. SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
  342. /// Global destructor functions and arguments that need to run on termination.
  343. std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
  344. /// \brief The complete set of modules that has been imported.
  345. llvm::SetVector<clang::Module *> ImportedModules;
  346. /// \brief A vector of metadata strings.
  347. SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
  348. /// @name Cache for Objective-C runtime types
  349. /// @{
  350. /// Cached reference to the class for constant strings. This value has type
  351. /// int * but is actually an Obj-C class pointer.
  352. llvm::WeakVH CFConstantStringClassRef;
  353. /// Cached reference to the class for constant strings. This value has type
  354. /// int * but is actually an Obj-C class pointer.
  355. llvm::WeakVH ConstantStringClassRef;
  356. /// \brief The LLVM type corresponding to NSConstantString.
  357. llvm::StructType *NSConstantStringType;
  358. /// \brief The type used to describe the state of a fast enumeration in
  359. /// Objective-C's for..in loop.
  360. QualType ObjCFastEnumerationStateType;
  361. /// @}
  362. /// Lazily create the Objective-C runtime
  363. void createObjCRuntime();
  364. void createOpenCLRuntime();
  365. void createOpenMPRuntime();
  366. void createCUDARuntime();
  367. bool isTriviallyRecursive(const FunctionDecl *F);
  368. bool shouldEmitFunction(GlobalDecl GD);
  369. /// @name Cache for Blocks Runtime Globals
  370. /// @{
  371. llvm::Constant *NSConcreteGlobalBlock;
  372. llvm::Constant *NSConcreteStackBlock;
  373. llvm::Constant *BlockObjectAssign;
  374. llvm::Constant *BlockObjectDispose;
  375. llvm::Type *BlockDescriptorType;
  376. llvm::Type *GenericBlockLiteralType;
  377. struct {
  378. int GlobalUniqueCount;
  379. } Block;
  380. /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
  381. llvm::Constant *LifetimeStartFn;
  382. /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
  383. llvm::Constant *LifetimeEndFn;
  384. GlobalDecl initializedGlobalDecl;
  385. std::unique_ptr<SanitizerMetadata> SanitizerMD;
  386. /// @}
  387. llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
  388. std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
  389. /// Mapping from canonical types to their metadata identifiers. We need to
  390. /// maintain this mapping because identifiers may be formed from distinct
  391. /// MDNodes.
  392. llvm::DenseMap<QualType, llvm::Metadata *> MetadataIdMap;
  393. SanitizerBlacklist WholeProgramVTablesBlacklist;
  394. public:
  395. CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
  396. const PreprocessorOptions &ppopts,
  397. const CodeGenOptions &CodeGenOpts, llvm::Module &M,
  398. DiagnosticsEngine &Diags,
  399. CoverageSourceInfo *CoverageInfo = nullptr);
  400. ~CodeGenModule();
  401. void clear();
  402. /// Finalize LLVM code generation.
  403. void Release();
  404. /// Return a reference to the configured Objective-C runtime.
  405. CGObjCRuntime &getObjCRuntime() {
  406. if (!ObjCRuntime) createObjCRuntime();
  407. return *ObjCRuntime;
  408. }
  409. /// Return true iff an Objective-C runtime has been configured.
  410. bool hasObjCRuntime() { return !!ObjCRuntime; }
  411. /// Return a reference to the configured OpenCL runtime.
  412. CGOpenCLRuntime &getOpenCLRuntime() {
  413. assert(OpenCLRuntime != nullptr);
  414. return *OpenCLRuntime;
  415. }
  416. /// Return a reference to the configured OpenMP runtime.
  417. CGOpenMPRuntime &getOpenMPRuntime() {
  418. assert(OpenMPRuntime != nullptr);
  419. return *OpenMPRuntime;
  420. }
  421. /// Return a reference to the configured CUDA runtime.
  422. CGCUDARuntime &getCUDARuntime() {
  423. assert(CUDARuntime != nullptr);
  424. return *CUDARuntime;
  425. }
  426. ObjCEntrypoints &getObjCEntrypoints() const {
  427. assert(ObjCData != nullptr);
  428. return *ObjCData;
  429. }
  430. InstrProfStats &getPGOStats() { return PGOStats; }
  431. llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
  432. CoverageMappingModuleGen *getCoverageMapping() const {
  433. return CoverageMapping.get();
  434. }
  435. llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
  436. return StaticLocalDeclMap[D];
  437. }
  438. void setStaticLocalDeclAddress(const VarDecl *D,
  439. llvm::Constant *C) {
  440. StaticLocalDeclMap[D] = C;
  441. }
  442. llvm::Constant *
  443. getOrCreateStaticVarDecl(const VarDecl &D,
  444. llvm::GlobalValue::LinkageTypes Linkage);
  445. llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
  446. return StaticLocalDeclGuardMap[D];
  447. }
  448. void setStaticLocalDeclGuardAddress(const VarDecl *D,
  449. llvm::GlobalVariable *C) {
  450. StaticLocalDeclGuardMap[D] = C;
  451. }
  452. bool lookupRepresentativeDecl(StringRef MangledName,
  453. GlobalDecl &Result) const;
  454. llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
  455. return AtomicSetterHelperFnMap[Ty];
  456. }
  457. void setAtomicSetterHelperFnMap(QualType Ty,
  458. llvm::Constant *Fn) {
  459. AtomicSetterHelperFnMap[Ty] = Fn;
  460. }
  461. llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
  462. return AtomicGetterHelperFnMap[Ty];
  463. }
  464. void setAtomicGetterHelperFnMap(QualType Ty,
  465. llvm::Constant *Fn) {
  466. AtomicGetterHelperFnMap[Ty] = Fn;
  467. }
  468. llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
  469. return TypeDescriptorMap[Ty];
  470. }
  471. void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
  472. TypeDescriptorMap[Ty] = C;
  473. }
  474. CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
  475. llvm::MDNode *getNoObjCARCExceptionsMetadata() {
  476. if (!NoObjCARCExceptionsMetadata)
  477. NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
  478. return NoObjCARCExceptionsMetadata;
  479. }
  480. ASTContext &getContext() const { return Context; }
  481. const LangOptions &getLangOpts() const { return LangOpts; }
  482. const HeaderSearchOptions &getHeaderSearchOpts()
  483. const { return HeaderSearchOpts; }
  484. const PreprocessorOptions &getPreprocessorOpts()
  485. const { return PreprocessorOpts; }
  486. const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
  487. llvm::Module &getModule() const { return TheModule; }
  488. DiagnosticsEngine &getDiags() const { return Diags; }
  489. const llvm::DataLayout &getDataLayout() const {
  490. return TheModule.getDataLayout();
  491. }
  492. const TargetInfo &getTarget() const { return Target; }
  493. const llvm::Triple &getTriple() const;
  494. bool supportsCOMDAT() const;
  495. void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
  496. CGCXXABI &getCXXABI() const { return *ABI; }
  497. llvm::LLVMContext &getLLVMContext() { return VMContext; }
  498. bool shouldUseTBAA() const { return TBAA != nullptr; }
  499. const TargetCodeGenInfo &getTargetCodeGenInfo();
  500. CodeGenTypes &getTypes() { return Types; }
  501. CodeGenVTables &getVTables() { return VTables; }
  502. ItaniumVTableContext &getItaniumVTableContext() {
  503. return VTables.getItaniumVTableContext();
  504. }
  505. MicrosoftVTableContext &getMicrosoftVTableContext() {
  506. return VTables.getMicrosoftVTableContext();
  507. }
  508. CtorList &getGlobalCtors() { return GlobalCtors; }
  509. CtorList &getGlobalDtors() { return GlobalDtors; }
  510. llvm::MDNode *getTBAAInfo(QualType QTy);
  511. llvm::MDNode *getTBAAInfoForVTablePtr();
  512. llvm::MDNode *getTBAAStructInfo(QualType QTy);
  513. /// Return the path-aware tag for given base type, access node and offset.
  514. llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
  515. uint64_t O);
  516. bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
  517. bool isPaddedAtomicType(QualType type);
  518. bool isPaddedAtomicType(const AtomicType *type);
  519. /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
  520. /// is the same as the type. For struct-path aware TBAA, the tag
  521. /// is different from the type: base type, access type and offset.
  522. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  523. void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  524. llvm::MDNode *TBAAInfo,
  525. bool ConvertTypeToTag = true);
  526. /// Adds !invariant.barrier !tag to instruction
  527. void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
  528. const CXXRecordDecl *RD);
  529. /// Emit the given number of characters as a value of type size_t.
  530. llvm::ConstantInt *getSize(CharUnits numChars);
  531. /// Set the visibility for the given LLVM GlobalValue.
  532. void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
  533. /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
  534. /// variable declaration D.
  535. void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
  536. static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
  537. switch (V) {
  538. case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
  539. case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
  540. case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
  541. }
  542. llvm_unreachable("unknown visibility!");
  543. }
  544. llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition = false);
  545. /// Will return a global variable of the given type. If a variable with a
  546. /// different type already exists then a new variable with the right type
  547. /// will be created and all uses of the old variable will be replaced with a
  548. /// bitcast to the new variable.
  549. llvm::GlobalVariable *
  550. CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
  551. llvm::GlobalValue::LinkageTypes Linkage);
  552. llvm::Function *
  553. CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
  554. const CGFunctionInfo &FI,
  555. SourceLocation Loc = SourceLocation(),
  556. bool TLS = false);
  557. /// Return the address space of the underlying global variable for D, as
  558. /// determined by its declaration. Normally this is the same as the address
  559. /// space of D's type, but in CUDA, address spaces are associated with
  560. /// declarations, not types.
  561. unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
  562. /// Return the llvm::Constant for the address of the given global variable.
  563. /// If Ty is non-null and if the global doesn't exist, then it will be created
  564. /// with the specified type instead of whatever the normal requested type
  565. /// would be. If IsForDefinition is true, it is guranteed that an actual
  566. /// global with type Ty will be returned, not conversion of a variable with
  567. /// the same mangled name but some other type.
  568. llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
  569. llvm::Type *Ty = nullptr,
  570. bool IsForDefinition = false);
  571. /// Return the address of the given function. If Ty is non-null, then this
  572. /// function will use the specified type if it has to create it.
  573. llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
  574. bool ForVTable = false,
  575. bool DontDefer = false,
  576. bool IsForDefinition = false);
  577. /// Get the address of the RTTI descriptor for the given type.
  578. llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
  579. /// Get the address of a uuid descriptor .
  580. ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
  581. /// Get the address of the thunk for the given global decl.
  582. llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
  583. /// Get a reference to the target of VD.
  584. ConstantAddress GetWeakRefReference(const ValueDecl *VD);
  585. /// Returns the assumed alignment of an opaque pointer to the given class.
  586. CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
  587. /// Returns the assumed alignment of a virtual base of a class.
  588. CharUnits getVBaseAlignment(CharUnits DerivedAlign,
  589. const CXXRecordDecl *Derived,
  590. const CXXRecordDecl *VBase);
  591. /// Given a class pointer with an actual known alignment, and the
  592. /// expected alignment of an object at a dynamic offset w.r.t that
  593. /// pointer, return the alignment to assume at the offset.
  594. CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
  595. const CXXRecordDecl *Class,
  596. CharUnits ExpectedTargetAlign);
  597. CharUnits
  598. computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
  599. CastExpr::path_const_iterator Start,
  600. CastExpr::path_const_iterator End);
  601. /// Returns the offset from a derived class to a class. Returns null if the
  602. /// offset is 0.
  603. llvm::Constant *
  604. GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  605. CastExpr::path_const_iterator PathBegin,
  606. CastExpr::path_const_iterator PathEnd);
  607. llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
  608. /// Fetches the global unique block count.
  609. int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
  610. /// Fetches the type of a generic block descriptor.
  611. llvm::Type *getBlockDescriptorType();
  612. /// The type of a generic block literal.
  613. llvm::Type *getGenericBlockLiteralType();
  614. /// Gets the address of a block which requires no captures.
  615. llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
  616. /// Return a pointer to a constant CFString object for the given string.
  617. ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
  618. /// Return a pointer to a constant NSString object for the given string. Or a
  619. /// user defined String object as defined via
  620. /// -fconstant-string-class=class_name option.
  621. ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
  622. /// Return a constant array for the given string.
  623. llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
  624. /// Return a pointer to a constant array for the given string literal.
  625. ConstantAddress
  626. GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  627. StringRef Name = ".str");
  628. /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
  629. ConstantAddress
  630. GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
  631. /// Returns a pointer to a character array containing the literal and a
  632. /// terminating '\0' character. The result has pointer to array type.
  633. ///
  634. /// \param GlobalName If provided, the name to use for the global (if one is
  635. /// created).
  636. ConstantAddress
  637. GetAddrOfConstantCString(const std::string &Str,
  638. const char *GlobalName = nullptr);
  639. /// Returns a pointer to a constant global variable for the given file-scope
  640. /// compound literal expression.
  641. ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
  642. /// \brief Returns a pointer to a global variable representing a temporary
  643. /// with static or thread storage duration.
  644. ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
  645. const Expr *Inner);
  646. /// \brief Retrieve the record type that describes the state of an
  647. /// Objective-C fast enumeration loop (for..in).
  648. QualType getObjCFastEnumerationStateType();
  649. // Produce code for this constructor/destructor. This method doesn't try
  650. // to apply any ABI rules about which other constructors/destructors
  651. // are needed or if they are alias to each other.
  652. llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
  653. StructorType Type);
  654. /// Return the address of the constructor/destructor of the given type.
  655. llvm::Constant *
  656. getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
  657. const CGFunctionInfo *FnInfo = nullptr,
  658. llvm::FunctionType *FnType = nullptr,
  659. bool DontDefer = false, bool IsForDefinition = false);
  660. /// Given a builtin id for a function like "__builtin_fabsf", return a
  661. /// Function* for "fabsf".
  662. llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
  663. unsigned BuiltinID);
  664. llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
  665. /// Emit code for a single top level declaration.
  666. void EmitTopLevelDecl(Decl *D);
  667. /// \brief Stored a deferred empty coverage mapping for an unused
  668. /// and thus uninstrumented top level declaration.
  669. void AddDeferredUnusedCoverageMapping(Decl *D);
  670. /// \brief Remove the deferred empty coverage mapping as this
  671. /// declaration is actually instrumented.
  672. void ClearUnusedCoverageMapping(const Decl *D);
  673. /// \brief Emit all the deferred coverage mappings
  674. /// for the uninstrumented functions.
  675. void EmitDeferredUnusedCoverageMappings();
  676. /// Tell the consumer that this variable has been instantiated.
  677. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
  678. /// \brief If the declaration has internal linkage but is inside an
  679. /// extern "C" linkage specification, prepare to emit an alias for it
  680. /// to the expected name.
  681. template<typename SomeDecl>
  682. void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
  683. /// Add a global to a list to be added to the llvm.used metadata.
  684. void addUsedGlobal(llvm::GlobalValue *GV);
  685. /// Add a global to a list to be added to the llvm.compiler.used metadata.
  686. void addCompilerUsedGlobal(llvm::GlobalValue *GV);
  687. /// Add a destructor and object to add to the C++ global destructor function.
  688. void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
  689. CXXGlobalDtors.emplace_back(DtorFn, Object);
  690. }
  691. /// Create a new runtime function with the specified type and name.
  692. llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
  693. StringRef Name,
  694. llvm::AttributeSet ExtraAttrs =
  695. llvm::AttributeSet());
  696. /// Create a new compiler builtin function with the specified type and name.
  697. llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
  698. StringRef Name,
  699. llvm::AttributeSet ExtraAttrs =
  700. llvm::AttributeSet());
  701. /// Create a new runtime global variable with the specified type and name.
  702. llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
  703. StringRef Name);
  704. ///@name Custom Blocks Runtime Interfaces
  705. ///@{
  706. llvm::Constant *getNSConcreteGlobalBlock();
  707. llvm::Constant *getNSConcreteStackBlock();
  708. llvm::Constant *getBlockObjectAssign();
  709. llvm::Constant *getBlockObjectDispose();
  710. ///@}
  711. llvm::Constant *getLLVMLifetimeStartFn();
  712. llvm::Constant *getLLVMLifetimeEndFn();
  713. // Make sure that this type is translated.
  714. void UpdateCompletedType(const TagDecl *TD);
  715. llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
  716. /// Try to emit the initializer for the given declaration as a constant;
  717. /// returns 0 if the expression cannot be emitted as a constant.
  718. llvm::Constant *EmitConstantInit(const VarDecl &D,
  719. CodeGenFunction *CGF = nullptr);
  720. /// Try to emit the given expression as a constant; returns 0 if the
  721. /// expression cannot be emitted as a constant.
  722. llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
  723. CodeGenFunction *CGF = nullptr);
  724. /// Emit the given constant value as a constant, in the type's scalar
  725. /// representation.
  726. llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
  727. CodeGenFunction *CGF = nullptr);
  728. /// Emit the given constant value as a constant, in the type's memory
  729. /// representation.
  730. llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
  731. QualType DestType,
  732. CodeGenFunction *CGF = nullptr);
  733. /// \brief Emit type info if type of an expression is a variably modified
  734. /// type. Also emit proper debug info for cast types.
  735. void EmitExplicitCastExprType(const ExplicitCastExpr *E,
  736. CodeGenFunction *CGF = nullptr);
  737. /// Return the result of value-initializing the given type, i.e. a null
  738. /// expression of the given type. This is usually, but not always, an LLVM
  739. /// null constant.
  740. llvm::Constant *EmitNullConstant(QualType T);
  741. /// Return a null constant appropriate for zero-initializing a base class with
  742. /// the given type. This is usually, but not always, an LLVM null constant.
  743. llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
  744. /// Emit a general error that something can't be done.
  745. void Error(SourceLocation loc, StringRef error);
  746. /// Print out an error that codegen doesn't support the specified stmt yet.
  747. void ErrorUnsupported(const Stmt *S, const char *Type);
  748. /// Print out an error that codegen doesn't support the specified decl yet.
  749. void ErrorUnsupported(const Decl *D, const char *Type);
  750. /// Set the attributes on the LLVM function for the given decl and function
  751. /// info. This applies attributes necessary for handling the ABI as well as
  752. /// user specified attributes like section.
  753. void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
  754. const CGFunctionInfo &FI);
  755. /// Set the LLVM function attributes (sext, zext, etc).
  756. void SetLLVMFunctionAttributes(const Decl *D,
  757. const CGFunctionInfo &Info,
  758. llvm::Function *F);
  759. /// Set the LLVM function attributes which only apply to a function
  760. /// definition.
  761. void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
  762. /// Return true iff the given type uses 'sret' when used as a return type.
  763. bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
  764. /// Return true iff the given type uses an argument slot when 'sret' is used
  765. /// as a return type.
  766. bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
  767. /// Return true iff the given type uses 'fpret' when used as a return type.
  768. bool ReturnTypeUsesFPRet(QualType ResultType);
  769. /// Return true iff the given type uses 'fp2ret' when used as a return type.
  770. bool ReturnTypeUsesFP2Ret(QualType ResultType);
  771. /// Get the LLVM attributes and calling convention to use for a particular
  772. /// function type.
  773. ///
  774. /// \param Name - The function name.
  775. /// \param Info - The function type information.
  776. /// \param CalleeInfo - The callee information these attributes are being
  777. /// constructed for. If valid, the attributes applied to this decl may
  778. /// contribute to the function attributes and calling convention.
  779. /// \param PAL [out] - On return, the attribute list to use.
  780. /// \param CallingConv [out] - On return, the LLVM calling convention to use.
  781. void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
  782. CGCalleeInfo CalleeInfo, AttributeListType &PAL,
  783. unsigned &CallingConv, bool AttrOnCallSite);
  784. // Fills in the supplied string map with the set of target features for the
  785. // passed in function.
  786. void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  787. const FunctionDecl *FD);
  788. StringRef getMangledName(GlobalDecl GD);
  789. StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
  790. void EmitTentativeDefinition(const VarDecl *D);
  791. void EmitVTable(CXXRecordDecl *Class);
  792. void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
  793. /// \brief Appends Opts to the "Linker Options" metadata value.
  794. void AppendLinkerOptions(StringRef Opts);
  795. /// \brief Appends a detect mismatch command to the linker options.
  796. void AddDetectMismatch(StringRef Name, StringRef Value);
  797. /// \brief Appends a dependent lib to the "Linker Options" metadata value.
  798. void AddDependentLib(StringRef Lib);
  799. llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
  800. void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
  801. F->setLinkage(getFunctionLinkage(GD));
  802. }
  803. /// Set the DLL storage class on F.
  804. void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
  805. /// Return the appropriate linkage for the vtable, VTT, and type information
  806. /// of the given class.
  807. llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
  808. /// Return the store size, in character units, of the given LLVM type.
  809. CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
  810. /// Returns LLVM linkage for a declarator.
  811. llvm::GlobalValue::LinkageTypes
  812. getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
  813. bool IsConstantVariable);
  814. /// Returns LLVM linkage for a declarator.
  815. llvm::GlobalValue::LinkageTypes
  816. getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
  817. /// Emit all the global annotations.
  818. void EmitGlobalAnnotations();
  819. /// Emit an annotation string.
  820. llvm::Constant *EmitAnnotationString(StringRef Str);
  821. /// Emit the annotation's translation unit.
  822. llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
  823. /// Emit the annotation line number.
  824. llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
  825. /// Generate the llvm::ConstantStruct which contains the annotation
  826. /// information for a given GlobalValue. The annotation struct is
  827. /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
  828. /// GlobalValue being annotated. The second field is the constant string
  829. /// created from the AnnotateAttr's annotation. The third field is a constant
  830. /// string containing the name of the translation unit. The fourth field is
  831. /// the line number in the file of the annotated value declaration.
  832. llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
  833. const AnnotateAttr *AA,
  834. SourceLocation L);
  835. /// Add global annotations that are set on D, for the global GV. Those
  836. /// annotations are emitted during finalization of the LLVM code.
  837. void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
  838. bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
  839. bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
  840. QualType Ty,
  841. StringRef Category = StringRef()) const;
  842. SanitizerMetadata *getSanitizerMetadata() {
  843. return SanitizerMD.get();
  844. }
  845. void addDeferredVTable(const CXXRecordDecl *RD) {
  846. DeferredVTables.push_back(RD);
  847. }
  848. /// Emit code for a singal global function or var decl. Forward declarations
  849. /// are emitted lazily.
  850. void EmitGlobal(GlobalDecl D);
  851. bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
  852. bool InEveryTU);
  853. bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
  854. /// Set attributes for a global definition.
  855. void setFunctionDefinitionAttributes(const FunctionDecl *D,
  856. llvm::Function *F);
  857. llvm::GlobalValue *GetGlobalValue(StringRef Ref);
  858. /// Set attributes which are common to any form of a global definition (alias,
  859. /// Objective-C method, function, global variable).
  860. ///
  861. /// NOTE: This should only be called for definitions.
  862. void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
  863. /// Set attributes which must be preserved by an alias. This includes common
  864. /// attributes (i.e. it includes a call to SetCommonAttributes).
  865. ///
  866. /// NOTE: This should only be called for definitions.
  867. void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
  868. void addReplacement(StringRef Name, llvm::Constant *C);
  869. void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
  870. /// \brief Emit a code for threadprivate directive.
  871. /// \param D Threadprivate declaration.
  872. void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
  873. /// \brief Emit a code for declare reduction construct.
  874. void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  875. CodeGenFunction *CGF = nullptr);
  876. /// Returns whether we need bit sets attached to vtables.
  877. bool NeedVTableBitSets();
  878. /// Returns whether the given record is blacklisted from whole-program
  879. /// transformations (i.e. CFI or whole-program vtable optimization).
  880. bool IsBitSetBlacklistedRecord(const CXXRecordDecl *RD);
  881. /// Emit bit set entries for the given vtable using the given layout if
  882. /// vptr CFI is enabled.
  883. void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
  884. const VTableLayout &VTLayout);
  885. /// Generate a cross-DSO type identifier for type.
  886. llvm::ConstantInt *CreateCfiIdForTypeMetadata(llvm::Metadata *MD);
  887. /// Create a metadata identifier for the given type. This may either be an
  888. /// MDString (for external identifiers) or a distinct unnamed MDNode (for
  889. /// internal identifiers).
  890. llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
  891. /// Create a bitset entry for the given function and add it to BitsetsMD.
  892. void CreateFunctionBitSetEntry(const FunctionDecl *FD, llvm::Function *F);
  893. /// Returns whether this module needs the "all-vtables" bitset.
  894. bool NeedAllVtablesBitSet() const;
  895. /// Create a bitset entry for the given vtable and add it to BitsetsMD.
  896. void CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
  897. llvm::GlobalVariable *VTable, CharUnits Offset,
  898. const CXXRecordDecl *RD);
  899. /// \breif Get the declaration of std::terminate for the platform.
  900. llvm::Constant *getTerminateFn();
  901. llvm::SanitizerStatReport &getSanStats();
  902. private:
  903. llvm::Constant *
  904. GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
  905. bool ForVTable, bool DontDefer = false,
  906. bool IsThunk = false,
  907. llvm::AttributeSet ExtraAttrs = llvm::AttributeSet(),
  908. bool IsForDefinition = false);
  909. llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
  910. llvm::PointerType *PTy,
  911. const VarDecl *D,
  912. bool IsForDefinition = false);
  913. void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
  914. /// Set function attributes for a function declaration.
  915. void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  916. bool IsIncompleteFunction, bool IsThunk);
  917. void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
  918. void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
  919. void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
  920. void EmitAliasDefinition(GlobalDecl GD);
  921. void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
  922. void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
  923. // C++ related functions.
  924. void EmitNamespace(const NamespaceDecl *D);
  925. void EmitLinkageSpec(const LinkageSpecDecl *D);
  926. void CompleteDIClassType(const CXXMethodDecl* D);
  927. /// \brief Emit the function that initializes C++ thread_local variables.
  928. void EmitCXXThreadLocalInitFunc();
  929. /// Emit the function that initializes C++ globals.
  930. void EmitCXXGlobalInitFunc();
  931. /// Emit the function that destroys C++ globals.
  932. void EmitCXXGlobalDtorFunc();
  933. /// Emit the function that initializes the specified global (if PerformInit is
  934. /// true) and registers its destructor.
  935. void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
  936. llvm::GlobalVariable *Addr,
  937. bool PerformInit);
  938. void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
  939. llvm::Function *InitFunc, InitSegAttr *ISA);
  940. // FIXME: Hardcoding priority here is gross.
  941. void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
  942. llvm::Constant *AssociatedData = nullptr);
  943. void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
  944. /// Generates a global array of functions and priorities using the given list
  945. /// and name. This array will have appending linkage and is suitable for use
  946. /// as a LLVM constructor or destructor array.
  947. void EmitCtorList(const CtorList &Fns, const char *GlobalName);
  948. /// Emit any needed decls for which code generation was deferred.
  949. void EmitDeferred();
  950. /// Call replaceAllUsesWith on all pairs in Replacements.
  951. void applyReplacements();
  952. /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
  953. void applyGlobalValReplacements();
  954. void checkAliases();
  955. /// Emit any vtables which we deferred and still have a use for.
  956. void EmitDeferredVTables();
  957. /// Emit the llvm.used and llvm.compiler.used metadata.
  958. void emitLLVMUsed();
  959. /// \brief Emit the link options introduced by imported modules.
  960. void EmitModuleLinkOptions();
  961. /// \brief Emit aliases for internal-linkage declarations inside "C" language
  962. /// linkage specifications, giving them the "expected" name where possible.
  963. void EmitStaticExternCAliases();
  964. void EmitDeclMetadata();
  965. /// \brief Emit the Clang version as llvm.ident metadata.
  966. void EmitVersionIdentMetadata();
  967. /// Emits target specific Metadata for global declarations.
  968. void EmitTargetMetadata();
  969. /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
  970. /// .gcda files in a way that persists in .bc files.
  971. void EmitCoverageFile();
  972. /// Emits the initializer for a uuidof string.
  973. llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
  974. /// Determine whether the definition must be emitted; if this returns \c
  975. /// false, the definition can be emitted lazily if it's used.
  976. bool MustBeEmitted(const ValueDecl *D);
  977. /// Determine whether the definition can be emitted eagerly, or should be
  978. /// delayed until the end of the translation unit. This is relevant for
  979. /// definitions whose linkage can change, e.g. implicit function instantions
  980. /// which may later be explicitly instantiated.
  981. bool MayBeEmittedEagerly(const ValueDecl *D);
  982. /// Check whether we can use a "simpler", more core exceptions personality
  983. /// function.
  984. void SimplifyPersonality();
  985. };
  986. } // end namespace CodeGen
  987. } // end namespace clang
  988. #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H