64695d6
From d7c20ff3406ee048dd5d0ff812f9e8b3d48bb192 Mon Sep 17 00:00:00 2001
64695d6
From: =?UTF-8?q?Stefan=20B=C3=BChler?= <lighttpd@stbuehler.de>
64695d6
Date: Thu, 3 Dec 2015 14:51:50 +0100
64695d6
Subject: [PATCH 1/3] add gcc abi_tag support
64695d6
64695d6
<http://reviews.llvm.org/D12834?id=34645>
64695d6
---
64695d6
 docs/ItaniumMangleAbiTags.rst              |  90 +++++
64695d6
 include/clang/Basic/Attr.td                |   8 +
64695d6
 include/clang/Basic/DiagnosticSemaKinds.td |  10 +-
64695d6
 include/clang/Sema/AttributeList.h         |   3 +-
64695d6
 lib/AST/ItaniumMangle.cpp                  | 525 ++++++++++++++++++++++++-----
64695d6
 lib/Sema/SemaDeclAttr.cpp                  |  55 +++
64695d6
 6 files changed, 609 insertions(+), 82 deletions(-)
64695d6
 create mode 100644 docs/ItaniumMangleAbiTags.rst
64695d6
64695d6
diff --git a/docs/ItaniumMangleAbiTags.rst b/docs/ItaniumMangleAbiTags.rst
64695d6
new file mode 100644
64695d6
index 0000000..d390162
64695d6
--- /dev/null
64695d6
+++ b/tools/clang/docs/ItaniumMangleAbiTags.rst
64695d6
@@ -0,0 +1,90 @@
64695d6
+========
64695d6
+Abi Tags
64695d6
+========
64695d6
+
64695d6
+Introduction
64695d6
+============
64695d6
+
64695d6
+This text tries to describe gcc semantic for mangling "abi_tag" attributes
64695d6
+described in https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
64695d6
+
64695d6
+There is no guarantee the following rules are correct, complete or make sense
64695d6
+in any way as they were determined empirically by experiments with gcc5.
64695d6
+
64695d6
+Declaration
64695d6
+===========
64695d6
+
64695d6
+Abi tags are declared in an abi_tag attribute and can be applied to a
64695d6
+function, variable, class or inline namespace declaration. The attribute takes
64695d6
+one or more strings (called tags); the order does not matter.
64695d6
+
64695d6
+See https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html for
64695d6
+details.
64695d6
+
64695d6
+Tags on an inline namespace are called "implicit tags", all other tags are
64695d6
+"explicit tags".
64695d6
+
64695d6
+Mangling
64695d6
+========
64695d6
+
64695d6
+All tags that are "active" on a <unqualified-name> are emitted after the
64695d6
+<unqualified-name>, before <template-args> or <discriminator>, and are part of
64695d6
+the same <substitution> the <unqualified-name> is.
64695d6
+
64695d6
+They are mangled as:
64695d6
+
64695d6
+    <abi-tags> ::= <abi-tag>*   # sort by name
64695d6
+    <abi-tag> ::= B <tag source-name>
64695d6
+
64695d6
+Example:
64695d6
+
64695d6
+    __attribute__((abi_tag("test")))
64695d6
+    void Func();
64695d6
+
64695d6
+    gets mangled as: _Z4FuncB4testv (prettified as `Func[abi:test]()`)
64695d6
+
64695d6
+Active tags
64695d6
+===========
64695d6
+
64695d6
+A namespace has never any active tags; for types (class / struct / union /
64695d6
+enum) the explicit tags are the active tags.
64695d6
+
64695d6
+For variables and functions the active tags are the explicit tags plus any
64695d6
+"required tags" which are not in the "available tags" set:
64695d6
+
64695d6
+    derived-tags := (required-tags - available-tags)
64695d6
+    active-tags := explicit-tags + derived-tags
64695d6
+
64695d6
+Required tags for a function
64695d6
+============================
64695d6
+
64695d6
+If a function is used as a local scope for another name, and is part of
64695d6
+another function as local scope, it doesn't have any required tags.
64695d6
+
64695d6
+If a function is used as a local scope for a guard variable name, it doesn't
64695d6
+have any required tags.
64695d6
+
64695d6
+Otherwise the function requires any implicit or explicit tag used in the name
64695d6
+for the return type.
64695d6
+
64695d6
+Required tags for a variable
64695d6
+============================
64695d6
+
64695d6
+A variable requires any implicit or explicit tag used in its type.
64695d6
+
64695d6
+Available tags
64695d6
+==============
64695d6
+
64695d6
+All tags used in the prefix and in the template arguments for a name are
64695d6
+available; for functions also all  tags from the <bare-function-type> (which
64695d6
+might include the return type for template functions) are available.
64695d6
+
64695d6
+For <local-name>s all active tags used in the local part (
64695d6
+encoding>) are available, but not implicit tags which were not active!
64695d6
+
64695d6
+Implicit and explicit tags used in the <unqualified-name> for a function (as
64695d6
+in the type of a cast operator) are NOT available.
64695d6
+
64695d6
+Example: a cast operator to std::string (which is
64695d6
+std::__cxx11::basic_string<...>) will use 'cxx11' as active tag, as it is
64695d6
+required from the return type `std::string` but not available.
64695d6
diff --git a/include/clang/Basic/Attr.td b/include/clang/Basic/Attr.td
64695d6
index 6187bcb..c54ab34 100644
64695d6
--- a/tools/clang/include/clang/Basic/Attr.td
64695d6
+++ b/tools/clang/include/clang/Basic/Attr.td
64695d6
@@ -338,6 +338,14 @@ class IgnoredAttr : Attr {
64695d6
 // Attributes begin here
64695d6
 //
64695d6
 
64695d6
+def AbiTag : Attr {
64695d6
+  let Spellings = [GCC<"abi_tag">];
64695d6
+  let Args = [VariadicStringArgument<"Tags">];
64695d6
+  let Subjects = SubjectList<[Struct, Var, Function, Namespace], ErrorDiag,
64695d6
+                             "ExpectedStructClassVariableFunctionMethodOrInlineNamespace">;
64695d6
+  let Documentation = [Undocumented];
64695d6
+}
64695d6
+
64695d6
 def AddressSpace : TypeAttr {
64695d6
   let Spellings = [GNU<"address_space">];
64695d6
   let Args = [IntArgument<"AddressSpace">];
64695d6
diff --git a/include/clang/Basic/DiagnosticSemaKinds.td b/include/clang/Basic/DiagnosticSemaKinds.td
64695d6
index 82f5121..973456e 100644
64695d6
--- a/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td
64695d6
+++ b/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td
64695d6
@@ -2323,7 +2323,8 @@ def warn_attribute_wrong_decl_type : Warning<
64695d6
   "Objective-C instance methods|init methods of interface or class extension declarations|"
64695d6
   "variables, functions and classes|Objective-C protocols|"
64695d6
   "functions and global variables|structs, unions, and typedefs|structs and typedefs|"
64695d6
-  "interface or protocol declarations|kernel functions}1">,
64695d6
+  "interface or protocol declarations|kernel functions|"
64695d6
+  "structs, classes, variables, functions, methods and inline namespaces}1">,
64695d6
   InGroup<IgnoredAttributes>;
64695d6
 def err_attribute_wrong_decl_type : Error<warn_attribute_wrong_decl_type.Text>;
64695d6
 def warn_type_attribute_wrong_type : Warning<
64695d6
@@ -3997,6 +3998,13 @@ def err_definition_of_explicitly_defaulted_member : Error<
64695d6
 def err_redefinition_extern_inline : Error<
64695d6
   "redefinition of a 'extern inline' function %0 is not supported in "
64695d6
   "%select{C99 mode|C++}1">;
64695d6
+def err_attr_abi_tag_only_on_inline_namespace :
64695d6
+  Error<"abi_tag attribute only allowed on inline namespaces">;
64695d6
+def err_abi_tag_on_redeclaration :
64695d6
+  Error<"cannot add abi_tag attribute in redeclaration">;
64695d6
+def err_new_abi_tag_on_redeclaration :
64695d6
+  Error<"abi_tag %0 missing in original declaration">;
64695d6
+
64695d6
 
64695d6
 def note_deleted_dtor_no_operator_delete : Note<
64695d6
   "virtual destructor requires an unambiguous, accessible 'operator delete'">;
64695d6
diff --git a/include/clang/Sema/AttributeList.h b/include/clang/Sema/AttributeList.h
64695d6
index 4d18633..b3a9333 100644
64695d6
--- a/tools/clang/include/clang/Sema/AttributeList.h
64695d6
+++ b/tools/clang/include/clang/Sema/AttributeList.h
64695d6
@@ -854,7 +854,8 @@ enum AttributeDeclKind {
64695d6
   ExpectedStructOrUnionOrTypedef,
64695d6
   ExpectedStructOrTypedef,
64695d6
   ExpectedObjectiveCInterfaceOrProtocol,
64695d6
-  ExpectedKernelFunction
64695d6
+  ExpectedKernelFunction,
64695d6
+  ExpectedStructClassVariableFunctionMethodOrInlineNamespace
64695d6
 };
64695d6
 
64695d6
 }  // end namespace clang
64695d6
diff --git a/lib/AST/ItaniumMangle.cpp b/lib/AST/ItaniumMangle.cpp
64695d6
index dac803e..e32b659 100644
64695d6
--- a/tools/clang/lib/AST/ItaniumMangle.cpp
64695d6
+++ b/tools/clang/lib/AST/ItaniumMangle.cpp
64695d6
@@ -214,6 +214,8 @@ public:
64695d6
 class CXXNameMangler {
64695d6
   ItaniumMangleContextImpl &Context;
64695d6
   raw_ostream &Out;
64695d6
+  bool NullOut = false;
64695d6
+  bool DisableDerivedAbiTags = false;
64695d6
 
64695d6
   /// The "structor" is the top-level declaration being mangled, if
64695d6
   /// that's not a template specialization; otherwise it's the pattern
64695d6
@@ -263,6 +265,167 @@ class CXXNameMangler {
64695d6
 
64695d6
   } FunctionTypeDepth;
64695d6
 
64695d6
+  // abi_tag is a gcc attribute, taking one or more strings called "tags".
64695d6
+  //
64695d6
+  // the goal is to annotage against which version of a library an object was
64695d6
+  // build and to be able to provide backwards compatibility ("dual abi").
64695d6
+  //
64695d6
+  // for this the emitted mangled names have to be different, while you don't
64695d6
+  // want the user to have to use different names in the source.
64695d6
+  //
64695d6
+  // the abi_tag can be present on Struct, Var and Function  declarations as
64695d6
+  // "explicit" tag, and on inline Namespace as "implicit" tag. Explicit tags
64695d6
+  // are always emitted after the unqualified name, and (implicit) tags on
64695d6
+  // namespace are not.
64695d6
+  //
64695d6
+  // For functions and variables there is a set of "implicitly available"
64695d6
+  // tags. These tags are: all tags from the namespace/structs the name is
64695d6
+  // embedded in, all tags from any template arguments of the name, and, for
64695d6
+  // functions, alls tags used anywhere in the <bare-function-type> (i.e.
64695d6
+  // parameters and sometimes the return type).
64695d6
+  //
64695d6
+  // For functions this is basically the list of all tags from the signature
64695d6
+  // without the unqualified name and usually without the return type of the
64695d6
+  // function. In `operator Type()` Type is NOT part of that list, as it is
64695d6
+  // part of the unqualified name!
64695d6
+  //
64695d6
+  // Now all tags from the function return type/variable type which are not
64695d6
+  // "implicitly available" must be added to the explicit list of tags, and
64695d6
+  // are emitted after the unqualified name.
64695d6
+  //
64695d6
+  // Example:
64695d6
+  // namespace std {
64695d6
+  //   inline namespace __cxx11 __attribute__((__abi_tag__("cxx11"))) { }
64695d6
+  //   inline namespace __cxx11 {
64695d6
+  //     struct string { };
64695d6
+  //   }
64695d6
+  // }
64695d6
+  //
64695d6
+  // std::string foo(); // needs abi tag "cxx11" on foo
64695d6
+  // std::string foo(std::string); // does NOT need abi tag "cxx11" on foo
64695d6
+  // __attribute__((__abi_tag__("cxx11")))
64695d6
+  // std::string foo2(std::string); // emit abi tag "cxx11" on foo anyway
64695d6
+  //
64695d6
+  // The tags are sorted by name before emitting, and are serialized as
64695d6
+  //   <abitag> ::= B <"tag" source-name>
64695d6
+
64695d6
+  typedef SmallVector<StringRef, 4> AbiTagList;
64695d6
+
64695d6
+  // state to gather all implicit and explicit tags used in a mangled name.
64695d6
+  // must always have an instance of this while emitting any name to keep
64695d6
+  // track.
64695d6
+  //
64695d6
+  // TODO(abitags): how to handle substituted names? they should add the tags used in
64695d6
+  // the substitution to the list of available tags.
64695d6
+  class AbiTagState final {
64695d6
+  public:
64695d6
+    //! all abi tags used implicitly or explicitly
64695d6
+    std::set<StringRef> UsedAbiTags;
64695d6
+    //! all explicit abi tags (i.e. not from namespace)
64695d6
+    std::set<StringRef> EmittedAbiTags;
64695d6
+
64695d6
+    AbiTagState* &LinkHead;
64695d6
+    AbiTagState *Parent{nullptr};
64695d6
+
64695d6
+    bool LinkActive{false};
64695d6
+
64695d6
+    explicit AbiTagState(AbiTagState* &linkHead)
64695d6
+      : LinkHead(linkHead) {
64695d6
+      Parent = LinkHead;
64695d6
+      LinkHead = this;
64695d6
+      LinkActive = true;
64695d6
+    }
64695d6
+
64695d6
+    // no copy, no move
64695d6
+    AbiTagState(AbiTagState const&) = delete;
64695d6
+    AbiTagState& operator=(AbiTagState const&) = delete;
64695d6
+
64695d6
+    ~AbiTagState() {
64695d6
+      pop();
64695d6
+    }
64695d6
+
64695d6
+    void pop() {
64695d6
+      if (!LinkActive) return;
64695d6
+
64695d6
+      assert(LinkHead == this && "abi tag link head must point to us on destruction");
64695d6
+      LinkActive = false;
64695d6
+      if (Parent) {
64695d6
+        Parent->UsedAbiTags.insert(UsedAbiTags.begin(), UsedAbiTags.end());
64695d6
+        Parent->EmittedAbiTags.insert(EmittedAbiTags.begin(), EmittedAbiTags.end());
64695d6
+      }
64695d6
+      LinkHead = Parent;
64695d6
+    }
64695d6
+
64695d6
+    void write(raw_ostream &Out, const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
64695d6
+      ND = cast<NamedDecl>(ND->getCanonicalDecl());
64695d6
+
64695d6
+      if (dyn_cast<FunctionDecl>(ND) || dyn_cast<VarDecl>(ND)) {
64695d6
+        // assert(AdditionalAbiTags && "function and variables need a list of additional abi tags");
64695d6
+      } else {
64695d6
+        assert(!AdditionalAbiTags && "only function and variables need a list of additional abi tags");
64695d6
+        if (const auto* NS = dyn_cast<NamespaceDecl>(ND)) {
64695d6
+          if (const auto* AbiTag = NS->getAttr<AbiTagAttr>()) {
64695d6
+            for (const auto& Tag: AbiTag->tags()) {
64695d6
+              UsedAbiTags.insert(Tag);
64695d6
+            }
64695d6
+          }
64695d6
+          // don't emit abi tags for namespaces
64695d6
+          return;
64695d6
+        }
64695d6
+      }
64695d6
+
64695d6
+      AbiTagList TagList;
64695d6
+      if (const auto* AbiTag = ND->getAttr<AbiTagAttr>()) {
64695d6
+        for (const auto& Tag: AbiTag->tags()) {
64695d6
+          UsedAbiTags.insert(Tag);
64695d6
+          // AbiTag->tags() is sorted and has no duplicates
64695d6
+          TagList.push_back(Tag);
64695d6
+        }
64695d6
+      }
64695d6
+
64695d6
+      if (AdditionalAbiTags) {
64695d6
+        for (const auto& Tag: *AdditionalAbiTags) {
64695d6
+          UsedAbiTags.insert(Tag);
64695d6
+          if (std::find(TagList.begin(), TagList.end(), Tag) == TagList.end()) {
64695d6
+            // don't insert duplicates
64695d6
+            TagList.push_back(Tag);
64695d6
+          }
64695d6
+        }
64695d6
+        // AbiTag->tags() are already sorted; only add if we had additional tags
64695d6
+        std::sort(TagList.begin(), TagList.end());
64695d6
+      }
64695d6
+
64695d6
+      writeSortedUniqueAbiTags(Out, TagList);
64695d6
+    }
64695d6
+
64695d6
+  protected:
64695d6
+    template<typename TagList>
64695d6
+    void writeSortedUniqueAbiTags(raw_ostream &Out, TagList const& AbiTags) {
64695d6
+      for (const auto& Tag: AbiTags) {
64695d6
+        EmittedAbiTags.insert(Tag);
64695d6
+        Out << "B";
64695d6
+        Out << Tag.size();
64695d6
+        Out << Tag;
64695d6
+      }
64695d6
+    }
64695d6
+  } *AbiTags = nullptr;
64695d6
+  AbiTagState AbiTagsRoot{AbiTags};
64695d6
+
64695d6
+  struct TemporaryDisableDerivedAbiTags {
64695d6
+    bool& StateRef;
64695d6
+    bool OldState;
64695d6
+
64695d6
+    TemporaryDisableDerivedAbiTags(bool& State, bool Disable = true)
64695d6
+    : StateRef(State) {
64695d6
+      OldState = StateRef;
64695d6
+      StateRef = Disable;
64695d6
+    }
64695d6
+    TemporaryDisableDerivedAbiTags(TemporaryDisableDerivedAbiTags const&) = delete;
64695d6
+    ~TemporaryDisableDerivedAbiTags() {
64695d6
+      StateRef = OldState;
64695d6
+    }
64695d6
+  };
64695d6
+
64695d6
   llvm::DenseMap<uintptr_t, unsigned> Substitutions;
64695d6
 
64695d6
   ASTContext &getASTContext() const { return Context.getASTContext(); }
64695d6
@@ -285,6 +448,10 @@ public:
64695d6
     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
64695d6
       SeqID(0) { }
64695d6
 
64695d6
+  CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
64695d6
+    : Context(Outer.Context), Out(Out_), NullOut(true), Structor(Outer.Structor), StructorType(Outer.StructorType),
64695d6
+      SeqID(Outer.SeqID) { }
64695d6
+
64695d6
 #if MANGLE_CHECKER
64695d6
   ~CXXNameMangler() {
64695d6
     if (Out.str()[0] == '\01')
64695d6
@@ -298,18 +465,21 @@ public:
64695d6
 #endif
64695d6
   raw_ostream &getStream() { return Out; }
64695d6
 
64695d6
+  void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
64695d6
+
64695d6
   void mangle(const NamedDecl *D);
64695d6
   void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
64695d6
   void mangleNumber(const llvm::APSInt &I);
64695d6
   void mangleNumber(int64_t Number);
64695d6
   void mangleFloat(const llvm::APFloat &F);
64695d6
-  void mangleFunctionEncoding(const FunctionDecl *FD);
64695d6
+  void mangleFunctionEncoding(const FunctionDecl *FD, bool ExcludeUnqualifiedName = false);
64695d6
   void mangleSeqID(unsigned SeqID);
64695d6
-  void mangleName(const NamedDecl *ND);
64695d6
+  void mangleName(const NamedDecl *ND, bool ExcludeUnqualifiedName = false);
64695d6
   void mangleType(QualType T);
64695d6
   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
64695d6
   
64695d6
 private:
64695d6
+  void writeAbiTags(const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
64695d6
 
64695d6
   bool mangleSubstitution(const NamedDecl *ND);
64695d6
   bool mangleSubstitution(QualType T);
64695d6
@@ -336,31 +506,49 @@ private:
64695d6
                             DeclarationName name,
64695d6
                             unsigned KnownArity = UnknownArity);
64695d6
 
64695d6
-  void mangleName(const TemplateDecl *TD,
64695d6
+  void mangleFunctionEncodingBareType(const FunctionDecl *FD);
64695d6
+
64695d6
+  void mangleNameWithAbiTags(const NamedDecl *ND,
64695d6
+                             const AbiTagList *AdditionalAbiTags,
64695d6
+                             bool ExcludeUnqualifiedName);
64695d6
+  void mangleTemplateName(const TemplateDecl *TD,
64695d6
+                  const AbiTagList *AdditionalAbiTags,
64695d6
+                  bool ExcludeUnqualifiedName,
64695d6
                   const TemplateArgument *TemplateArgs,
64695d6
                   unsigned NumTemplateArgs);
64695d6
-  void mangleUnqualifiedName(const NamedDecl *ND) {
64695d6
-    mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
64695d6
+  void mangleUnqualifiedName(const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
64695d6
+    mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity, AdditionalAbiTags);
64695d6
   }
64695d6
   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
64695d6
-                             unsigned KnownArity);
64695d6
-  void mangleUnscopedName(const NamedDecl *ND);
64695d6
-  void mangleUnscopedTemplateName(const TemplateDecl *ND);
64695d6
-  void mangleUnscopedTemplateName(TemplateName);
64695d6
+                             unsigned KnownArity, const AbiTagList *AdditionalAbiTags);
64695d6
+  void mangleUnscopedName(const NamedDecl *ND, const AbiTagList *AdditionalAbiTags);
64695d6
+  void mangleUnscopedTemplateName(const TemplateDecl *ND,
64695d6
+                                  const AbiTagList *AdditionalAbiTags);
64695d6
+  void mangleUnscopedTemplateName(TemplateName,
64695d6
+                                  const AbiTagList *AdditionalAbiTags);
64695d6
   void mangleSourceName(const IdentifierInfo *II);
64695d6
-  void mangleLocalName(const Decl *D);
64695d6
+  void mangleLocalName(const Decl *D,
64695d6
+                       const AbiTagList *AdditionalAbiTags,
64695d6
+                       bool ExcludeUnqualifiedName);
64695d6
   void mangleBlockForPrefix(const BlockDecl *Block);
64695d6
   void mangleUnqualifiedBlock(const BlockDecl *Block);
64695d6
   void mangleLambda(const CXXRecordDecl *Lambda);
64695d6
   void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
64695d6
-                        bool NoFunction=false);
64695d6
+                        const AbiTagList *AdditionalAbiTags,
64695d6
+                        bool NoFunction,
64695d6
+                        bool ExcludeUnqualifiedName);
64695d6
   void mangleNestedName(const TemplateDecl *TD,
64695d6
+                        const AbiTagList *AdditionalAbiTags,
64695d6
+                        bool ExcludeUnqualifiedName,
64695d6
                         const TemplateArgument *TemplateArgs,
64695d6
                         unsigned NumTemplateArgs);
