]> granicus.if.org Git - clang/commitdiff
When calling a virtual member function on a base class and the most derived class...
authorAnders Carlsson <andersca@mac.com>
Sat, 29 Jan 2011 03:52:01 +0000 (03:52 +0000)
committerAnders Carlsson <andersca@mac.com>
Sat, 29 Jan 2011 03:52:01 +0000 (03:52 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@124524 91177308-0d34-0410-b5e6-96231b3b80d8

lib/CodeGen/CGExprCXX.cpp
test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp

index 03b90e2587a9eceb81730a938a64e7ac6bc65cc4..fa6ac5469f8c49957e34c5331db69d7be7c5c401 100644 (file)
@@ -53,16 +53,39 @@ RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
                   Callee, ReturnValue, Args, MD);
 }
 
+static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
+  QualType DerivedType = Base->IgnoreParenCasts()->getType();
+  if (const PointerType *PTy = DerivedType->getAs<PointerType>())
+    DerivedType = PTy->getPointeeType();
+
+  return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
+}
+
 /// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
 /// expr can be devirtualized.
 static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
                                                const Expr *Base, 
                                                const CXXMethodDecl *MD) {
   
-  // Cannot divirtualize in kext mode.
+  // When building with -fapple-kext, all calls must go through the vtable since
+  // the kernel linker can do runtime patching of vtables.
   if (Context.getLangOptions().AppleKext)
     return false;
 
+  // If the most derived class is marked final, we know that no subclass can
+  // override this member function and so we can devirtualize it. For example:
+  //
+  // struct A { virtual void f(); }
+  // struct B final : A { };
+  //
+  // void f(B *b) {
+  //   b->f();
+  // }
+  //
+  const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
+  if (MostDerivedClassDecl->hasAttr<FinalAttr>())
+    return true;
+
   // If the member function is marked 'final', we know that it can't be
   // overridden and can therefore devirtualize it.
   if (MD->hasAttr<FinalAttr>())
index f6f2a491339cf3d794fb8912a90e8b093748dbbd..08a94903d5261046899f45769097bdf10ee4f52b 100644 (file)
@@ -23,3 +23,17 @@ namespace Test2 {
     return a->f();
   }
 }
+
+namespace Test3 {
+  struct A {
+    virtual int f();
+  };
+
+  struct B final : A { };
+
+  // CHECK: define i32 @_ZN5Test31fEPNS_1BE
+  int f(B *b) {
+    // CHECK: call i32 @_ZN5Test31A1fEv
+    return b->f();
+  }
+}