CodeGenModule.h 48 KB

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