64695d6
   void manglePrefix(NestedNameSpecifier *qualifier);
64695d6
   void manglePrefix(const DeclContext *DC, bool NoFunction=false);
64695d6
   void manglePrefix(QualType type);
64695d6
-  void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
64695d6
+  void mangleTemplatePrefix(const TemplateDecl *ND,
64695d6
+                            const AbiTagList *AdditionalAbiTags,
64695d6
+                            bool NoFunction = false,
64695d6
+                            bool ExcludeUnqualifiedName = false);
64695d6
   void mangleTemplatePrefix(TemplateName Template);
64695d6
   bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
64695d6
                                       StringRef Prefix = "");
64695d6
@@ -406,6 +594,10 @@ private:
64695d6
   void mangleTemplateParameter(unsigned Index);
64695d6
 
64695d6
   void mangleFunctionParam(const ParmVarDecl *parm);
64695d6
+
64695d6
+  std::set<StringRef> getTagsFromPrefixAndTemplateArguments(const NamedDecl *ND);
64695d6
+  AbiTagList makeAdditionalTagsForFunction(const FunctionDecl *FD);
64695d6
+  AbiTagList makeAdditionalTagsForVariable(const VarDecl *VD);
64695d6
 };
64695d6
 
64695d6
 }
64695d6
@@ -456,6 +648,11 @@ bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
64695d6
   return true;
