1 //===--- CodeGenTypes.h - Type translation 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 code that handles AST -> LLVM type lowering.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENTYPES_H
14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENTYPES_H
15 
16 #include "CGCall.h"
17 #include "clang/Basic/ABI.h"
18 #include "clang/CodeGen/CGFunctionInfo.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/IR/Module.h"
21 
22 namespace llvm {
23 class FunctionType;
24 class DataLayout;
25 class Type;
26 class LLVMContext;
27 class StructType;
28 }
29 
30 namespace clang {
31 class ASTContext;
32 template <typename> class CanQual;
33 class CXXConstructorDecl;
34 class CXXMethodDecl;
35 class CodeGenOptions;
36 class FunctionProtoType;
37 class QualType;
38 class RecordDecl;
39 class TagDecl;
40 class TargetInfo;
41 class Type;
42 typedef CanQual<Type> CanQualType;
43 class GlobalDecl;
44 
45 namespace CodeGen {
46 class ABIInfo;
47 class CGCXXABI;
48 class CGRecordLayout;
49 class CodeGenModule;
50 class RequiredArgs;
51 
52 /// This class organizes the cross-module state that is used while lowering
53 /// AST types to LLVM types.
54 class CodeGenTypes {
55   CodeGenModule &CGM;
56   // Some of this stuff should probably be left on the CGM.
57   ASTContext &Context;
58   llvm::Module &TheModule;
59   const TargetInfo &Target;
60   CGCXXABI &TheCXXABI;
61 
62   // This should not be moved earlier, since its initialization depends on some
63   // of the previous reference members being already initialized
64   const ABIInfo &TheABIInfo;
65 
66   /// The opaque type map for Objective-C interfaces. All direct
67   /// manipulation is done by the runtime interfaces, which are
68   /// responsible for coercing to the appropriate type; these opaque
69   /// types are never refined.
70   llvm::DenseMap<const ObjCInterfaceType*, llvm::Type *> InterfaceTypes;
71 
72   /// Maps clang struct type with corresponding record layout info.
73   llvm::DenseMap<const Type*, std::unique_ptr<CGRecordLayout>> CGRecordLayouts;
74 
75   /// Contains the LLVM IR type for any converted RecordDecl.
76   llvm::DenseMap<const Type*, llvm::StructType *> RecordDeclTypes;
77 
78   /// Hold memoized CGFunctionInfo results.
79   llvm::FoldingSet<CGFunctionInfo> FunctionInfos;
80 
81   /// This set keeps track of records that we're currently converting
82   /// to an IR type.  For example, when converting:
83   /// struct A { struct B { int x; } } when processing 'x', the 'A' and 'B'
84   /// types will be in this set.
85   llvm::SmallPtrSet<const Type*, 4> RecordsBeingLaidOut;
86 
87   llvm::SmallPtrSet<const CGFunctionInfo*, 4> FunctionsBeingProcessed;
88 
89   /// True if we didn't layout a function due to a being inside
90   /// a recursive struct conversion, set this to true.
91   bool SkippedLayout;
92 
93   SmallVector<const RecordDecl *, 8> DeferredRecords;
94 
95   /// This map keeps cache of llvm::Types and maps clang::Type to
96   /// corresponding llvm::Type.
97   llvm::DenseMap<const Type *, llvm::Type *> TypeCache;
98 
99   llvm::SmallSet<const Type *, 8> RecordsWithOpaqueMemberPointers;
100 
101   /// Helper for ConvertType.
102   llvm::Type *ConvertFunctionTypeInternal(QualType FT);
103 
104 public:
105   CodeGenTypes(CodeGenModule &cgm);
106   ~CodeGenTypes();
107 
108   const llvm::DataLayout &getDataLayout() const {
109     return TheModule.getDataLayout();
110   }
111   ASTContext &getContext() const { return Context; }
112   const ABIInfo &getABIInfo() const { return TheABIInfo; }
113   const TargetInfo &getTarget() const { return Target; }
114   CGCXXABI &getCXXABI() const { return TheCXXABI; }
115   llvm::LLVMContext &getLLVMContext() { return TheModule.getContext(); }
116   const CodeGenOptions &getCodeGenOpts() const;
117 
118   /// Convert clang calling convention to LLVM callilng convention.
119   unsigned ClangCallConvToLLVMCallConv(CallingConv CC);
120 
121   /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
122   /// qualification.
123   CanQualType DeriveThisType(const CXXRecordDecl *RD, const CXXMethodDecl *MD);
124 
125   /// ConvertType - Convert type T into a llvm::Type.
126   llvm::Type *ConvertType(QualType T);
127 
128   /// ConvertTypeForMem - Convert type T into a llvm::Type.  This differs from
129   /// ConvertType in that it is used to convert to the memory representation for
130   /// a type.  For example, the scalar representation for _Bool is i1, but the
131   /// memory representation is usually i8 or i32, depending on the target.
132   llvm::Type *ConvertTypeForMem(QualType T, bool ForBitField = false);
133 
134   /// GetFunctionType - Get the LLVM function type for \arg Info.
135   llvm::FunctionType *GetFunctionType(const CGFunctionInfo &Info);
136 
137   llvm::FunctionType *GetFunctionType(GlobalDecl GD);
138 
139   /// isFuncTypeConvertible - Utility to check whether a function type can
140   /// be converted to an LLVM type (i.e. doesn't depend on an incomplete tag
141   /// type).
142   bool isFuncTypeConvertible(const FunctionType *FT);
143   bool isFuncParamTypeConvertible(QualType Ty);
144 
145   /// Determine if a C++ inheriting constructor should have parameters matching
146   /// those of its inherited constructor.
147   bool inheritingCtorHasParams(const InheritedConstructor &Inherited,
148                                CXXCtorType Type);
149 
150   /// GetFunctionTypeForVTable - Get the LLVM function type for use in a vtable,
151   /// given a CXXMethodDecl. If the method to has an incomplete return type,
152   /// and/or incomplete argument types, this will return the opaque type.
153   llvm::Type *GetFunctionTypeForVTable(GlobalDecl GD);
154 
155   const CGRecordLayout &getCGRecordLayout(const RecordDecl*);
156 
157   /// UpdateCompletedType - When we find the full definition for a TagDecl,
158   /// replace the 'opaque' type we previously made for it if applicable.
159   void UpdateCompletedType(const TagDecl *TD);
160 
161   /// Remove stale types from the type cache when an inheritance model
162   /// gets assigned to a class.
163   void RefreshTypeCacheForClass(const CXXRecordDecl *RD);
164 
165   // The arrangement methods are split into three families:
166   //   - those meant to drive the signature and prologue/epilogue
167   //     of a function declaration or definition,
168   //   - those meant for the computation of the LLVM type for an abstract
169   //     appearance of a function, and
170   //   - those meant for performing the IR-generation of a call.
171   // They differ mainly in how they deal with optional (i.e. variadic)
172   // arguments, as well as unprototyped functions.
173   //
174   // Key points:
175   // - The CGFunctionInfo for emitting a specific call site must include
176   //   entries for the optional arguments.
177   // - The function type used at the call site must reflect the formal
178   //   signature of the declaration being called, or else the call will
179   //   go awry.
180   // - For the most part, unprototyped functions are called by casting to
181   //   a formal signature inferred from the specific argument types used
182   //   at the call-site.  However, some targets (e.g. x86-64) screw with
183   //   this for compatibility reasons.
184 
185   const CGFunctionInfo &arrangeGlobalDeclaration(GlobalDecl GD);
186 
187   /// Given a function info for a declaration, return the function info
188   /// for a call with the given arguments.
189   ///
190   /// Often this will be able to simply return the declaration info.
191   const CGFunctionInfo &arrangeCall(const CGFunctionInfo &declFI,
192                                     const CallArgList &args);
193 
194   /// Free functions are functions that are compatible with an ordinary
195   /// C function pointer type.
196   const CGFunctionInfo &arrangeFunctionDeclaration(const FunctionDecl *FD);
197   const CGFunctionInfo &arrangeFreeFunctionCall(const CallArgList &Args,
198                                                 const FunctionType *Ty,
199                                                 bool ChainCall);
200   const CGFunctionInfo &arrangeFreeFunctionType(CanQual<FunctionProtoType> Ty);
201   const CGFunctionInfo &arrangeFreeFunctionType(CanQual<FunctionNoProtoType> Ty);
202 
203   /// A nullary function is a freestanding function of type 'void ()'.
204   /// This method works for both calls and declarations.
205   const CGFunctionInfo &arrangeNullaryFunction();
206 
207   /// A builtin function is a freestanding function using the default
208   /// C conventions.
209   const CGFunctionInfo &
210   arrangeBuiltinFunctionDeclaration(QualType resultType,
211                                     const FunctionArgList &args);
212   const CGFunctionInfo &
213   arrangeBuiltinFunctionDeclaration(CanQualType resultType,
214                                     ArrayRef<CanQualType> argTypes);
215   const CGFunctionInfo &arrangeBuiltinFunctionCall(QualType resultType,
216                                                    const CallArgList &args);
217 
218   /// Objective-C methods are C functions with some implicit parameters.
219   const CGFunctionInfo &arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD);
220   const CGFunctionInfo &arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
221                                                         QualType receiverType);
222   const CGFunctionInfo &arrangeUnprototypedObjCMessageSend(
223                                                      QualType returnType,
224                                                      const CallArgList &args);
225 
226   /// Block invocation functions are C functions with an implicit parameter.
227   const CGFunctionInfo &arrangeBlockFunctionDeclaration(
228                                                  const FunctionProtoType *type,
229                                                  const FunctionArgList &args);
230   const CGFunctionInfo &arrangeBlockFunctionCall(const CallArgList &args,
231                                                  const FunctionType *type);
232 
233   /// C++ methods have some special rules and also have implicit parameters.
234   const CGFunctionInfo &arrangeCXXMethodDeclaration(const CXXMethodDecl *MD);
235   const CGFunctionInfo &arrangeCXXStructorDeclaration(GlobalDecl GD);
236   const CGFunctionInfo &arrangeCXXConstructorCall(const CallArgList &Args,
237                                                   const CXXConstructorDecl *D,
238                                                   CXXCtorType CtorKind,
239                                                   unsigned ExtraPrefixArgs,
240                                                   unsigned ExtraSuffixArgs,
241                                                   bool PassProtoArgs = true);
242 
243   const CGFunctionInfo &arrangeCXXMethodCall(const CallArgList &args,
244                                              const FunctionProtoType *type,
245                                              RequiredArgs required,
246                                              unsigned numPrefixArgs);
247   const CGFunctionInfo &
248   arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD);
249   const CGFunctionInfo &arrangeMSCtorClosure(const CXXConstructorDecl *CD,
250                                                  CXXCtorType CT);
251   const CGFunctionInfo &arrangeCXXMethodType(const CXXRecordDecl *RD,
252                                              const FunctionProtoType *FTP,
253                                              const CXXMethodDecl *MD);
254 
255   /// "Arrange" the LLVM information for a call or type with the given
256   /// signature.  This is largely an internal method; other clients
257   /// should use one of the above routines, which ultimately defer to
258   /// this.
259   ///
260   /// \param argTypes - must all actually be canonical as params
261   const CGFunctionInfo &arrangeLLVMFunctionInfo(CanQualType returnType,
262                                                 bool instanceMethod,
263                                                 bool chainCall,
264                                                 ArrayRef<CanQualType> argTypes,
265                                                 FunctionType::ExtInfo info,
266                     ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
267                                                 RequiredArgs args);
268 
269   /// Compute a new LLVM record layout object for the given record.
270   std::unique_ptr<CGRecordLayout> ComputeRecordLayout(const RecordDecl *D,
271                                                       llvm::StructType *Ty);
272 
273   /// addRecordTypeName - Compute a name from the given record decl with an
274   /// optional suffix and name the given LLVM type using it.
275   void addRecordTypeName(const RecordDecl *RD, llvm::StructType *Ty,
276                          StringRef suffix);
277 
278 
279 public:  // These are internal details of CGT that shouldn't be used externally.
280   /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
281   llvm::StructType *ConvertRecordDeclType(const RecordDecl *TD);
282 
283   /// getExpandedTypes - Expand the type \arg Ty into the LLVM
284   /// argument types it would be passed as. See ABIArgInfo::Expand.
285   void getExpandedTypes(QualType Ty,
286                         SmallVectorImpl<llvm::Type *>::iterator &TI);
287 
288   /// IsZeroInitializable - Return whether a type can be
289   /// zero-initialized (in the C++ sense) with an LLVM zeroinitializer.
290   bool isZeroInitializable(QualType T);
291 
292   /// Check if the pointer type can be zero-initialized (in the C++ sense)
293   /// with an LLVM zeroinitializer.
294   bool isPointerZeroInitializable(QualType T);
295 
296   /// IsZeroInitializable - Return whether a record type can be
297   /// zero-initialized (in the C++ sense) with an LLVM zeroinitializer.
298   bool isZeroInitializable(const RecordDecl *RD);
299 
300   bool isRecordLayoutComplete(const Type *Ty) const;
301   bool noRecordsBeingLaidOut() const {
302     return RecordsBeingLaidOut.empty();
303   }
304   bool isRecordBeingLaidOut(const Type *Ty) const {
305     return RecordsBeingLaidOut.count(Ty);
306   }
307 
308 };
309 
310 }  // end namespace CodeGen
311 }  // end namespace clang
312 
313 #endif
314