CodeGenModule.h 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  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/GlobalDecl.h"
  23. #include "clang/AST/Mangle.h"
  24. #include "clang/Basic/ABI.h"
  25. #include "clang/Basic/LangOptions.h"
  26. #include "clang/Basic/Module.h"
  27. #include "clang/Basic/SanitizerBlacklist.h"
  28. #include "llvm/ADT/DenseMap.h"
  29. #include "llvm/ADT/SetVector.h"
  30. #include "llvm/ADT/SmallPtrSet.h"
  31. #include "llvm/ADT/StringMap.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/IR/ValueHandle.h"
  34. namespace llvm {
  35. class Module;
  36. class Constant;
  37. class ConstantInt;
  38. class Function;
  39. class GlobalValue;
  40. class DataLayout;
  41. class FunctionType;
  42. class LLVMContext;
  43. class IndexedInstrProfReader;
  44. }
  45. namespace clang {
  46. class TargetCodeGenInfo;
  47. class ASTContext;
  48. class AtomicType;
  49. class FunctionDecl;
  50. class IdentifierInfo;
  51. class ObjCMethodDecl;
  52. class ObjCImplementationDecl;
  53. class ObjCCategoryImplDecl;
  54. class ObjCProtocolDecl;
  55. class ObjCEncodeExpr;
  56. class BlockExpr;
  57. class CharUnits;
  58. class Decl;
  59. class Expr;
  60. class Stmt;
  61. class InitListExpr;
  62. class StringLiteral;
  63. class NamedDecl;
  64. class ValueDecl;
  65. class VarDecl;
  66. class LangOptions;
  67. class CodeGenOptions;
  68. class HeaderSearchOptions;
  69. class PreprocessorOptions;
  70. class DiagnosticsEngine;
  71. class AnnotateAttr;
  72. class CXXDestructorDecl;
  73. class Module;
  74. class CoverageSourceInfo;
  75. namespace CodeGen {
  76. class CallArgList;
  77. class CodeGenFunction;
  78. class CodeGenTBAA;
  79. class CGCXXABI;
  80. class CGDebugInfo;
  81. class CGObjCRuntime;
  82. class CGOpenCLRuntime;
  83. class CGOpenMPRuntime;
  84. class CGCUDARuntime;
  85. class BlockFieldFlags;
  86. class FunctionArgList;
  87. class CoverageMappingModuleGen;
  88. struct OrderGlobalInits {
  89. unsigned int priority;
  90. unsigned int lex_order;
  91. OrderGlobalInits(unsigned int p, unsigned int l)
  92. : priority(p), lex_order(l) {}
  93. bool operator==(const OrderGlobalInits &RHS) const {
  94. return priority == RHS.priority && lex_order == RHS.lex_order;
  95. }
  96. bool operator<(const OrderGlobalInits &RHS) const {
  97. return std::tie(priority, lex_order) <
  98. std::tie(RHS.priority, RHS.lex_order);
  99. }
  100. };
  101. struct RREntrypoints {
  102. RREntrypoints() { memset(this, 0, sizeof(*this)); }
  103. /// void objc_autoreleasePoolPop(void*);
  104. llvm::Constant *objc_autoreleasePoolPop;
  105. /// void *objc_autoreleasePoolPush(void);
  106. llvm::Constant *objc_autoreleasePoolPush;
  107. };
  108. struct ARCEntrypoints {
  109. ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
  110. /// id objc_autorelease(id);
  111. llvm::Constant *objc_autorelease;
  112. /// id objc_autoreleaseReturnValue(id);
  113. llvm::Constant *objc_autoreleaseReturnValue;
  114. /// void objc_copyWeak(id *dest, id *src);
  115. llvm::Constant *objc_copyWeak;
  116. /// void objc_destroyWeak(id*);
  117. llvm::Constant *objc_destroyWeak;
  118. /// id objc_initWeak(id*, id);
  119. llvm::Constant *objc_initWeak;
  120. /// id objc_loadWeak(id*);
  121. llvm::Constant *objc_loadWeak;
  122. /// id objc_loadWeakRetained(id*);
  123. llvm::Constant *objc_loadWeakRetained;
  124. /// void objc_moveWeak(id *dest, id *src);
  125. llvm::Constant *objc_moveWeak;
  126. /// id objc_retain(id);
  127. llvm::Constant *objc_retain;
  128. /// id objc_retainAutorelease(id);
  129. llvm::Constant *objc_retainAutorelease;
  130. /// id objc_retainAutoreleaseReturnValue(id);
  131. llvm::Constant *objc_retainAutoreleaseReturnValue;
  132. /// id objc_retainAutoreleasedReturnValue(id);
  133. llvm::Constant *objc_retainAutoreleasedReturnValue;
  134. /// id objc_retainBlock(id);
  135. llvm::Constant *objc_retainBlock;
  136. /// void objc_release(id);
  137. llvm::Constant *objc_release;
  138. /// id objc_storeStrong(id*, id);
  139. llvm::Constant *objc_storeStrong;
  140. /// id objc_storeWeak(id*, id);
  141. llvm::Constant *objc_storeWeak;
  142. /// A void(void) inline asm to use to mark that the return value of
  143. /// a call will be immediately retain.
  144. llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
  145. /// void clang.arc.use(...);
  146. llvm::Constant *clang_arc_use;
  147. };
  148. /// This class records statistics on instrumentation based profiling.
  149. class InstrProfStats {
  150. uint32_t VisitedInMainFile;
  151. uint32_t MissingInMainFile;
  152. uint32_t Visited;
  153. uint32_t Missing;
  154. uint32_t Mismatched;
  155. public:
  156. InstrProfStats()
  157. : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
  158. Mismatched(0) {}
  159. /// Record that we've visited a function and whether or not that function was
  160. /// in the main source file.
  161. void addVisited(bool MainFile) {
  162. if (MainFile)
  163. ++VisitedInMainFile;
  164. ++Visited;
  165. }
  166. /// Record that a function we've visited has no profile data.
  167. void addMissing(bool MainFile) {
  168. if (MainFile)
  169. ++MissingInMainFile;
  170. ++Missing;
  171. }
  172. /// Record that a function we've visited has mismatched profile data.
  173. void addMismatched(bool MainFile) { ++Mismatched; }
  174. /// Whether or not the stats we've gathered indicate any potential problems.
  175. bool hasDiagnostics() { return Missing || Mismatched; }
  176. /// Report potential problems we've found to \c Diags.
  177. void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
  178. };
  179. /// A pair of helper functions for a __block variable.
  180. class BlockByrefHelpers : public llvm::FoldingSetNode {
  181. // MSVC requires this type to be complete in order to process this
  182. // header.
  183. public:
  184. llvm::Constant *CopyHelper;
  185. llvm::Constant *DisposeHelper;
  186. /// The alignment of the field. This is important because
  187. /// different offsets to the field within the byref struct need to
  188. /// have different helper functions.
  189. CharUnits Alignment;
  190. BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
  191. BlockByrefHelpers(const BlockByrefHelpers &) = default;
  192. virtual ~BlockByrefHelpers();
  193. void Profile(llvm::FoldingSetNodeID &id) const {
  194. id.AddInteger(Alignment.getQuantity());
  195. profileImpl(id);
  196. }
  197. virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
  198. virtual bool needsCopy() const { return true; }
  199. virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
  200. virtual bool needsDispose() const { return true; }
  201. virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
  202. };
  203. /// This class organizes the cross-function state that is used while generating
  204. /// LLVM code.
  205. class CodeGenModule : public CodeGenTypeCache {
  206. CodeGenModule(const CodeGenModule &) = delete;
  207. void operator=(const CodeGenModule &) = delete;
  208. public:
  209. struct Structor {
  210. Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
  211. Structor(int Priority, llvm::Constant *Initializer,
  212. llvm::Constant *AssociatedData)
  213. : Priority(Priority), Initializer(Initializer),
  214. AssociatedData(AssociatedData) {}
  215. int Priority;
  216. llvm::Constant *Initializer;
  217. llvm::Constant *AssociatedData;
  218. };
  219. typedef std::vector<Structor> CtorList;
  220. private:
  221. ASTContext &Context;
  222. const LangOptions &LangOpts;
  223. const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
  224. const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
  225. const CodeGenOptions &CodeGenOpts;
  226. llvm::Module &TheModule;
  227. DiagnosticsEngine &Diags;
  228. const TargetInfo &Target;
  229. std::unique_ptr<CGCXXABI> ABI;
  230. llvm::LLVMContext &VMContext;
  231. CodeGenTBAA *TBAA;
  232. mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
  233. // This should not be moved earlier, since its initialization depends on some
  234. // of the previous reference members being already initialized and also checks
  235. // if TheTargetCodeGenInfo is NULL
  236. CodeGenTypes Types;
  237. /// Holds information about C++ vtables.
  238. CodeGenVTables VTables;
  239. CGObjCRuntime* ObjCRuntime;
  240. CGOpenCLRuntime* OpenCLRuntime;
  241. CGOpenMPRuntime* OpenMPRuntime;
  242. CGCUDARuntime* CUDARuntime;
  243. CGDebugInfo* DebugInfo;
  244. ARCEntrypoints *ARCData;
  245. llvm::MDNode *NoObjCARCExceptionsMetadata;
  246. RREntrypoints *RRData;
  247. std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
  248. InstrProfStats PGOStats;
  249. // A set of references that have only been seen via a weakref so far. This is
  250. // used to remove the weak of the reference if we ever see a direct reference
  251. // or a definition.
  252. llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
  253. /// This contains all the decls which have definitions but/ which are deferred
  254. /// for emission and therefore should only be output if they are actually
  255. /// used. If a decl is in this, then it is known to have not been referenced
  256. /// yet.
  257. std::map<StringRef, GlobalDecl> DeferredDecls;
  258. /// This is a list of deferred decls which we have seen that *are* actually
  259. /// referenced. These get code generated when the module is done.
  260. struct DeferredGlobal {
  261. DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
  262. llvm::TrackingVH<llvm::GlobalValue> GV;
  263. GlobalDecl GD;
  264. };
  265. std::vector<DeferredGlobal> DeferredDeclsToEmit;
  266. void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
  267. DeferredDeclsToEmit.emplace_back(GV, GD);
  268. }
  269. /// List of alias we have emitted. Used to make sure that what they point to
  270. /// is defined once we get to the end of the of the translation unit.
  271. std::vector<GlobalDecl> Aliases;
  272. typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
  273. ReplacementsTy Replacements;
  274. /// List of global values to be replaced with something else. Used when we
  275. /// want to replace a GlobalValue but can't identify it by its mangled name
  276. /// anymore (because the name is already taken).
  277. llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
  278. GlobalValReplacements;
  279. /// Set of global decls for which we already diagnosed mangled name conflict.
  280. /// Required to not issue a warning (on a mangling conflict) multiple times
  281. /// for the same decl.
  282. llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
  283. /// A queue of (optional) vtables to consider emitting.
  284. std::vector<const CXXRecordDecl*> DeferredVTables;
  285. /// List of global values which are required to be present in the object file;
  286. /// bitcast to i8*. This is used for forcing visibility of symbols which may
  287. /// otherwise be optimized out.
  288. std::vector<llvm::WeakVH> LLVMUsed;
  289. std::vector<llvm::WeakVH> LLVMCompilerUsed;
  290. /// Store the list of global constructors and their respective priorities to
  291. /// be emitted when the translation unit is complete.
  292. CtorList GlobalCtors;
  293. /// Store the list of global destructors and their respective priorities to be
  294. /// emitted when the translation unit is complete.
  295. CtorList GlobalDtors;
  296. /// An ordered map of canonical GlobalDecls to their mangled names.
  297. llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
  298. llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
  299. /// Global annotations.
  300. std::vector<llvm::Constant*> Annotations;
  301. /// Map used to get unique annotation strings.
  302. llvm::StringMap<llvm::Constant*> AnnotationStrings;
  303. llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
  304. llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
  305. llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
  306. llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
  307. llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
  308. llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
  309. llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
  310. /// Map used to get unique type descriptor constants for sanitizers.
  311. llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
  312. /// Map used to track internal linkage functions declared within
  313. /// extern "C" regions.
  314. typedef llvm::MapVector<IdentifierInfo *,
  315. llvm::GlobalValue *> StaticExternCMap;
  316. StaticExternCMap StaticExternCValues;
  317. /// \brief thread_local variables defined or used in this TU.
  318. std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
  319. 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<llvm::GlobalVariable *> 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. public:
  394. CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
  395. const PreprocessorOptions &ppopts,
  396. const CodeGenOptions &CodeGenOpts, llvm::Module &M,
  397. DiagnosticsEngine &Diags,
  398. CoverageSourceInfo *CoverageInfo = nullptr);
  399. ~CodeGenModule();
  400. void clear();
  401. /// Finalize LLVM code generation.
  402. void Release();
  403. /// Return a reference to the configured Objective-C runtime.
  404. CGObjCRuntime &getObjCRuntime() {
  405. if (!ObjCRuntime) createObjCRuntime();
  406. return *ObjCRuntime;
  407. }
  408. /// Return true iff an Objective-C runtime has been configured.
  409. bool hasObjCRuntime() { return !!ObjCRuntime; }
  410. /// Return a reference to the configured OpenCL runtime.
  411. CGOpenCLRuntime &getOpenCLRuntime() {
  412. assert(OpenCLRuntime != nullptr);
  413. return *OpenCLRuntime;
  414. }
  415. /// Return a reference to the configured OpenMP runtime.
  416. CGOpenMPRuntime &getOpenMPRuntime() {
  417. assert(OpenMPRuntime != nullptr);
  418. return *OpenMPRuntime;
  419. }
  420. /// Return a reference to the configured CUDA runtime.
  421. CGCUDARuntime &getCUDARuntime() {
  422. assert(CUDARuntime != nullptr);
  423. return *CUDARuntime;
  424. }
  425. ARCEntrypoints &getARCEntrypoints() const {
  426. assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr);
  427. return *ARCData;
  428. }
  429. RREntrypoints &getRREntrypoints() const {
  430. assert(RRData != nullptr);
  431. return *RRData;
  432. }
  433. InstrProfStats &getPGOStats() { return PGOStats; }
  434. llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
  435. CoverageMappingModuleGen *getCoverageMapping() const {
  436. return CoverageMapping.get();
  437. }
  438. llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
  439. return StaticLocalDeclMap[D];
  440. }
  441. void setStaticLocalDeclAddress(const VarDecl *D,
  442. llvm::Constant *C) {
  443. StaticLocalDeclMap[D] = C;
  444. }
  445. llvm::Constant *
  446. getOrCreateStaticVarDecl(const VarDecl &D,
  447. llvm::GlobalValue::LinkageTypes Linkage);
  448. llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
  449. return StaticLocalDeclGuardMap[D];
  450. }
  451. void setStaticLocalDeclGuardAddress(const VarDecl *D,
  452. llvm::GlobalVariable *C) {
  453. StaticLocalDeclGuardMap[D] = C;
  454. }
  455. bool lookupRepresentativeDecl(StringRef MangledName,
  456. GlobalDecl &Result) const;
  457. llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
  458. return AtomicSetterHelperFnMap[Ty];
  459. }
  460. void setAtomicSetterHelperFnMap(QualType Ty,
  461. llvm::Constant *Fn) {
  462. AtomicSetterHelperFnMap[Ty] = Fn;
  463. }
  464. llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
  465. return AtomicGetterHelperFnMap[Ty];
  466. }
  467. void setAtomicGetterHelperFnMap(QualType Ty,
  468. llvm::Constant *Fn) {
  469. AtomicGetterHelperFnMap[Ty] = Fn;
  470. }
  471. llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
  472. return TypeDescriptorMap[Ty];
  473. }
  474. void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
  475. TypeDescriptorMap[Ty] = C;
  476. }
  477. CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
  478. llvm::MDNode *getNoObjCARCExceptionsMetadata() {
  479. if (!NoObjCARCExceptionsMetadata)
  480. NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
  481. return NoObjCARCExceptionsMetadata;
  482. }
  483. ASTContext &getContext() const { return Context; }
  484. const LangOptions &getLangOpts() const { return LangOpts; }
  485. const HeaderSearchOptions &getHeaderSearchOpts()
  486. const { return HeaderSearchOpts; }
  487. const PreprocessorOptions &getPreprocessorOpts()
  488. const { return PreprocessorOpts; }
  489. const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
  490. llvm::Module &getModule() const { return TheModule; }
  491. DiagnosticsEngine &getDiags() const { return Diags; }
  492. const llvm::DataLayout &getDataLayout() const {
  493. return TheModule.getDataLayout();
  494. }
  495. const TargetInfo &getTarget() const { return Target; }
  496. const llvm::Triple &getTriple() const;
  497. bool supportsCOMDAT() const;
  498. void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
  499. CGCXXABI &getCXXABI() const { return *ABI; }
  500. llvm::LLVMContext &getLLVMContext() { return VMContext; }
  501. bool shouldUseTBAA() const { return TBAA != nullptr; }
  502. const TargetCodeGenInfo &getTargetCodeGenInfo();
  503. CodeGenTypes &getTypes() { return Types; }
  504. CodeGenVTables &getVTables() { return VTables; }
  505. ItaniumVTableContext &getItaniumVTableContext() {
  506. return VTables.getItaniumVTableContext();
  507. }
  508. MicrosoftVTableContext &getMicrosoftVTableContext() {
  509. return VTables.getMicrosoftVTableContext();
  510. }
  511. CtorList &getGlobalCtors() { return GlobalCtors; }
  512. CtorList &getGlobalDtors() { return GlobalDtors; }
  513. llvm::MDNode *getTBAAInfo(QualType QTy);
  514. llvm::MDNode *getTBAAInfoForVTablePtr();
  515. llvm::MDNode *getTBAAStructInfo(QualType QTy);
  516. /// Return the MDNode in the type DAG for the given struct type.
  517. llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
  518. /// Return the path-aware tag for given base type, access node and offset.
  519. llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
  520. uint64_t O);
  521. bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
  522. bool isPaddedAtomicType(QualType type);
  523. bool isPaddedAtomicType(const AtomicType *type);
  524. /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
  525. /// is the same as the type. For struct-path aware TBAA, the tag
  526. /// is different from the type: base type, access type and offset.
  527. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  528. void DecorateInstruction(llvm::Instruction *Inst,
  529. llvm::MDNode *TBAAInfo,
  530. bool ConvertTypeToTag = true);
  531. /// Emit the given number of characters as a value of type size_t.
  532. llvm::ConstantInt *getSize(CharUnits numChars);
  533. /// Set the visibility for the given LLVM GlobalValue.
  534. void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
  535. /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
  536. /// variable declaration D.
  537. void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
  538. static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
  539. switch (V) {
  540. case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
  541. case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
  542. case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
  543. }
  544. llvm_unreachable("unknown visibility!");
  545. }
  546. llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition = false);
  547. /// Will return a global variable of the given type. If a variable with a
  548. /// different type already exists then a new variable with the right type
  549. /// will be created and all uses of the old variable will be replaced with a
  550. /// bitcast to the new variable.
  551. llvm::GlobalVariable *
  552. CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
  553. llvm::GlobalValue::LinkageTypes Linkage);
  554. llvm::Function *
  555. CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
  556. SourceLocation Loc = SourceLocation(),
  557. bool TLS = false);
  558. /// Return the address space of the underlying global variable for D, as
  559. /// determined by its declaration. Normally this is the same as the address
  560. /// space of D's type, but in CUDA, address spaces are associated with
  561. /// declarations, not types.
  562. unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
  563. /// Return the llvm::Constant for the address of the given global variable.
  564. /// If Ty is non-null and if the global doesn't exist, then it will be greated
  565. /// with the specified type instead of whatever the normal requested type
  566. /// would be.
  567. llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
  568. llvm::Type *Ty = nullptr);
  569. /// Return the address of the given function. If Ty is non-null, then this
  570. /// function will use the specified type if it has to create it.
  571. llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0,
  572. bool ForVTable = false,
  573. bool DontDefer = false,
  574. bool IsForDefinition = false);
  575. /// Get the address of the RTTI descriptor for the given type.
  576. llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
  577. llvm::Constant *getAddrOfCXXCatchHandlerType(QualType Ty,
  578. QualType CatchHandlerType);
  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. /// Return the result of value-initializing the given type, i.e. a null
  734. /// expression of the given type. This is usually, but not always, an LLVM
  735. /// null constant.
  736. llvm::Constant *EmitNullConstant(QualType T);
  737. /// Return a null constant appropriate for zero-initializing a base class with
  738. /// the given type. This is usually, but not always, an LLVM null constant.
  739. llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
  740. /// Emit a general error that something can't be done.
  741. void Error(SourceLocation loc, StringRef error);
  742. /// Print out an error that codegen doesn't support the specified stmt yet.
  743. void ErrorUnsupported(const Stmt *S, const char *Type);
  744. /// Print out an error that codegen doesn't support the specified decl yet.
  745. void ErrorUnsupported(const Decl *D, const char *Type);
  746. /// Set the attributes on the LLVM function for the given decl and function
  747. /// info. This applies attributes necessary for handling the ABI as well as
  748. /// user specified attributes like section.
  749. void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
  750. const CGFunctionInfo &FI);
  751. /// Set the LLVM function attributes (sext, zext, etc).
  752. void SetLLVMFunctionAttributes(const Decl *D,
  753. const CGFunctionInfo &Info,
  754. llvm::Function *F);
  755. /// Set the LLVM function attributes which only apply to a function
  756. /// definition.
  757. void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
  758. /// Return true iff the given type uses 'sret' when used as a return type.
  759. bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
  760. /// Return true iff the given type uses an argument slot when 'sret' is used
  761. /// as a return type.
  762. bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
  763. /// Return true iff the given type uses 'fpret' when used as a return type.
  764. bool ReturnTypeUsesFPRet(QualType ResultType);
  765. /// Return true iff the given type uses 'fp2ret' when used as a return type.
  766. bool ReturnTypeUsesFP2Ret(QualType ResultType);
  767. /// Get the LLVM attributes and calling convention to use for a particular
  768. /// function type.
  769. ///
  770. /// \param Info - The function type information.
  771. /// \param TargetDecl - The decl these attributes are being constructed
  772. /// for. If supplied the attributes applied to this decl may contribute to the
  773. /// function attributes and calling convention.
  774. /// \param PAL [out] - On return, the attribute list to use.
  775. /// \param CallingConv [out] - On return, the LLVM calling convention to use.
  776. void ConstructAttributeList(const CGFunctionInfo &Info,
  777. const Decl *TargetDecl,
  778. AttributeListType &PAL,
  779. unsigned &CallingConv,
  780. bool AttrOnCallSite);
  781. StringRef getMangledName(GlobalDecl GD);
  782. StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
  783. void EmitTentativeDefinition(const VarDecl *D);
  784. void EmitVTable(CXXRecordDecl *Class);
  785. /// Emit the RTTI descriptors for the builtin types.
  786. void EmitFundamentalRTTIDescriptors();
  787. /// \brief Appends Opts to the "Linker Options" metadata value.
  788. void AppendLinkerOptions(StringRef Opts);
  789. /// \brief Appends a detect mismatch command to the linker options.
  790. void AddDetectMismatch(StringRef Name, StringRef Value);
  791. /// \brief Appends a dependent lib to the "Linker Options" metadata value.
  792. void AddDependentLib(StringRef Lib);
  793. llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
  794. void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
  795. F->setLinkage(getFunctionLinkage(GD));
  796. }
  797. /// Set the DLL storage class on F.
  798. void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
  799. /// Return the appropriate linkage for the vtable, VTT, and type information
  800. /// of the given class.
  801. llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
  802. /// Return the store size, in character units, of the given LLVM type.
  803. CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
  804. /// Returns LLVM linkage for a declarator.
  805. llvm::GlobalValue::LinkageTypes
  806. getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
  807. bool IsConstantVariable);
  808. /// Returns LLVM linkage for a declarator.
  809. llvm::GlobalValue::LinkageTypes
  810. getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
  811. /// Emit all the global annotations.
  812. void EmitGlobalAnnotations();
  813. /// Emit an annotation string.
  814. llvm::Constant *EmitAnnotationString(StringRef Str);
  815. /// Emit the annotation's translation unit.
  816. llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
  817. /// Emit the annotation line number.
  818. llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
  819. /// Generate the llvm::ConstantStruct which contains the annotation
  820. /// information for a given GlobalValue. The annotation struct is
  821. /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
  822. /// GlobalValue being annotated. The second field is the constant string
  823. /// created from the AnnotateAttr's annotation. The third field is a constant
  824. /// string containing the name of the translation unit. The fourth field is
  825. /// the line number in the file of the annotated value declaration.
  826. llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
  827. const AnnotateAttr *AA,
  828. SourceLocation L);
  829. /// Add global annotations that are set on D, for the global GV. Those
  830. /// annotations are emitted during finalization of the LLVM code.
  831. void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
  832. bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
  833. bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
  834. QualType Ty,
  835. StringRef Category = StringRef()) const;
  836. SanitizerMetadata *getSanitizerMetadata() {
  837. return SanitizerMD.get();
  838. }
  839. void addDeferredVTable(const CXXRecordDecl *RD) {
  840. DeferredVTables.push_back(RD);
  841. }
  842. /// Emit code for a singal global function or var decl. Forward declarations
  843. /// are emitted lazily.
  844. void EmitGlobal(GlobalDecl D);
  845. bool
  846. HasTrivialDestructorBody(ASTContext &Context,
  847. const CXXRecordDecl *BaseClassDecl,
  848. const CXXRecordDecl *MostDerivedClassDecl);
  849. bool
  850. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  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. /// Returns whether the given record is blacklisted from control flow
  874. /// integrity checks.
  875. bool IsCFIBlacklistedRecord(const CXXRecordDecl *RD);
  876. /// Emit bit set entries for the given vtable using the given layout if
  877. /// vptr CFI is enabled.
  878. void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
  879. const VTableLayout &VTLayout);
  880. /// Create a metadata identifier for the given type. This may either be an
  881. /// MDString (for external identifiers) or a distinct unnamed MDNode (for
  882. /// internal identifiers).
  883. llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
  884. /// Create a bitset entry for the given vtable.
  885. llvm::MDTuple *CreateVTableBitSetEntry(llvm::GlobalVariable *VTable,
  886. CharUnits Offset,
  887. const CXXRecordDecl *RD);
  888. /// \breif Get the declaration of std::terminate for the platform.
  889. llvm::Constant *getTerminateFn();
  890. private:
  891. llvm::Constant *
  892. GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
  893. bool ForVTable, bool DontDefer = false,
  894. bool IsThunk = false,
  895. llvm::AttributeSet ExtraAttrs = llvm::AttributeSet(),
  896. bool IsForDefinition = false);
  897. llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
  898. llvm::PointerType *PTy,
  899. const VarDecl *D);
  900. void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
  901. /// Set function attributes for a function declaration.
  902. void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  903. bool IsIncompleteFunction, bool IsThunk);
  904. void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
  905. void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
  906. void EmitGlobalVarDefinition(const VarDecl *D);
  907. void EmitAliasDefinition(GlobalDecl GD);
  908. void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
  909. void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
  910. // C++ related functions.
  911. void EmitNamespace(const NamespaceDecl *D);
  912. void EmitLinkageSpec(const LinkageSpecDecl *D);
  913. void CompleteDIClassType(const CXXMethodDecl* D);
  914. /// \brief Emit the function that initializes C++ thread_local variables.
  915. void EmitCXXThreadLocalInitFunc();
  916. /// Emit the function that initializes C++ globals.
  917. void EmitCXXGlobalInitFunc();
  918. /// Emit the function that destroys C++ globals.
  919. void EmitCXXGlobalDtorFunc();
  920. /// Emit the function that initializes the specified global (if PerformInit is
  921. /// true) and registers its destructor.
  922. void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
  923. llvm::GlobalVariable *Addr,
  924. bool PerformInit);
  925. void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
  926. llvm::Function *InitFunc, InitSegAttr *ISA);
  927. // FIXME: Hardcoding priority here is gross.
  928. void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
  929. llvm::Constant *AssociatedData = 0);
  930. void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
  931. /// Generates a global array of functions and priorities using the given list
  932. /// and name. This array will have appending linkage and is suitable for use
  933. /// as a LLVM constructor or destructor array.
  934. void EmitCtorList(const CtorList &Fns, const char *GlobalName);
  935. /// Emit the RTTI descriptors for the given type.
  936. void EmitFundamentalRTTIDescriptor(QualType Type);
  937. /// Emit any needed decls for which code generation was deferred.
  938. void EmitDeferred();
  939. /// Call replaceAllUsesWith on all pairs in Replacements.
  940. void applyReplacements();
  941. /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
  942. void applyGlobalValReplacements();
  943. void checkAliases();
  944. /// Emit any vtables which we deferred and still have a use for.
  945. void EmitDeferredVTables();
  946. /// Emit the llvm.used and llvm.compiler.used metadata.
  947. void emitLLVMUsed();
  948. /// \brief Emit the link options introduced by imported modules.
  949. void EmitModuleLinkOptions();
  950. /// \brief Emit aliases for internal-linkage declarations inside "C" language
  951. /// linkage specifications, giving them the "expected" name where possible.
  952. void EmitStaticExternCAliases();
  953. void EmitDeclMetadata();
  954. /// \brief Emit the Clang version as llvm.ident metadata.
  955. void EmitVersionIdentMetadata();
  956. /// Emits target specific Metadata for global declarations.
  957. void EmitTargetMetadata();
  958. /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
  959. /// .gcda files in a way that persists in .bc files.
  960. void EmitCoverageFile();
  961. /// Emits the initializer for a uuidof string.
  962. llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
  963. /// Determine whether the definition must be emitted; if this returns \c
  964. /// false, the definition can be emitted lazily if it's used.
  965. bool MustBeEmitted(const ValueDecl *D);
  966. /// Determine whether the definition can be emitted eagerly, or should be
  967. /// delayed until the end of the translation unit. This is relevant for
  968. /// definitions whose linkage can change, e.g. implicit function instantions
  969. /// which may later be explicitly instantiated.
  970. bool MayBeEmittedEagerly(const ValueDecl *D);
  971. /// Check whether we can use a "simpler", more core exceptions personality
  972. /// function.
  973. void SimplifyPersonality();
  974. };
  975. } // end namespace CodeGen
  976. } // end namespace clang
  977. #endif