64695d6
 }
64695d6
 
64695d6
+void CXXNameMangler::writeAbiTags(const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
64695d6
+  assert(AbiTags && "require AbiTagState");
64695d6
+  if (AbiTags) AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
64695d6
+}
64695d6
+
64695d6
 void CXXNameMangler::mangle(const NamedDecl *D) {
64695d6
   // <mangled-name> ::= _Z <encoding>
64695d6
   //            ::= <data name>
64695d6
@@ -471,14 +668,28 @@ void CXXNameMangler::mangle(const NamedDecl *D) {
64695d6
     mangleName(cast<FieldDecl>(D));
64695d6
 }
64695d6
 
64695d6
-void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
64695d6
-  // <encoding> ::= <function name> <bare-function-type>
64695d6
-  mangleName(FD);
64695d6
-
64695d6
+void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD, bool ExcludeUnqualifiedName) {
64695d6
   // Don't mangle in the type if this isn't a decl we should typically mangle.
64695d6
-  if (!Context.shouldMangleDeclName(FD))
64695d6
+  if (!Context.shouldMangleDeclName(FD)) {
64695d6
+    mangleNameWithAbiTags(FD, /* AdditionalAbiTags */ nullptr, ExcludeUnqualifiedName);
64695d6
     return;
64695d6
+  }
64695d6
+
64695d6
+  // <encoding> ::= <function name> <bare-function-type>
64695d6
 
64695d6
+  if (ExcludeUnqualifiedName)
64695d6
+  {
64695d6
+    // running makeAdditionalTagsForFunction would loop, don't need it here anyway
64695d6
+    mangleNameWithAbiTags(FD, /* AdditionalAbiTags */ nullptr, ExcludeUnqualifiedName);
64695d6
+  } else {
64695d6
+    AbiTagList AdditionalAbiTags = makeAdditionalTagsForFunction(FD);
64695d6
+    mangleNameWithAbiTags(FD, &AdditionalAbiTags, ExcludeUnqualifiedName);
64695d6
+  }
64695d6
+
64695d6
+  mangleFunctionEncodingBareType(FD);
64695d6
+}
64695d6
+
64695d6
+void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
64695d6
   if (FD->hasAttr<EnableIfAttr>()) {
64695d6
     FunctionTypeDepthState Saved = FunctionTypeDepth.push();
64695d6
     Out << "Ua9enable_ifI";
64695d6
@@ -524,7 +735,7 @@ void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
64695d6
     FD = PrimaryTemplate->getTemplatedDecl();
64695d6
   }
