CodeGenModule.h 53 KB

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