CodeGenModule.h 52 KB

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