64695d6
 
64695d6
-  mangleBareFunctionType(FD->getType()->getAs<FunctionType>(), 
64695d6
+  mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
64695d6
                          MangleReturnType);
64695d6
 }
64695d6
 
64695d6
@@ -582,7 +793,21 @@ isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
64695d6
   return nullptr;
64695d6
 }
64695d6
 
64695d6
-void CXXNameMangler::mangleName(const NamedDecl *ND) {
64695d6
+// must not be run from mangleLocalName for the <entity name> as it would loop otherwise.
64695d6
+void CXXNameMangler::mangleName(const NamedDecl *ND, bool ExcludeUnqualifiedName) {
64695d6
+  if (!ExcludeUnqualifiedName) {
64695d6
+    if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
64695d6
+      AbiTagList VariableAdditionalAbiTags = makeAdditionalTagsForVariable(VD);
64695d6
+      mangleNameWithAbiTags(VD, &VariableAdditionalAbiTags, ExcludeUnqualifiedName);
64695d6
+      return;
64695d6
+    }
64695d6
+  }
64695d6
+  mangleNameWithAbiTags(ND, nullptr, ExcludeUnqualifiedName);
64695d6
+}
64695d6
+
64695d6
+void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
64695d6
+                                           const AbiTagList *AdditionalAbiTags,
64695d6
+                                           bool ExcludeUnqualifiedName) {
64695d6
   //  <name> ::= <nested-name>
64695d6
   //         ::= <unscoped-name>
64695d6
   //         ::= <unscoped-template-name> <template-args>
64695d6
@@ -598,7 +823,7 @@ void CXXNameMangler::mangleName(const NamedDecl *ND) {
64695d6
     while (!DC->isNamespace() && !DC->isTranslationUnit())
64695d6
       DC = getEffectiveParentContext(DC);
64695d6
   else if (GetLocalClassDecl(ND)) {
64695d6
-    mangleLocalName(ND);
64695d6
+    mangleLocalName(ND, AdditionalAbiTags, ExcludeUnqualifiedName);
64695d6
     return;
64695d6
   }
64695d6
 
64695d6
@@ -608,76 +833,88 @@ void CXXNameMangler::mangleName(const NamedDecl *ND) {
64695d6
     // Check if we have a template.
64695d6
     const TemplateArgumentList *TemplateArgs = nullptr;
64695d6
     if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
64695d6
-      mangleUnscopedTemplateName(TD);
64695d6
+      if (!ExcludeUnqualifiedName)
64695d6
+        mangleUnscopedTemplateName(TD, AdditionalAbiTags);
64695d6
       mangleTemplateArgs(*TemplateArgs);
64695d6
       return;
64695d6
     }
64695d6
 
64695d6
-    mangleUnscopedName(ND);
64695d6
+    if (!ExcludeUnqualifiedName)
64695d6
+      mangleUnscopedName(ND, AdditionalAbiTags);
64695d6
     return;
64695d6
   }
64695d6
 
64695d6
   if (isLocalContainerContext(DC)) {
64695d6
-    mangleLocalName(ND);
64695d6
+    mangleLocalName(ND, AdditionalAbiTags, ExcludeUnqualifiedName);
64695d6
     return;
64695d6
   }
64695d6
 
64695d6
-  mangleNestedName(ND, DC);
64695d6
+  mangleNestedName(ND, DC, AdditionalAbiTags, /* NoFunction */ false, ExcludeUnqualifiedName);
64695d6
 }
