1 //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
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 contains code dealing with C++ code generation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 // We might split this into multiple files if it gets too unwieldy
15 
16 #include "CodeGenModule.h"
17 #include "CGCXXABI.h"
18 #include "CodeGenFunction.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Frontend/CodeGenOptions.h"
27 #include "llvm/ADT/StringExtras.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 
32 /// Try to emit a base destructor as an alias to its primary
33 /// base-class destructor.
34 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
35   if (!getCodeGenOpts().CXXCtorDtorAliases)
36     return true;
37 
38   // Producing an alias to a base class ctor/dtor can degrade debug quality
39   // as the debugger cannot tell them apart.
40   if (getCodeGenOpts().OptimizationLevel == 0)
41     return true;
42 
43   // If sanitizing memory to check for use-after-dtor, do not emit as
44   //  an alias, unless this class owns no members.
45   if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
46       !D->getParent()->field_empty())
47     return true;
48 
49   // If the destructor doesn't have a trivial body, we have to emit it
50   // separately.
51   if (!D->hasTrivialBody())
52     return true;
53 
54   const CXXRecordDecl *Class = D->getParent();
55 
56   // We are going to instrument this destructor, so give up even if it is
57   // currently empty.
58   if (Class->mayInsertExtraPadding())
59     return true;
60 
61   // If we need to manipulate a VTT parameter, give up.
62   if (Class->getNumVBases()) {
63     // Extra Credit:  passing extra parameters is perfectly safe
64     // in many calling conventions, so only bail out if the ctor's
65     // calling convention is nonstandard.
66     return true;
67   }
68 
69   // If any field has a non-trivial destructor, we have to emit the
70   // destructor separately.
71   for (const auto *I : Class->fields())
72     if (I->getType().isDestructedType())
73       return true;
74 
75   // Try to find a unique base class with a non-trivial destructor.
76   const CXXRecordDecl *UniqueBase = nullptr;
77   for (const auto &I : Class->bases()) {
78 
79     // We're in the base destructor, so skip virtual bases.
80     if (I.isVirtual()) continue;
81 
82     // Skip base classes with trivial destructors.
83     const auto *Base =
84         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
85     if (Base->hasTrivialDestructor()) continue;
86 
87     // If we've already found a base class with a non-trivial
88     // destructor, give up.
89     if (UniqueBase) return true;
90     UniqueBase = Base;
91   }
92 
93   // If we didn't find any bases with a non-trivial destructor, then
94   // the base destructor is actually effectively trivial, which can
95   // happen if it was needlessly user-defined or if there are virtual
96   // bases with non-trivial destructors.
97   if (!UniqueBase)
98     return true;
99 
100   // If the base is at a non-zero offset, give up.
101   const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
102   if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
103     return true;
104 
105   // Give up if the calling conventions don't match. We could update the call,
106   // but it is probably not worth it.
107   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
108   if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
109       D->getType()->getAs<FunctionType>()->getCallConv())
110     return true;
111 
112   return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
113                                   GlobalDecl(BaseD, Dtor_Base),
114                                   false);
115 }
116 
117 /// Try to emit a definition as a global alias for another definition.
118 /// If \p InEveryTU is true, we know that an equivalent alias can be produced
119 /// in every translation unit.
120 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
121                                              GlobalDecl TargetDecl,
122                                              bool InEveryTU) {
123   if (!getCodeGenOpts().CXXCtorDtorAliases)
124     return true;
125 
126   // The alias will use the linkage of the referent.  If we can't
127   // support aliases with that linkage, fail.
128   llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
129 
130   // We can't use an alias if the linkage is not valid for one.
131   if (!llvm::GlobalAlias::isValidLinkage(Linkage))
132     return true;
133 
134   llvm::GlobalValue::LinkageTypes TargetLinkage =
135       getFunctionLinkage(TargetDecl);
136 
137   // available_externally definitions aren't real definitions, so we cannot
138   // create an alias to one.
139   if (TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage)
140     return true;
141 
142   // Check if we have it already.
143   StringRef MangledName = getMangledName(AliasDecl);
144   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
145   if (Entry && !Entry->isDeclaration())
146     return false;
147   if (Replacements.count(MangledName))
148     return false;
149 
150   // Derive the type for the alias.
151   llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
152   llvm::PointerType *AliasType = AliasValueType->getPointerTo();
153 
154   // Find the referent.  Some aliases might require a bitcast, in
155   // which case the caller is responsible for ensuring the soundness
156   // of these semantics.
157   auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
158   llvm::Constant *Aliasee = Ref;
159   if (Ref->getType() != AliasType)
160     Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
161 
162   // Instead of creating as alias to a linkonce_odr, replace all of the uses
163   // of the aliasee.
164   if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) {
165     addReplacement(MangledName, Aliasee);
166     return false;
167   }
168 
169   // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
170   // template instantiation or a dllexported class, avoid forming it on COFF.
171   // A COFF weak external alias cannot satisfy a normal undefined symbol
172   // reference from another TU. The other TU must also mark the referenced
173   // symbol as weak, which we cannot rely on.
174   if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
175       getTriple().isOSBinFormatCOFF()) {
176     return true;
177   }
178 
179   if (!InEveryTU) {
180     // If we don't have a definition for the destructor yet, don't
181     // emit.  We can't emit aliases to declarations; that's just not
182     // how aliases work.
183     if (Ref->isDeclaration())
184       return true;
185   }
186 
187   // Don't create an alias to a linker weak symbol. This avoids producing
188   // different COMDATs in different TUs. Another option would be to
189   // output the alias both for weak_odr and linkonce_odr, but that
190   // requires explicit comdat support in the IL.
191   if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
192     return true;
193 
194   // Create the alias with no name.
195   auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
196                                           Aliasee, &getModule());
197 
198   // Switch any previous uses to the alias.
199   if (Entry) {
200     assert(Entry->getType() == AliasType &&
201            "declaration exists with different type");
202     Alias->takeName(Entry);
203     Entry->replaceAllUsesWith(Alias);
204     Entry->eraseFromParent();
205   } else {
206     Alias->setName(MangledName);
207   }
208 
209   // Finally, set up the alias with its proper name and attributes.
210   setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
211 
212   return false;
213 }
214 
215 llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
216                                                   StructorType Type) {
217   const CGFunctionInfo &FnInfo =
218       getTypes().arrangeCXXStructorDeclaration(MD, Type);
219   auto *Fn = cast<llvm::Function>(
220       getAddrOfCXXStructor(MD, Type, &FnInfo, /*FnType=*/nullptr,
221                            /*DontDefer=*/true, /*IsForDefinition=*/true));
222 
223   GlobalDecl GD;
224   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
225     GD = GlobalDecl(DD, toCXXDtorType(Type));
226   } else {
227     const auto *CD = cast<CXXConstructorDecl>(MD);
228     GD = GlobalDecl(CD, toCXXCtorType(Type));
229   }
230 
231   setFunctionLinkage(GD, Fn);
232   setFunctionDLLStorageClass(GD, Fn);
233 
234   CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
235   setFunctionDefinitionAttributes(MD, Fn);
236   SetLLVMFunctionAttributesForDefinition(MD, Fn);
237   return Fn;
238 }
239 
240 llvm::Constant *CodeGenModule::getAddrOfCXXStructor(
241     const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
242     llvm::FunctionType *FnType, bool DontDefer, bool IsForDefinition) {
243   GlobalDecl GD;
244   if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
245     GD = GlobalDecl(CD, toCXXCtorType(Type));
246   } else {
247     GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
248   }
249 
250   if (!FnType) {
251     if (!FnInfo)
252       FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
253     FnType = getTypes().GetFunctionType(*FnInfo);
254   }
255 
256   return GetOrCreateLLVMFunction(
257       getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
258       /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeSet(), IsForDefinition);
259 }
260 
261 static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
262                                               GlobalDecl GD,
263                                               llvm::Type *Ty,
264                                               const CXXRecordDecl *RD) {
265   assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
266          "No kext in Microsoft ABI");
267   GD = GD.getCanonicalDecl();
268   CodeGenModule &CGM = CGF.CGM;
269   llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
270   Ty = Ty->getPointerTo()->getPointerTo();
271   VTable = CGF.Builder.CreateBitCast(VTable, Ty);
272   assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
273   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
274   uint64_t AddressPoint =
275     CGM.getItaniumVTableContext().getVTableLayout(RD)
276        .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
277   VTableIndex += AddressPoint;
278   llvm::Value *VFuncPtr =
279     CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
280   return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
281 }
282 
283 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
284 /// indirect call to virtual functions. It makes the call through indexing
285 /// into the vtable.
286 llvm::Value *
287 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
288                                   NestedNameSpecifier *Qual,
289                                   llvm::Type *Ty) {
290   assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
291          "BuildAppleKextVirtualCall - bad Qual kind");
292 
293   const Type *QTy = Qual->getAsType();
294   QualType T = QualType(QTy, 0);
295   const RecordType *RT = T->getAs<RecordType>();
296   assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
297   const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
298 
299   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
300     return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
301 
302   return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
303 }
304 
305 /// BuildVirtualCall - This routine makes indirect vtable call for
306 /// call to virtual destructors. It returns 0 if it could not do it.
307 llvm::Value *
308 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
309                                             const CXXDestructorDecl *DD,
310                                             CXXDtorType Type,
311                                             const CXXRecordDecl *RD) {
312   const auto *MD = cast<CXXMethodDecl>(DD);
313   // FIXME. Dtor_Base dtor is always direct!!
314   // It need be somehow inline expanded into the caller.
315   // -O does that. But need to support -O0 as well.
316   if (MD->isVirtual() && Type != Dtor_Base) {
317     // Compute the function type we're calling.
318     const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
319         DD, StructorType::Complete);
320     llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
321     return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
322   }
323   return nullptr;
324 }
325