CodeGenModule.h 58 KB

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