64695d6
-void CXXNameMangler::mangleName(const TemplateDecl *TD,
64695d6
-                                const TemplateArgument *TemplateArgs,
64695d6
-                                unsigned NumTemplateArgs) {
64695d6
+
64695d6
+void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
64695d6
+                                        const AbiTagList *AdditionalAbiTags,
64695d6
+                                        bool ExcludeUnqualifiedName,
64695d6
+                                        const TemplateArgument *TemplateArgs,
64695d6
+                                        unsigned NumTemplateArgs) {
64695d6
   const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
64695d6
 
64695d6
   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
64695d6
-    mangleUnscopedTemplateName(TD);
64695d6
+    if (!ExcludeUnqualifiedName)
64695d6
+      mangleUnscopedTemplateName(TD, AdditionalAbiTags);
64695d6
     mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
64695d6
   } else {
64695d6
-    mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
64695d6
+    mangleNestedName(TD, AdditionalAbiTags, ExcludeUnqualifiedName, TemplateArgs, NumTemplateArgs);
64695d6
   }
64695d6
 }
64695d6
 
64695d6
-void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
64695d6
+void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
64695d6
   //  <unscoped-name> ::= <unqualified-name>
64695d6
   //                  ::= St <unqualified-name>   # ::std::
64695d6
 
64695d6
   if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
64695d6
     Out << "St";
64695d6
 
64695d6
-  mangleUnqualifiedName(ND);
64695d6
+  mangleUnqualifiedName(ND, AdditionalAbiTags);
64695d6
 }
64695d6
 
64695d6
-void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
64695d6
+void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND,
64695d6
+                                                const AbiTagList *AdditionalAbiTags) {
64695d6
   //     <unscoped-template-name> ::= <unscoped-name>
64695d6
   //                              ::= <substitution>
64695d6
   if (mangleSubstitution(ND))
64695d6
     return;
64695d6
 
64695d6
   // <template-template-param> ::= <template-param>
64695d6
-  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
64695d6
+  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
64695d6
+    assert(!AdditionalAbiTags && "template template param cannot have abi tags"); // TODO(abitags)
64695d6
     mangleTemplateParameter(TTP->getIndex());
64695d6
-  else
64695d6
-    mangleUnscopedName(ND->getTemplatedDecl());
64695d6
+  } else {
64695d6
+    mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
64695d6
+  }
64695d6
 
64695d6
   addSubstitution(ND);
64695d6
 }
64695d6
 
64695d6
-void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
64695d6
+void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template,
64695d6
+                                                const AbiTagList *AdditionalAbiTags) {
64695d6
   //     <unscoped-template-name> ::= <unscoped-name>
64695d6
   //                              ::= <substitution>
64695d6
   if (TemplateDecl *TD = Template.getAsTemplateDecl())
64695d6
-    return mangleUnscopedTemplateName(TD);
64695d6
+    return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
64695d6
   
64695d6
   if (mangleSubstitution(Template))
64695d6
     return;
64695d6
 
64695d6
+  assert(!AdditionalAbiTags && "dependent template name cannot have abi tags"); // TODO(abitags)
64695d6
+
64695d6
   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
64695d6
   assert(Dependent && "Not a dependent template name?");
64695d6
   if (const IdentifierInfo *Id = Dependent->getIdentifier())
64695d6
     mangleSourceName(Id);
64695d6
   else
64695d6
     mangleOperatorName(Dependent->getOperator(), UnknownArity);
64695d6
-  
64695d6
+
64695d6
   addSubstitution(Template);
64695d6
 }
64695d6
 
64695d6
@@ -837,6 +1074,7 @@ void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
64695d6
     else
64695d6
       Out << "sr";
64695d6
     mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
64695d6
+    writeAbiTags(qualifier->getAsNamespace());
64695d6
     break;
64695d6
   case NestedNameSpecifier::NamespaceAlias:
64695d6
     if (qualifier->getPrefix())
64695d6
@@ -845,6 +1083,7 @@ void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
64695d6
     else
64695d6
       Out << "sr";
64695d6
     mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
64695d6
+    writeAbiTags(qualifier->getAsNamespaceAlias());
64695d6
     break;
64695d6
 
64695d6
   case NestedNameSpecifier::TypeSpec:
64695d6
@@ -879,6 +1118,7 @@ void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
64695d6
       Out << "sr";
64695d6
 
64695d6
     mangleSourceName(qualifier->getAsIdentifier());
64695d6
+    writeAbiTags(qualifier->getAsNamespaceAlias());
64695d6
     break;
64695d6
   }
64695d6
 
64695d6
@@ -924,7 +1164,8 @@ void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
64695d6
 
64695d6
 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
64695d6
                                            DeclarationName Name,
64695d6
-                                           unsigned KnownArity) {
64695d6
+                                           unsigned KnownArity,
64695d6
+                                           const AbiTagList *AdditionalAbiTags) {
64695d6
   unsigned Arity = KnownArity;
64695d6
   //  <unqualified-name> ::= <operator-name>
64695d6
   //                     ::= <ctor-dtor-name>
64695d6
@@ -943,6 +1184,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
64695d6
         Out << 'L';
64695d6
 
64695d6
       mangleSourceName(II);
64695d6
+      writeAbiTags(ND, AdditionalAbiTags);
64695d6
       break;
64695d6
     }
64695d6
 
64695d6
@@ -982,6 +1224,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
64695d6
       assert(FD->getIdentifier() && "Data member name isn't an identifier!");
64695d6
 
64695d6
       mangleSourceName(FD->getIdentifier());
64695d6
+      // TODO(abitags): not emitting abi tags: internal name anyway
64695d6
       break;
64695d6
     }
64695d6
 
64695d6
@@ -1002,6 +1245,9 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
64695d6
       assert(D->getDeclName().getAsIdentifierInfo() &&
64695d6
              "Typedef was not named!");
64695d6
       mangleSourceName(D->getDeclName().getAsIdentifierInfo());
64695d6
+      assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
64695d6
+      // explicit abi tags are still possible; take from underlying type, not from typedef.
64695d6
+      writeAbiTags(TD, nullptr);
64695d6
       break;
64695d6
     }
64695d6
 
64695d6
@@ -1011,6 +1257,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
64695d6
     // <lambda-sig> ::= <parameter-type>+   # Parameter types or 'v' for 'void'.
64695d6
     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
64695d6
       if (Record->isLambda() && Record->getLambdaManglingNumber()) {
64695d6
+        assert(!AdditionalAbiTags && "Lambda type cannot have additional abi tags");
64695d6
         mangleLambda(Record);
64695d6
         break;
64695d6
       }
64695d6
@@ -1022,6 +1269,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
64695d6
       if (UnnamedMangle > 1)
64695d6
         Out << llvm::utostr(UnnamedMangle - 2);
64695d6
       Out << '_';
64695d6
+      writeAbiTags(TD, AdditionalAbiTags);
64695d6
       break;
64695d6
     }
64695d6
 
64695d6
@@ -1054,6 +1302,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
64695d6
       // Otherwise, use the complete constructor name. This is relevant if a
64695d6
       // class with a constructor is declared within a constructor.
64695d6
       mangleCXXCtorType(Ctor_Complete);
64695d6
+    writeAbiTags(ND, AdditionalAbiTags);
64695d6
     break;
64695d6
 
64695d6
   case DeclarationName::CXXDestructorName:
64695d6
@@ -1065,6 +1314,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
64695d6
       // Otherwise, use the complete destructor name. This is relevant if a
64695d6
       // class with a destructor is declared within a destructor.
64695d6
       mangleCXXDtorType(Dtor_Complete);
64695d6
+    writeAbiTags(ND, AdditionalAbiTags);
64695d6
     break;
64695d6
 
64695d6
   case DeclarationName::CXXOperatorName:
64695d6
@@ -1080,6 +1330,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
64695d6
   case DeclarationName::CXXConversionFunctionName:
64695d6
   case DeclarationName::CXXLiteralOperatorName:
64695d6
     mangleOperatorName(Name, Arity);
64695d6
+    writeAbiTags(ND, AdditionalAbiTags);
64695d6
     break;
64695d6
 
64695d6
   case DeclarationName::CXXUsingDirective:
64695d6
@@ -1096,7 +1347,9 @@ void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
64695d6
 
64695d6
 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
64695d6
                                       const DeclContext *DC,
64695d6
-                                      bool NoFunction) {
64695d6
+                                      const AbiTagList *AdditionalAbiTags,
64695d6
+                                      bool NoFunction,
64695d6
+                                      bool ExcludeUnqualifiedName) {
64695d6
   // <nested-name> 
64695d6
   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
64695d6
   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> 
64695d6
@@ -1116,30 +1369,35 @@ void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
64695d6
   // Check if we have a template.
64695d6
   const TemplateArgumentList *TemplateArgs = nullptr;
64695d6
   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
64695d6
-    mangleTemplatePrefix(TD, NoFunction);
64695d6
+    mangleTemplatePrefix(TD, AdditionalAbiTags, NoFunction, ExcludeUnqualifiedName);
64695d6
     mangleTemplateArgs(*TemplateArgs);
64695d6
   }
64695d6
   else {
64695d6
     manglePrefix(DC, NoFunction);
64695d6
-    mangleUnqualifiedName(ND);
64695d6
+    if (!ExcludeUnqualifiedName)
64695d6
+      mangleUnqualifiedName(ND, AdditionalAbiTags);
64695d6
   }
64695d6
 
64695d6
   Out << 'E';
64695d6
 }
64695d6
 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
64695d6
+                                      const AbiTagList *AdditionalAbiTags,
64695d6
+                                      bool ExcludeUnqualifiedName,
64695d6
                                       const TemplateArgument *TemplateArgs,
64695d6
                                       unsigned NumTemplateArgs) {
64695d6
   // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
64695d6
 
64695d6
   Out << 'N';
64695d6
 
64695d6
-  mangleTemplatePrefix(TD);
64695d6
+  mangleTemplatePrefix(TD, AdditionalAbiTags, ExcludeUnqualifiedName);
64695d6
   mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
64695d6
 
64695d6
   Out << 'E';
64695d6
 }
64695d6
 
64695d6
-void CXXNameMangler::mangleLocalName(const Decl *D) {
64695d6
+void CXXNameMangler::mangleLocalName(const Decl *D,
64695d6
+                                     const AbiTagList *AdditionalAbiTags,
64695d6
+                                     bool ExcludeUnqualifiedName) {
64695d6
   // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
64695d6
   //              := Z <function encoding> E s [<discriminator>]
64695d6
   // <local-name> := Z <function encoding> E d [ <parameter number> ] 
64695d6
@@ -1151,15 +1409,25 @@ void CXXNameMangler::mangleLocalName(const Decl *D) {
64695d6
 
64695d6
   Out << 'Z';
64695d6
 
64695d6
-  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
64695d6
-    mangleObjCMethodName(MD);
64695d6
-  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
64695d6
-    mangleBlockForPrefix(BD);
64695d6
-  else
64695d6
-    mangleFunctionEncoding(cast<FunctionDecl>(DC));
64695d6
+  {
64695d6
+    AbiTagState localAbiTags(AbiTags);
64695d6
+
64695d6
+    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
64695d6
+      mangleObjCMethodName(MD);
64695d6
+    else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
64695d6
+      mangleBlockForPrefix(BD);
64695d6
+    else
64695d6
+      mangleFunctionEncoding(cast<FunctionDecl>(DC));
64695d6
+
64695d6
+    // implicit abi tags (from namespace) are not available in the following
64695d6
+    // entity; reset to actually emitted tags, which are available.
64695d6
+    localAbiTags.UsedAbiTags = localAbiTags.EmittedAbiTags;
64695d6
+  }
64695d6
 
64695d6
   Out << 'E';
64695d6
 
64695d6
+  TemporaryDisableDerivedAbiTags TemporyDisable(DisableDerivedAbiTags, getStructor(dyn_cast<NamedDecl>(D)) != Structor);
64695d6
+
64695d6
   if (RD) {
64695d6
     // The parameter number is omitted for the last parameter, 0 for the 
64695d6
     // second-to-last parameter, 1 for the third-to-last parameter, etc. The 
64695d6
@@ -1184,13 +1452,17 @@ void CXXNameMangler::mangleLocalName(const Decl *D) {
64695d6
     // Mangle the name relative to the closest enclosing function.
64695d6
     // equality ok because RD derived from ND above
64695d6
     if (D == RD)  {
64695d6
-      mangleUnqualifiedName(RD);
64695d6
+      if (!ExcludeUnqualifiedName)
64695d6
+        mangleUnqualifiedName(RD, AdditionalAbiTags);
64695d6
     } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64695d6
       manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
64695d6
-      mangleUnqualifiedBlock(BD);
64695d6
+      assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
64695d6
+      if (!ExcludeUnqualifiedName)
64695d6
+        mangleUnqualifiedBlock(BD);
64695d6
     } else {
64695d6
       const NamedDecl *ND = cast<NamedDecl>(D);
64695d6
-      mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
64695d6
+      mangleNestedName(ND, getEffectiveDeclContext(ND),
64695d6
+                       AdditionalAbiTags, true /*NoFunction*/, ExcludeUnqualifiedName);
64695d6
     }
64695d6
   } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64695d6
     // Mangle a block in a default parameter; see above explanation for
64695d6
@@ -1207,30 +1479,35 @@ void CXXNameMangler::mangleLocalName(const Decl *D) {
64695d6
       }
64695d6
     }
64695d6
 
64695d6
-    mangleUnqualifiedBlock(BD);
64695d6
+    assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
64695d6
+    if (!ExcludeUnqualifiedName)
64695d6
+      mangleUnqualifiedBlock(BD);
64695d6
   } else {
64695d6
-    mangleUnqualifiedName(cast<NamedDecl>(D));
64695d6
-  }
64695d6
-
64695d6
-  if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
64695d6
-    unsigned disc;
64695d6
-    if (Context.getNextDiscriminator(ND, disc)) {
64695d6
-      if (disc < 10)
64695d6
-        Out << '_' << disc;
64695d6
-      else
64695d6
-        Out << "__" << disc << '_';
64695d6
+    if (!ExcludeUnqualifiedName)
64695d6
+      mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
64695d6
+  }
64695d6
+
64695d6
+  if (!ExcludeUnqualifiedName) {
64695d6
+    if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
64695d6
+      unsigned disc;
64695d6
+      if (Context.getNextDiscriminator(ND, disc)) {
64695d6
+        if (disc < 10)
64695d6
+          Out << '_' << disc;
64695d6
+        else
64695d6
+          Out << "__" << disc << '_';
64695d6
+      }
64695d6
     }
64695d6
   }
64695d6
 }
64695d6
 
64695d6
 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
64695d6
   if (GetLocalClassDecl(Block)) {
64695d6
-    mangleLocalName(Block);
64695d6
+    mangleLocalName(Block, /* AdditionalAbiTags */ nullptr, /* ExcludeUnqualifiedName */ false);
64695d6
     return;
64695d6
   }
64695d6
   const DeclContext *DC = getEffectiveDeclContext(Block);
64695d6
   if (isLocalContainerContext(DC)) {
64695d6
-    mangleLocalName(Block);
64695d6
+    mangleLocalName(Block, /* AdditionalAbiTags */ nullptr, /* ExcludeUnqualifiedName */ false);
64695d6
     return;
64695d6
   }
64695d6
   manglePrefix(getEffectiveDeclContext(Block));
64695d6
@@ -1241,10 +1518,11 @@ void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
64695d6
   if (Decl *Context = Block->getBlockManglingContextDecl()) {
64695d6
     if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
64695d6
         Context->getDeclContext()->isRecord()) {
64695d6
-      if (const IdentifierInfo *Name
64695d6
-            = cast<NamedDecl>(Context)->getIdentifier()) {
64695d6
+      const auto *ND = cast<NamedDecl>(Context);
64695d6
+      if (const IdentifierInfo *Name = ND->getIdentifier()) {
64695d6
         mangleSourceName(Name);
64695d6
-        Out << 'M';            
64695d6
+        writeAbiTags(ND, /* AdditionalAbiTags */ nullptr);
64695d6
+        Out << 'M';
64695d6
       }
64695d6
     }
64695d6
   }
64695d6
@@ -1277,7 +1555,7 @@ void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
64695d6
       if (const IdentifierInfo *Name
64695d6
             = cast<NamedDecl>(Context)->getIdentifier()) {
64695d6
         mangleSourceName(Name);
64695d6
-        Out << 'M';            
64695d6
+        Out << 'M';
64695d6
       }
64695d6
     }
64695d6
   }
64695d6
@@ -1359,11 +1637,11 @@ void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
64695d6
   // Check if we have a template.
64695d6
   const TemplateArgumentList *TemplateArgs = nullptr;
64695d6
   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
64695d6
-    mangleTemplatePrefix(TD);
64695d6
+    mangleTemplatePrefix(TD, /* AdditionalAbiTags */ nullptr);
64695d6
     mangleTemplateArgs(*TemplateArgs);
64695d6
   } else {
64695d6
     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
64695d6
-    mangleUnqualifiedName(ND);
64695d6
+    mangleUnqualifiedName(ND, /* AdditionalAbiTags */ nullptr);
64695d6
   }
64695d6
 
64695d6
   addSubstitution(ND);
64695d6
@@ -1374,27 +1652,30 @@ void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
64695d6
   //                   ::= <template-param>
64695d6
   //                   ::= <substitution>
64695d6
   if (TemplateDecl *TD = Template.getAsTemplateDecl())
64695d6
-    return mangleTemplatePrefix(TD);
64695d6
+    return mangleTemplatePrefix(TD, /* AdditionalAbiTags */ nullptr);
64695d6
 
64695d6
   if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
64695d6
     manglePrefix(Qualified->getQualifier());
64695d6
-  
64695d6
+
64695d6
   if (OverloadedTemplateStorage *Overloaded
64695d6
                                       = Template.getAsOverloadedTemplate()) {
64695d6
     mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
64695d6
-                          UnknownArity);
64695d6
+                          UnknownArity,
64695d6
+                          /* AdditionalAbiTags */ nullptr);
64695d6
     return;
64695d6
   }
64695d6
-   
64695d6
+
64695d6
   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
64695d6
   assert(Dependent && "Unknown template name kind?");
64695d6
   if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
64695d6
     manglePrefix(Qualifier);
64695d6
-  mangleUnscopedTemplateName(Template);
64695d6
+  mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
64695d6
 }
64695d6
 
64695d6
 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
64695d6
-                                          bool NoFunction) {
64695d6
+                                          const AbiTagList *AdditionalAbiTags,
64695d6
+                                          bool NoFunction,
64695d6
+                                          bool ExcludeUnqualifiedName) {
64695d6
   // <template-prefix> ::= <prefix> <template unqualified-name>
64695d6
   //                   ::= <template-param>
64695d6
   //                   ::= <substitution>
64695d6
@@ -1406,10 +1687,12 @@ void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
64695d6
 
64695d6
   // <template-template-param> ::= <template-param>
64695d6
   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
64695d6
+    // TODO(abitags): ???
64695d6
     mangleTemplateParameter(TTP->getIndex());
64695d6
   } else {
64695d6
     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
64695d6
-    mangleUnqualifiedName(ND->getTemplatedDecl());
64695d6
+    if (!ExcludeUnqualifiedName)
64695d6
+      mangleUnqualifiedName(ND->getTemplatedDecl(), AdditionalAbiTags);
64695d6
   }
64695d6
 
64695d6
   addSubstitution(ND);
64695d6
@@ -1453,6 +1736,7 @@ void CXXNameMangler::mangleType(TemplateName TN) {
64695d6
     // <name> ::= <nested-name>
64695d6
     mangleUnresolvedPrefix(Dependent->getQualifier());
64695d6
     mangleSourceName(Dependent->getIdentifier());
64695d6
+     // writeAbiTags(Dependent);
64695d6
     break;
64695d6
   }
64695d6
 
64695d6
@@ -1544,16 +1828,19 @@ bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
64695d6
 
64695d6
   case Type::Typedef:
64695d6
     mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
64695d6
+    writeAbiTags(cast<TypedefType>(Ty)->getDecl());
64695d6
     break;
64695d6
 
64695d6
   case Type::UnresolvedUsing:
64695d6
     mangleSourceName(
64695d6
         cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
64695d6
+    writeAbiTags(cast<UnresolvedUsingType>(Ty)->getDecl());
64695d6
     break;
64695d6
 
64695d6
   case Type::Enum:
64695d6
   case Type::Record:
64695d6
     mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
64695d6
+    writeAbiTags(cast<TagType>(Ty)->getDecl());
64695d6
     break;
64695d6
 
64695d6
   case Type::TemplateSpecialization: {
64695d6
@@ -1572,6 +1859,7 @@ bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
64695d6
         goto unresolvedType;
64695d6
 
64695d6
       mangleSourceName(TD->getIdentifier());
64695d6
+      writeAbiTags(TD);
64695d6
       break;
64695d6
     }
64695d6
 
64695d6
@@ -1603,16 +1891,19 @@ bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
64695d6
   case Type::InjectedClassName:
64695d6
     mangleSourceName(
64695d6
         cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
64695d6
+    writeAbiTags(cast<InjectedClassNameType>(Ty)->getDecl());
64695d6
     break;
64695d6
 
64695d6
   case Type::DependentName:
64695d6
     mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
64695d6
+    // writeAbiTags(cast<DependentNameType>(Ty));
64695d6
     break;
64695d6
 
64695d6
   case Type::DependentTemplateSpecialization: {
64695d6
     const DependentTemplateSpecializationType *DTST =
64695d6
         cast<DependentTemplateSpecializationType>(Ty);
64695d6
     mangleSourceName(DTST->getIdentifier());
64695d6
+    // writeAbiTags(DTST);
64695d6
     mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
64695d6
     break;
64695d6
   }
64695d6
@@ -2421,7 +2712,11 @@ void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
64695d6
 
64695d6
 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
64695d6
   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
64695d6
-    mangleName(TD, T->getArgs(), T->getNumArgs());
64695d6
+    // types only have explicit abi tags, no addition tags
64695d6
+    mangleTemplateName(TD,
64695d6
+                       /* AdditionalAbiTags */ nullptr,
64695d6
+                       /* ExcludeUnqualifiedName */ false,
64695d6
+                       T->getArgs(), T->getNumArgs());
64695d6
   } else {
64695d6
     if (mangleSubstitution(QualType(T, 0)))
64695d6
       return;
64695d6
@@ -2468,6 +2763,7 @@ void CXXNameMangler::mangleType(const DependentNameType *T) {
64695d6
   Out << 'N';
64695d6
   manglePrefix(T->getQualifier());
64695d6
   mangleSourceName(T->getIdentifier());
64695d6
+  // writeAbiTags(T); // TODO(abitags)
64695d6
   Out << 'E';
64695d6
 }
64695d6
 
64695d6
@@ -3863,6 +4159,74 @@ void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
64695d6
   Substitutions[Ptr] = SeqID++;
64695d6
 }
64695d6
 
64695d6
+std::set<StringRef> CXXNameMangler::getTagsFromPrefixAndTemplateArguments(const NamedDecl *ND) {
64695d6
+  llvm::raw_null_ostream NullOutStream;
64695d6
+  CXXNameMangler TrackPrefixAndTemplateArguments(*this, NullOutStream);
64695d6
+
64695d6
+  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
64695d6
+    TrackPrefixAndTemplateArguments.mangleFunctionEncoding(FD, /* ExcludeUnqualifiedName */ true);
64695d6
+  } else {
64695d6
+    TrackPrefixAndTemplateArguments.mangleName(ND, /* ExcludeUnqualifiedName */ true);
64695d6
+  }
64695d6
+
64695d6
+  return std::move(TrackPrefixAndTemplateArguments.AbiTagsRoot.UsedAbiTags);
64695d6
+}
64695d6
+
64695d6
+CXXNameMangler::AbiTagList CXXNameMangler::makeAdditionalTagsForFunction(const FunctionDecl *FD) {
64695d6
+  // when derived abi tags are disabled there is no need to make any list
64695d6
+  if (DisableDerivedAbiTags) return AbiTagList();
64695d6
+
64695d6
+  std::set<StringRef> ImplicitlyAvailableTags = getTagsFromPrefixAndTemplateArguments(FD);
64695d6
+  std::set<StringRef> ReturnTypeTags;
64695d6
+
64695d6
+  {
64695d6
+    llvm::raw_null_ostream NullOutStream;
64695d6
+    CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
64695d6
+
64695d6
+    const FunctionProtoType *Proto = cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
64695d6
+    TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
64695d6
+    TrackReturnTypeTags.mangleType(Proto->getReturnType());
64695d6
+    TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
64695d6
+
64695d6
+    ReturnTypeTags = std::move(TrackReturnTypeTags.AbiTagsRoot.UsedAbiTags);
64695d6
+  }
64695d6
+
64695d6
+  AbiTagList AdditionalAbiTags;
64695d6
+
64695d6
+  for (const auto& Tag: ReturnTypeTags) {
64695d6
+    if (ImplicitlyAvailableTags.count(Tag) == 0)
64695d6
+      AdditionalAbiTags.push_back(Tag);
64695d6
+  }
64695d6
+
64695d6
+  return AdditionalAbiTags;
64695d6
+}
64695d6
+
64695d6
+CXXNameMangler::AbiTagList CXXNameMangler::makeAdditionalTagsForVariable(const VarDecl *VD) {
64695d6
+  // when derived abi tags are disabled there is no need to make any list
64695d6
+  if (DisableDerivedAbiTags) return AbiTagList();
64695d6
+
64695d6
+  std::set<StringRef> ImplicitlyAvailableTags = getTagsFromPrefixAndTemplateArguments(VD);
64695d6
+  std::set<StringRef> VariableTypeTags;
64695d6
+
64695d6
+  {
64695d6
+    llvm::raw_null_ostream NullOutStream;
64695d6
+    CXXNameMangler TrackVariableType(*this, NullOutStream);
64695d6
+
64695d6
+    TrackVariableType.mangleType(VD->getType());
64695d6
+
64695d6
+    VariableTypeTags = std::move(TrackVariableType.AbiTagsRoot.UsedAbiTags);
64695d6
+  }
64695d6
+
64695d6
+  AbiTagList AdditionalAbiTags;
64695d6
+
64695d6
+  for (const auto& Tag: VariableTypeTags) {
64695d6
+    if (ImplicitlyAvailableTags.count(Tag) == 0)
64695d6
+      AdditionalAbiTags.push_back(Tag);
64695d6
+  }
64695d6
+
64695d6
+  return AdditionalAbiTags;
64695d6
+}
64695d6
+
64695d6
 //
64695d6
 
64695d6
 /// Mangles the name of the declaration D and emits that name to the given
64695d6
@@ -3964,6 +4328,7 @@ void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
64695d6
   //  <special-name> ::= GV <object name>       # Guard variable for one-time
64695d6
   //                                            # initialization
64695d6
   CXXNameMangler Mangler(*this, Out);
64695d6
+  Mangler.disableDerivedAbiTags(); // GCC: doesn't emit derived abi tags for guard variables
64695d6
   Mangler.getStream() << "_ZGV";
64695d6
   Mangler.mangleName(D);
64695d6
 }
64695d6
diff --git a/lib/Sema/SemaDeclAttr.cpp b/lib/Sema/SemaDeclAttr.cpp
64695d6
index 191dbd0..225607e 100644
64695d6
--- a/tools/clang/lib/Sema/SemaDeclAttr.cpp
64695d6
+++ b/tools/clang/lib/Sema/SemaDeclAttr.cpp
64695d6
@@ -4166,6 +4166,58 @@ static void handleDeclspecThreadAttr(Sema &S, Decl *D,
64695d6
       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
64695d6
 }
64695d6
 
64695d6
+static void handleAbiTagAttr(Sema &S, Decl *D,
64695d6
+                             const AttributeList &Attr) {
64695d6
+  if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
64695d6
+    return;
64695d6
+
64695d6
+  SmallVector<std::string, 4> Tags;
64695d6
+
64695d6
+  for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
64695d6
+    StringRef Tag;
64695d6
+
64695d6
+    if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
64695d6
+      return;
64695d6
+
64695d6
+    Tags.push_back(Tag);
64695d6
+  }
64695d6
+  // store tags sorted and without duplicates
64695d6
+  std::sort(Tags.begin(), Tags.end());
64695d6
+  Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
64695d6
+
64695d6
+  if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
64695d6
+    if (!NS->isInline()) {
64695d6
+      S.Diag(Attr.getLoc(), diag::err_attr_abi_tag_only_on_inline_namespace);
64695d6
+      return;
64695d6
+    }
64695d6
+  }
64695d6
+
64695d6
+  const auto *CD = D->getCanonicalDecl();
64695d6
+  if (CD != D) {
64695d6
+    // redeclarations must not add new abi tags, or abi tags in the first place
64695d6
+    const auto *OldAbiTagAttr = D->getAttr<AbiTagAttr>();
64695d6
+    if (nullptr == OldAbiTagAttr) {
64695d6
+      S.Diag(Attr.getLoc(), diag::err_abi_tag_on_redeclaration);
64695d6
+      S.Diag(CD->getLocation(), diag::note_previous_definition);
64695d6
+      return;
64695d6
+    }
64695d6
+    for (const auto& NewTag: Tags) {
64695d6
+      if (std::find(OldAbiTagAttr->tags_begin(),
64695d6
+                    OldAbiTagAttr->tags_end(),
64695d6
+                    NewTag) == OldAbiTagAttr->tags_end()) {
64695d6
+        S.Diag(Attr.getLoc(), diag::err_new_abi_tag_on_redeclaration) << NewTag;
64695d6
+        S.Diag(OldAbiTagAttr->getLocation(), diag::note_previous_definition);
64695d6
+        return;
64695d6
+      }
64695d6
+    }
64695d6
+    return;
64695d6
+  }
64695d6
+
64695d6
+  D->addAttr(::new (S.Context) AbiTagAttr(Attr.getRange(), S.Context,
64695d6
+                                          Tags.data(), Tags.size(),
64695d6
+                                          Attr.getAttributeSpellingListIndex()));
64695d6
+}
64695d6
+
64695d6
 static void handleARMInterruptAttr(Sema &S, Decl *D,
64695d6
                                    const AttributeList &Attr) {
64695d6
   // Check the attribute arguments.
64695d6
@@ -4978,6 +5030,9 @@ static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
64695d6
   case AttributeList::AT_Thread:
64695d6
     handleDeclspecThreadAttr(S, D, Attr);
64695d6
     break;
64695d6
+  case AttributeList::AT_AbiTag:
64695d6
+    handleAbiTagAttr(S, D, Attr);
64695d6
+    break;
64695d6
 
64695d6
   // Thread safety attributes:
64695d6
   case AttributeList::AT_AssertExclusiveLock:
64695d6
-- 
64695d6
2.4.3
64695d6