head	1.1;
branch	1.1.1;
access;
symbols
	netbsd-11-0-RC4:1.1.1.13
	netbsd-11-0-RC3:1.1.1.13
	netbsd-11-0-RC2:1.1.1.13
	netbsd-11-0-RC1:1.1.1.13
	perseant-exfatfs-base-20250801:1.1.1.13
	netbsd-11:1.1.1.13.0.10
	netbsd-11-base:1.1.1.13
	netbsd-10-1-RELEASE:1.1.1.13
	perseant-exfatfs-base-20240630:1.1.1.13
	perseant-exfatfs:1.1.1.13.0.8
	perseant-exfatfs-base:1.1.1.13
	netbsd-8-3-RELEASE:1.1.1.10
	netbsd-9-4-RELEASE:1.1.1.12
	netbsd-10-0-RELEASE:1.1.1.13
	netbsd-10-0-RC6:1.1.1.13
	netbsd-10-0-RC5:1.1.1.13
	netbsd-10-0-RC4:1.1.1.13
	netbsd-10-0-RC3:1.1.1.13
	netbsd-10-0-RC2:1.1.1.13
	netbsd-10-0-RC1:1.1.1.13
	netbsd-10:1.1.1.13.0.6
	netbsd-10-base:1.1.1.13
	netbsd-9-3-RELEASE:1.1.1.12
	cjep_sun2x:1.1.1.13.0.4
	cjep_sun2x-base:1.1.1.13
	cjep_staticlib_x-base1:1.1.1.13
	netbsd-9-2-RELEASE:1.1.1.12
	cjep_staticlib_x:1.1.1.13.0.2
	cjep_staticlib_x-base:1.1.1.13
	netbsd-9-1-RELEASE:1.1.1.12
	phil-wifi-20200421:1.1.1.13
	phil-wifi-20200411:1.1.1.13
	phil-wifi-20200406:1.1.1.13
	netbsd-8-2-RELEASE:1.1.1.10
	netbsd-9-0-RELEASE:1.1.1.12
	netbsd-9-0-RC2:1.1.1.12
	netbsd-9-0-RC1:1.1.1.12
	netbsd-9:1.1.1.12.0.2
	netbsd-9-base:1.1.1.12
	phil-wifi-20190609:1.1.1.12
	netbsd-8-1-RELEASE:1.1.1.10
	netbsd-8-1-RC1:1.1.1.10
	pgoyette-compat-merge-20190127:1.1.1.11.2.1
	pgoyette-compat-20190127:1.1.1.12
	pgoyette-compat-20190118:1.1.1.12
	pgoyette-compat-1226:1.1.1.12
	pgoyette-compat-1126:1.1.1.12
	pgoyette-compat-1020:1.1.1.12
	pgoyette-compat-0930:1.1.1.12
	pgoyette-compat-0906:1.1.1.12
	netbsd-7-2-RELEASE:1.1.1.7.2.1
	pgoyette-compat-0728:1.1.1.12
	clang-337282:1.1.1.12
	netbsd-8-0-RELEASE:1.1.1.10
	phil-wifi:1.1.1.11.0.4
	phil-wifi-base:1.1.1.11
	pgoyette-compat-0625:1.1.1.11
	netbsd-8-0-RC2:1.1.1.10
	pgoyette-compat-0521:1.1.1.11
	pgoyette-compat-0502:1.1.1.11
	pgoyette-compat-0422:1.1.1.11
	netbsd-8-0-RC1:1.1.1.10
	pgoyette-compat-0415:1.1.1.11
	pgoyette-compat-0407:1.1.1.11
	pgoyette-compat-0330:1.1.1.11
	pgoyette-compat-0322:1.1.1.11
	pgoyette-compat-0315:1.1.1.11
	netbsd-7-1-2-RELEASE:1.1.1.7.2.1
	pgoyette-compat:1.1.1.11.0.2
	pgoyette-compat-base:1.1.1.11
	netbsd-7-1-1-RELEASE:1.1.1.7.2.1
	clang-319952:1.1.1.11
	matt-nb8-mediatek:1.1.1.10.0.10
	matt-nb8-mediatek-base:1.1.1.10
	clang-309604:1.1.1.11
	perseant-stdc-iso10646:1.1.1.10.0.8
	perseant-stdc-iso10646-base:1.1.1.10
	netbsd-8:1.1.1.10.0.6
	netbsd-8-base:1.1.1.10
	prg-localcount2-base3:1.1.1.10
	prg-localcount2-base2:1.1.1.10
	prg-localcount2-base1:1.1.1.10
	prg-localcount2:1.1.1.10.0.4
	prg-localcount2-base:1.1.1.10
	pgoyette-localcount-20170426:1.1.1.10
	bouyer-socketcan-base1:1.1.1.10
	pgoyette-localcount-20170320:1.1.1.10
	netbsd-7-1:1.1.1.7.2.1.0.6
	netbsd-7-1-RELEASE:1.1.1.7.2.1
	netbsd-7-1-RC2:1.1.1.7.2.1
	clang-294123:1.1.1.10
	netbsd-7-nhusb-base-20170116:1.1.1.7.2.1
	bouyer-socketcan:1.1.1.10.0.2
	bouyer-socketcan-base:1.1.1.10
	clang-291444:1.1.1.10
	pgoyette-localcount-20170107:1.1.1.9
	netbsd-7-1-RC1:1.1.1.7.2.1
	pgoyette-localcount-20161104:1.1.1.9
	netbsd-7-0-2-RELEASE:1.1.1.7.2.1
	localcount-20160914:1.1.1.9
	netbsd-7-nhusb:1.1.1.7.2.1.0.4
	netbsd-7-nhusb-base:1.1.1.7.2.1
	clang-280599:1.1.1.9
	pgoyette-localcount-20160806:1.1.1.9
	pgoyette-localcount-20160726:1.1.1.9
	pgoyette-localcount:1.1.1.9.0.2
	pgoyette-localcount-base:1.1.1.9
	netbsd-7-0-1-RELEASE:1.1.1.7.2.1
	clang-261930:1.1.1.9
	netbsd-7-0:1.1.1.7.2.1.0.2
	netbsd-7-0-RELEASE:1.1.1.7.2.1
	netbsd-7-0-RC3:1.1.1.7.2.1
	netbsd-7-0-RC2:1.1.1.7.2.1
	netbsd-7-0-RC1:1.1.1.7.2.1
	clang-237755:1.1.1.8
	clang-232565:1.1.1.8
	clang-227398:1.1.1.8
	tls-maxphys-base:1.1.1.7
	tls-maxphys:1.1.1.7.0.4
	netbsd-7:1.1.1.7.0.2
	netbsd-7-base:1.1.1.7
	clang-215315:1.1.1.7
	clang-209886:1.1.1.6
	yamt-pagecache:1.1.1.5.0.4
	yamt-pagecache-base9:1.1.1.5
	tls-earlyentropy:1.1.1.5.0.2
	tls-earlyentropy-base:1.1.1.6
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.1.1.5
	riastradh-drm2-base3:1.1.1.5
	clang-202566:1.1.1.5
	clang-201163:1.1.1.4
	clang-199312:1.1.1.3
	clang-198450:1.1.1.2
	clang-196603:1.1.1.1
	clang-195771:1.1.1.1
	LLVM:1.1.1;
locks; strict;
comment	@// @;


1.1
date	2013.11.28.14.14.48;	author joerg;	state Exp;
branches
	1.1.1.1;
next	;
commitid	ow8OybrawrB1f3fx;

1.1.1.1
date	2013.11.28.14.14.48;	author joerg;	state Exp;
branches;
next	1.1.1.2;
commitid	ow8OybrawrB1f3fx;

1.1.1.2
date	2014.01.05.15.37.51;	author joerg;	state Exp;
branches;
next	1.1.1.3;
commitid	wh3aCSIWykURqWjx;

1.1.1.3
date	2014.01.15.21.26.17;	author joerg;	state Exp;
branches;
next	1.1.1.4;
commitid	NQXlzzA0SPkc5glx;

1.1.1.4
date	2014.02.14.20.07.01;	author joerg;	state Exp;
branches;
next	1.1.1.5;
commitid	annVkZ1sc17rF6px;

1.1.1.5
date	2014.03.04.19.53.17;	author joerg;	state Exp;
branches
	1.1.1.5.2.1
	1.1.1.5.4.1;
next	1.1.1.6;
commitid	29z1hJonZISIXprx;

1.1.1.6
date	2014.05.30.18.14.50;	author joerg;	state Exp;
branches;
next	1.1.1.7;
commitid	8q0kdlBlCn09GACx;

1.1.1.7
date	2014.08.10.17.08.25;	author joerg;	state Exp;
branches
	1.1.1.7.2.1
	1.1.1.7.4.1;
next	1.1.1.8;
commitid	N85tXAN6Ex9VZPLx;

1.1.1.8
date	2015.01.29.19.57.27;	author joerg;	state Exp;
branches;
next	1.1.1.9;
commitid	mlISSizlPKvepX7y;

1.1.1.9
date	2016.02.27.22.11.00;	author joerg;	state Exp;
branches
	1.1.1.9.2.1;
next	1.1.1.10;
commitid	tIimz3oDlh1NpBWy;

1.1.1.10
date	2017.01.11.10.33.11;	author joerg;	state Exp;
branches;
next	1.1.1.11;
commitid	CNnUNfII1jgNmxBz;

1.1.1.11
date	2017.08.01.19.34.43;	author joerg;	state Exp;
branches
	1.1.1.11.2.1
	1.1.1.11.4.1;
next	1.1.1.12;
commitid	pMuDy65V0VicSx1A;

1.1.1.12
date	2018.07.17.18.31.59;	author joerg;	state Exp;
branches;
next	1.1.1.13;
commitid	wDzL46ALjrCZgwKA;

1.1.1.13
date	2019.11.13.22.23.13;	author joerg;	state dead;
branches;
next	;
commitid	QD8YATxuNG34YJKB;

1.1.1.5.2.1
date	2014.08.10.07.08.26;	author tls;	state Exp;
branches;
next	;
commitid	t01A1TLTYxkpGMLx;

1.1.1.5.4.1
date	2014.03.04.19.53.17;	author yamt;	state dead;
branches;
next	1.1.1.5.4.2;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.5.4.2
date	2014.05.22.16.19.50;	author yamt;	state Exp;
branches;
next	;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.7.2.1
date	2015.06.04.20.04.47;	author snj;	state Exp;
branches;
next	;
commitid	yRnjq9fueSo6n9oy;

1.1.1.7.4.1
date	2014.08.10.17.08.25;	author tls;	state dead;
branches;
next	1.1.1.7.4.2;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.7.4.2
date	2014.08.19.23.49.29;	author tls;	state Exp;
branches;
next	;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.9.2.1
date	2017.03.20.06.53.40;	author pgoyette;	state Exp;
branches;
next	;
commitid	jjw7cAwgyKq7RfKz;

1.1.1.11.2.1
date	2018.07.28.04.34.20;	author pgoyette;	state Exp;
branches;
next	;
commitid	1UP1xAIUxv1ZgRLA;

1.1.1.11.4.1
date	2019.06.10.21.46.48;	author christos;	state Exp;
branches;
next	1.1.1.11.4.2;
commitid	jtc8rnCzWiEEHGqB;

1.1.1.11.4.2
date	2020.04.13.07.50.41;	author martin;	state dead;
branches;
next	;
commitid	X01YhRUPVUDaec4C;


desc
@@


1.1
log
@Initial revision
@
text
@//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang attribute processing code
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/StringMatcher.h"
#include "llvm/TableGen/TableGenBackend.h"
#include <algorithm>
#include <cctype>

using namespace llvm;

static const std::vector<StringRef>
getValueAsListOfStrings(Record &R, StringRef FieldName) {
  ListInit *List = R.getValueAsListInit(FieldName);
  assert (List && "Got a null ListInit");

  std::vector<StringRef> Strings;
  Strings.reserve(List->getSize());

  for (ListInit::const_iterator i = List->begin(), e = List->end();
       i != e;
       ++i) {
    assert(*i && "Got a null element in a ListInit");
    if (StringInit *S = dyn_cast<StringInit>(*i))
      Strings.push_back(S->getValue());
    else
      assert(false && "Got a non-string, non-code element in a ListInit");
  }

  return Strings;
}

static std::string ReadPCHRecord(StringRef type) {
  return StringSwitch<std::string>(type)
    .EndsWith("Decl *", "GetLocalDeclAs<" 
              + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
    .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
    .Case("Expr *", "ReadExpr(F)")
    .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
    .Case("SourceLocation", "ReadSourceLocation(F, Record, Idx)")
    .Default("Record[Idx++]");
}

// Assumes that the way to get the value is SA->getname()
static std::string WritePCHRecord(StringRef type, StringRef name) {
  return StringSwitch<std::string>(type)
    .EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
                        ", Record);\n")
    .Case("TypeSourceInfo *",
          "AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
    .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
    .Case("IdentifierInfo *", 
          "AddIdentifierRef(" + std::string(name) + ", Record);\n")
    .Case("SourceLocation", 
          "AddSourceLocation(" + std::string(name) + ", Record);\n")
    .Default("Record.push_back(" + std::string(name) + ");\n");
}

// Normalize attribute name by removing leading and trailing
// underscores. For example, __foo, foo__, __foo__ would
// become foo.
static StringRef NormalizeAttrName(StringRef AttrName) {
  if (AttrName.startswith("__"))
    AttrName = AttrName.substr(2, AttrName.size());

  if (AttrName.endswith("__"))
    AttrName = AttrName.substr(0, AttrName.size() - 2);

  return AttrName;
}

// Normalize attribute spelling only if the spelling has both leading
// and trailing underscores. For example, __ms_struct__ will be 
// normalized to "ms_struct"; __cdecl will remain intact.
static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
  if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
    AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
  }

  return AttrSpelling;
}

namespace {
  class Argument {
    std::string lowerName, upperName;
    StringRef attrName;
    bool isOpt;

  public:
    Argument(Record &Arg, StringRef Attr)
      : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
        attrName(Attr), isOpt(false) {
      if (!lowerName.empty()) {
        lowerName[0] = std::tolower(lowerName[0]);
        upperName[0] = std::toupper(upperName[0]);
      }
    }
    virtual ~Argument() {}

    StringRef getLowerName() const { return lowerName; }
    StringRef getUpperName() const { return upperName; }
    StringRef getAttrName() const { return attrName; }

    bool isOptional() const { return isOpt; }
    void setOptional(bool set) { isOpt = set; }

    // These functions print the argument contents formatted in different ways.
    virtual void writeAccessors(raw_ostream &OS) const = 0;
    virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
    virtual void writeCloneArgs(raw_ostream &OS) const = 0;
    virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
    virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
    virtual void writeCtorBody(raw_ostream &OS) const {}
    virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
    virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
    virtual void writeCtorParameters(raw_ostream &OS) const = 0;
    virtual void writeDeclarations(raw_ostream &OS) const = 0;
    virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
    virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
    virtual void writePCHWrite(raw_ostream &OS) const = 0;
    virtual void writeValue(raw_ostream &OS) const = 0;
    virtual void writeDump(raw_ostream &OS) const = 0;
    virtual void writeDumpChildren(raw_ostream &OS) const {}
    virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }

    virtual bool isEnumArg() const { return false; }
    virtual bool isVariadicEnumArg() const { return false; }
  };

  class SimpleArgument : public Argument {
    std::string type;

  public:
    SimpleArgument(Record &Arg, StringRef Attr, std::string T)
      : Argument(Arg, Attr), type(T)
    {}

    std::string getType() const { return type; }

    void writeAccessors(raw_ostream &OS) const {
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "(" << getUpperName() << ")";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "()";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << type << " " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << type << " " << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      std::string read = ReadPCHRecord(type);
      OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    " << WritePCHRecord(type, "SA->get" +
                                           std::string(getUpperName()) + "()");
    }
    void writeValue(raw_ostream &OS) const {
      if (type == "FunctionDecl *") {
        OS << "\" << get" << getUpperName()
           << "()->getNameInfo().getAsString() << \"";
      } else if (type == "IdentifierInfo *") {
        OS << "\" << get" << getUpperName() << "()->getName() << \"";
      } else if (type == "TypeSourceInfo *") {
        OS << "\" << get" << getUpperName() << "().getAsString() << \"";
      } else if (type == "SourceLocation") {
        OS << "\" << get" << getUpperName() << "().getRawEncoding() << \"";
      } else {
        OS << "\" << get" << getUpperName() << "() << \"";
      }
    }
    void writeDump(raw_ostream &OS) const {
      if (type == "FunctionDecl *") {
        OS << "    OS << \" \";\n";
        OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n"; 
      } else if (type == "IdentifierInfo *") {
        OS << "    OS << \" \" << SA->get" << getUpperName()
           << "()->getName();\n";
      } else if (type == "TypeSourceInfo *") {
        OS << "    OS << \" \" << SA->get" << getUpperName()
           << "().getAsString();\n";
      } else if (type == "SourceLocation") {
        OS << "    OS << \" \";\n";
        OS << "    SA->get" << getUpperName() << "().print(OS, *SM);\n";
      } else if (type == "bool") {
        OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
           << getUpperName() << "\";\n";
      } else if (type == "int" || type == "unsigned") {
        OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
      } else {
        llvm_unreachable("Unknown SimpleArgument type!");
      }
    }
  };

  class StringArgument : public Argument {
  public:
    StringArgument(Record &Arg, StringRef Attr)
      : Argument(Arg, Attr)
    {}

    void writeAccessors(raw_ostream &OS) const {
      OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
      OS << "    return llvm::StringRef(" << getLowerName() << ", "
         << getLowerName() << "Length);\n";
      OS << "  }\n";
      OS << "  unsigned get" << getUpperName() << "Length() const {\n";
      OS << "    return " << getLowerName() << "Length;\n";
      OS << "  }\n";
      OS << "  void set" << getUpperName()
         << "(ASTContext &C, llvm::StringRef S) {\n";
      OS << "    " << getLowerName() << "Length = S.size();\n";
      OS << "    this->" << getLowerName() << " = new (C, 1) char ["
         << getLowerName() << "Length];\n";
      OS << "    std::memcpy(this->" << getLowerName() << ", S.data(), "
         << getLowerName() << "Length);\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << "get" << getUpperName() << "()";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorBody(raw_ostream &OS) const {
      OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName()
         << ".data(), " << getLowerName() << "Length);";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
         << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
         << "Length])";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "Length(0)," << getLowerName() << "(0)";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << "llvm::StringRef " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << "unsigned " << getLowerName() << "Length;\n";
      OS << "char *" << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    std::string " << getLowerName()
         << "= ReadString(Record, Idx);\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    AddString(SA->get" << getUpperName() << "(), Record);\n";
    }
    void writeValue(raw_ostream &OS) const {
      OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
         << "() << \"\\\"\";\n";
    }
  };

  class AlignedArgument : public Argument {
  public:
    AlignedArgument(Record &Arg, StringRef Attr)
      : Argument(Arg, Attr)
    {}

    void writeAccessors(raw_ostream &OS) const {
      OS << "  bool is" << getUpperName() << "Dependent() const;\n";

      OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";

      OS << "  bool is" << getUpperName() << "Expr() const {\n";
      OS << "    return is" << getLowerName() << "Expr;\n";
      OS << "  }\n";

      OS << "  Expr *get" << getUpperName() << "Expr() const {\n";
      OS << "    assert(is" << getLowerName() << "Expr);\n";
      OS << "    return " << getLowerName() << "Expr;\n";
      OS << "  }\n";

      OS << "  TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
      OS << "    assert(!is" << getLowerName() << "Expr);\n";
      OS << "    return " << getLowerName() << "Type;\n";
      OS << "  }";
    }
    void writeAccessorDefinitions(raw_ostream &OS) const {
      OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
         << "Dependent() const {\n";
      OS << "  if (is" << getLowerName() << "Expr)\n";
      OS << "    return " << getLowerName() << "Expr && (" << getLowerName()
         << "Expr->isValueDependent() || " << getLowerName()
         << "Expr->isTypeDependent());\n"; 
      OS << "  else\n";
      OS << "    return " << getLowerName()
         << "Type->getType()->isDependentType();\n";
      OS << "}\n";

      // FIXME: Do not do the calculation here
      // FIXME: Handle types correctly
      // A null pointer means maximum alignment
      // FIXME: Load the platform-specific maximum alignment, rather than
      //        16, the x86 max.
      OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
         << "(ASTContext &Ctx) const {\n";
      OS << "  assert(!is" << getUpperName() << "Dependent());\n";
      OS << "  if (is" << getLowerName() << "Expr)\n";
      OS << "    return (" << getLowerName() << "Expr ? " << getLowerName()
         << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue() : 16)"
         << "* Ctx.getCharWidth();\n";
      OS << "  else\n";
      OS << "    return 0; // FIXME\n";
      OS << "}\n";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << "is" << getLowerName() << "Expr, is" << getLowerName()
         << "Expr ? static_cast<void*>(" << getLowerName()
         << "Expr) : " << getLowerName()
         << "Type";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      // FIXME: move the definition in Sema::InstantiateAttrs to here.
      // In the meantime, aligned attributes are cloned.
    }
    void writeCtorBody(raw_ostream &OS) const {
      OS << "    if (is" << getLowerName() << "Expr)\n";
      OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
         << getUpperName() << ");\n";
      OS << "    else\n";
      OS << "       " << getLowerName()
         << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
         << ");";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << "is" << getLowerName() << "Expr(false)";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << "bool is" << getLowerName() << "Expr;\n";
      OS << "union {\n";
      OS << "Expr *" << getLowerName() << "Expr;\n";
      OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
      OS << "};";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    bool is" << getLowerName() << "Expr = Record[Idx++];\n";
      OS << "    void *" << getLowerName() << "Ptr;\n";
      OS << "    if (is" << getLowerName() << "Expr)\n";
      OS << "      " << getLowerName() << "Ptr = ReadExpr(F);\n";
      OS << "    else\n";
      OS << "      " << getLowerName()
         << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
      OS << "    if (SA->is" << getUpperName() << "Expr())\n";
      OS << "      AddStmt(SA->get" << getUpperName() << "Expr());\n";
      OS << "    else\n";
      OS << "      AddTypeSourceInfo(SA->get" << getUpperName()
         << "Type(), Record);\n";
    }
    void writeValue(raw_ostream &OS) const {
      OS << "\";\n"
         << "  " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n"
         << "  OS << \"";
    }
    void writeDump(raw_ostream &OS) const {
    }
    void writeDumpChildren(raw_ostream &OS) const {
      OS << "    if (SA->is" << getUpperName() << "Expr()) {\n";
      OS << "      lastChild();\n";
      OS << "      dumpStmt(SA->get" << getUpperName() << "Expr());\n";
      OS << "    } else\n";
      OS << "      dumpType(SA->get" << getUpperName()
         << "Type()->getType());\n";
    }
    void writeHasChildren(raw_ostream &OS) const {
      OS << "SA->is" << getUpperName() << "Expr()";
    }
  };

  class VariadicArgument : public Argument {
    std::string type;

  public:
    VariadicArgument(Record &Arg, StringRef Attr, std::string T)
      : Argument(Arg, Attr), type(T)
    {}

    std::string getType() const { return type; }

    void writeAccessors(raw_ostream &OS) const {
      OS << "  typedef " << type << "* " << getLowerName() << "_iterator;\n";
      OS << "  " << getLowerName() << "_iterator " << getLowerName()
         << "_begin() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }\n";
      OS << "  " << getLowerName() << "_iterator " << getLowerName()
         << "_end() const {\n";
      OS << "    return " << getLowerName() << " + " << getLowerName()
         << "Size;\n";
      OS << "  }\n";
      OS << "  unsigned " << getLowerName() << "_size() const {\n"
         << "    return " << getLowerName() << "Size;\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << getLowerName() << ", " << getLowerName() << "Size";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      // This isn't elegant, but we have to go through public methods...
      OS << "A->" << getLowerName() << "_begin(), "
         << "A->" << getLowerName() << "_size()";
    }
    void writeCtorBody(raw_ostream &OS) const {
      // FIXME: memcpy is not safe on non-trivial types.
      OS << "    std::memcpy(" << getLowerName() << ", " << getUpperName()
         << ", " << getLowerName() << "Size * sizeof(" << getType() << "));\n";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "Size(" << getUpperName() << "Size), "
         << getLowerName() << "(new (Ctx, 16) " << getType() << "["
         << getLowerName() << "Size])";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "Size(0), " << getLowerName() << "(0)";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << getType() << " *" << getUpperName() << ", unsigned "
         << getUpperName() << "Size";
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << "  unsigned " << getLowerName() << "Size;\n";
      OS << "  " << getType() << " *" << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "  unsigned " << getLowerName() << "Size = Record[Idx++];\n";
      OS << "  SmallVector<" << type << ", 4> " << getLowerName()
         << ";\n";
      OS << "  " << getLowerName() << ".reserve(" << getLowerName()
         << "Size);\n";
      OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
      
      std::string read = ReadPCHRecord(type);
      OS << "    " << getLowerName() << ".push_back(" << read << ");\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName() << ".data(), " << getLowerName() << "Size";
    }
    void writePCHWrite(raw_ostream &OS) const{
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
         << getLowerName() << "_end(); i != e; ++i)\n";
      OS << "      " << WritePCHRecord(type, "(*i)");
    }
    void writeValue(raw_ostream &OS) const {
      OS << "\";\n";
      OS << "  bool isFirst = true;\n"
         << "  for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator i = " << getLowerName() << "_begin(), e = "
         << getLowerName() << "_end(); i != e; ++i) {\n"
         << "    if (isFirst) isFirst = false;\n"
         << "    else OS << \", \";\n"
         << "    OS << *i;\n"
         << "  }\n";
      OS << "  OS << \"";
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
         << getLowerName() << "_end(); I != E; ++I)\n";
      OS << "      OS << \" \" << *I;\n";
    }
  };

  class EnumArgument : public Argument {
    std::string type;
    std::vector<StringRef> values, enums, uniques;
  public:
    EnumArgument(Record &Arg, StringRef Attr)
      : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
        values(getValueAsListOfStrings(Arg, "Values")),
        enums(getValueAsListOfStrings(Arg, "Enums")),
        uniques(enums)
    {
      // Calculate the various enum values
      std::sort(uniques.begin(), uniques.end());
      uniques.erase(std::unique(uniques.begin(), uniques.end()), uniques.end());
      // FIXME: Emit a proper error
      assert(!uniques.empty());
    }

    bool isEnumArg() const { return true; }

    void writeAccessors(raw_ostream &OS) const {
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "(" << getUpperName() << ")";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "(" << type << "(0))";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << type << " " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      std::vector<StringRef>::const_iterator i = uniques.begin(),
                                             e = uniques.end();
      // The last one needs to not have a comma.
      --e;

      OS << "public:\n";
      OS << "  enum " << type << " {\n";
      for (; i != e; ++i)
        OS << "    " << *i << ",\n";
      OS << "    " << *e << "\n";
      OS << "  };\n";
      OS << "private:\n";
      OS << "  " << type << " " << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    " << getAttrName() << "Attr::" << type << " " << getLowerName()
         << "(static_cast<" << getAttrName() << "Attr::" << type
         << ">(Record[Idx++]));\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
    }
    void writeValue(raw_ostream &OS) const {
      OS << "\" << get" << getUpperName() << "() << \"";
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    switch(SA->get" << getUpperName() << "()) {\n";
      for (std::vector<StringRef>::const_iterator I = uniques.begin(),
           E = uniques.end(); I != E; ++I) {
        OS << "    case " << getAttrName() << "Attr::" << *I << ":\n";
        OS << "      OS << \" " << *I << "\";\n";
        OS << "      break;\n";
      }
      OS << "    }\n";
    }

    void writeConversion(raw_ostream &OS) const {
      OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
      OS << type << " &Out) {\n";
      OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
      OS << type << "> >(Val)\n";
      for (size_t I = 0; I < enums.size(); ++I) {
        OS << "      .Case(\"" << values[I] << "\", ";
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
      }
      OS << "      .Default(Optional<" << type << ">());\n";
      OS << "    if (R) {\n";
      OS << "      Out = *R;\n      return true;\n    }\n";
      OS << "    return false;\n";
      OS << "  }\n";
    }
  };
  
  class VariadicEnumArgument: public VariadicArgument {
    std::string type, QualifiedTypeName;
    std::vector<StringRef> values, enums, uniques;
  public:
    VariadicEnumArgument(Record &Arg, StringRef Attr)
      : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
        type(Arg.getValueAsString("Type")),
        values(getValueAsListOfStrings(Arg, "Values")),
        enums(getValueAsListOfStrings(Arg, "Enums")),
        uniques(enums)
    {
      // Calculate the various enum values
      std::sort(uniques.begin(), uniques.end());
      uniques.erase(std::unique(uniques.begin(), uniques.end()), uniques.end());
      
      QualifiedTypeName = getAttrName().str() + "Attr::" + type;
      
      // FIXME: Emit a proper error
      assert(!uniques.empty());
    }

    bool isVariadicEnumArg() const { return true; }
    
    void writeDeclarations(raw_ostream &OS) const {
      std::vector<StringRef>::const_iterator i = uniques.begin(),
                                             e = uniques.end();
      // The last one needs to not have a comma.
      --e;

      OS << "public:\n";
      OS << "  enum " << type << " {\n";
      for (; i != e; ++i)
        OS << "    " << *i << ",\n";
      OS << "    " << *e << "\n";
      OS << "  };\n";
      OS << "private:\n";
      
      VariadicArgument::writeDeclarations(OS);
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
         << getLowerName() << "_end(); I != E; ++I) {\n";
      OS << "      switch(*I) {\n";
      for (std::vector<StringRef>::const_iterator UI = uniques.begin(),
           UE = uniques.end(); UI != UE; ++UI) {
        OS << "    case " << getAttrName() << "Attr::" << *UI << ":\n";
        OS << "      OS << \" " << *UI << "\";\n";
        OS << "      break;\n";
      }
      OS << "      }\n";
      OS << "    }\n";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    unsigned " << getLowerName() << "Size = Record[Idx++];\n";
      OS << "    SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
         << ";\n";
      OS << "    " << getLowerName() << ".reserve(" << getLowerName()
         << "Size);\n";
      OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
      OS << "      " << getLowerName() << ".push_back(" << "static_cast<"
         << QualifiedTypeName << ">(Record[Idx++]));\n";
    }
    void writePCHWrite(raw_ostream &OS) const{
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
         << getLowerName() << "_end(); i != e; ++i)\n";
      OS << "      " << WritePCHRecord(QualifiedTypeName, "(*i)");
    }
    void writeConversion(raw_ostream &OS) const {
      OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
      OS << type << " &Out) {\n";
      OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
      OS << type << "> >(Val)\n";
      for (size_t I = 0; I < enums.size(); ++I) {
        OS << "      .Case(\"" << values[I] << "\", ";
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
      }
      OS << "      .Default(Optional<" << type << ">());\n";
      OS << "    if (R) {\n";
      OS << "      Out = *R;\n      return true;\n    }\n";
      OS << "    return false;\n";
      OS << "  }\n";
    }
  };

  class VersionArgument : public Argument {
  public:
    VersionArgument(Record &Arg, StringRef Attr)
      : Argument(Arg, Attr)
    {}

    void writeAccessors(raw_ostream &OS) const {
      OS << "  VersionTuple get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }\n";
      OS << "  void set" << getUpperName() 
         << "(ASTContext &C, VersionTuple V) {\n";
      OS << "    " << getLowerName() << " = V;\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << "get" << getUpperName() << "()";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorBody(raw_ostream &OS) const {
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "(" << getUpperName() << ")";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "()";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << "VersionTuple " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << "VersionTuple " << getLowerName() << ";\n";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    VersionTuple " << getLowerName()
         << "= ReadVersionTuple(Record, Idx);\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
    }
    void writeValue(raw_ostream &OS) const {
      OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
    }
  };

  class ExprArgument : public SimpleArgument {
  public:
    ExprArgument(Record &Arg, StringRef Attr)
      : SimpleArgument(Arg, Attr, "Expr *")
    {}

    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "tempInst" << getUpperName();
    }

    void writeTemplateInstantiation(raw_ostream &OS) const {
      OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
      OS << "      {\n";
      OS << "        EnterExpressionEvaluationContext "
         << "Unevaluated(S, Sema::Unevaluated);\n";
      OS << "        ExprResult " << "Result = S.SubstExpr("
         << "A->get" << getUpperName() << "(), TemplateArgs);\n";
      OS << "        tempInst" << getUpperName() << " = "
         << "Result.takeAs<Expr>();\n";
      OS << "      }\n";
    }

    void writeDump(raw_ostream &OS) const {
    }

    void writeDumpChildren(raw_ostream &OS) const {
      OS << "    lastChild();\n";
      OS << "    dumpStmt(SA->get" << getUpperName() << "());\n";
    }
    void writeHasChildren(raw_ostream &OS) const { OS << "true"; }
  };

  class VariadicExprArgument : public VariadicArgument {
  public:
    VariadicExprArgument(Record &Arg, StringRef Attr)
      : VariadicArgument(Arg, Attr, "Expr *")
    {}

    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "tempInst" << getUpperName() << ", "
         << "A->" << getLowerName() << "_size()";
    }

    void writeTemplateInstantiation(raw_ostream &OS) const {
      OS << "      " << getType() << " *tempInst" << getUpperName()
         << " = new (C, 16) " << getType()
         << "[A->" << getLowerName() << "_size()];\n";
      OS << "      {\n";
      OS << "        EnterExpressionEvaluationContext "
         << "Unevaluated(S, Sema::Unevaluated);\n";
      OS << "        " << getType() << " *TI = tempInst" << getUpperName()
         << ";\n";
      OS << "        " << getType() << " *I = A->" << getLowerName()
         << "_begin();\n";
      OS << "        " << getType() << " *E = A->" << getLowerName()
         << "_end();\n";
      OS << "        for (; I != E; ++I, ++TI) {\n";
      OS << "          ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
      OS << "          *TI = Result.takeAs<Expr>();\n";
      OS << "        }\n";
      OS << "      }\n";
    }

    void writeDump(raw_ostream &OS) const {
    }

    void writeDumpChildren(raw_ostream &OS) const {
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
         << getLowerName() << "_end(); I != E; ++I) {\n";
      OS << "      if (I + 1 == E)\n";
      OS << "        lastChild();\n";
      OS << "      dumpStmt(*I);\n";
      OS << "    }\n";
    }

    void writeHasChildren(raw_ostream &OS) const {
      OS << "SA->" << getLowerName() << "_begin() != "
         << "SA->" << getLowerName() << "_end()";
    }
  };

  class TypeArgument : public SimpleArgument {
  public:
    TypeArgument(Record &Arg, StringRef Attr)
      : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
    {}

    void writeAccessors(raw_ostream &OS) const {
      OS << "  QualType get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << "->getType();\n";
      OS << "  }";
      OS << "  " << getType() << " get" << getUpperName() << "Loc() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "Loc()";
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    " << WritePCHRecord(
          getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
    }
  };
}

static Argument *createArgument(Record &Arg, StringRef Attr,
                                Record *Search = 0) {
  if (!Search)
    Search = &Arg;

  Argument *Ptr = 0;
  llvm::StringRef ArgName = Search->getName();

  if (ArgName == "AlignedArgument") Ptr = new AlignedArgument(Arg, Attr);
  else if (ArgName == "EnumArgument") Ptr = new EnumArgument(Arg, Attr);
  else if (ArgName == "ExprArgument") Ptr = new ExprArgument(Arg, Attr);
  else if (ArgName == "FunctionArgument")
    Ptr = new SimpleArgument(Arg, Attr, "FunctionDecl *");
  else if (ArgName == "IdentifierArgument")
    Ptr = new SimpleArgument(Arg, Attr, "IdentifierInfo *");
  else if (ArgName == "BoolArgument") Ptr = new SimpleArgument(Arg, Attr, 
                                                               "bool");
  else if (ArgName == "IntArgument") Ptr = new SimpleArgument(Arg, Attr, "int");
  else if (ArgName == "StringArgument") Ptr = new StringArgument(Arg, Attr);
  else if (ArgName == "TypeArgument") Ptr = new TypeArgument(Arg, Attr);
  else if (ArgName == "UnsignedArgument")
    Ptr = new SimpleArgument(Arg, Attr, "unsigned");
  else if (ArgName == "SourceLocArgument")
    Ptr = new SimpleArgument(Arg, Attr, "SourceLocation");
  else if (ArgName == "VariadicUnsignedArgument")
    Ptr = new VariadicArgument(Arg, Attr, "unsigned");
  else if (ArgName == "VariadicEnumArgument")
    Ptr = new VariadicEnumArgument(Arg, Attr);
  else if (ArgName == "VariadicExprArgument")
    Ptr = new VariadicExprArgument(Arg, Attr);
  else if (ArgName == "VersionArgument")
    Ptr = new VersionArgument(Arg, Attr);

  if (!Ptr) {
    std::vector<Record*> Bases = Search->getSuperClasses();
    for (std::vector<Record*>::iterator i = Bases.begin(), e = Bases.end();
         i != e; ++i) {
      Ptr = createArgument(Arg, Attr, *i);
      if (Ptr)
        break;
    }
  }

  if (Ptr && Arg.getValueAsBit("Optional"))
    Ptr->setOptional(true);

  return Ptr;
}

static void writeAvailabilityValue(raw_ostream &OS) {
  OS << "\" << getPlatform()->getName();\n"
     << "  if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
     << "  if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
     << "  if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
     << "  if (getUnavailable()) OS << \", unavailable\";\n"
     << "  OS << \"";
}

static void writePrettyPrintFunction(Record &R, std::vector<Argument*> &Args,
                                     raw_ostream &OS) {
  std::vector<Record*> Spellings = R.getValueAsListOfDefs("Spellings");

  OS << "void " << R.getName() << "Attr::printPretty("
    << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";

  if (Spellings.size() == 0) {
    OS << "}\n\n";
    return;
  }

  OS <<
    "  switch (SpellingListIndex) {\n"
    "  default:\n"
    "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
    "    break;\n";

  for (unsigned I = 0; I < Spellings.size(); ++ I) {
    llvm::SmallString<16> Prefix;
    llvm::SmallString<8> Suffix;
    // The actual spelling of the name and namespace (if applicable)
    // of an attribute without considering prefix and suffix.
    llvm::SmallString<64> Spelling;
    std::string Name = Spellings[I]->getValueAsString("Name");
    std::string Variety = Spellings[I]->getValueAsString("Variety");

    if (Variety == "GNU") {
      Prefix = " __attribute__((";
      Suffix = "))";
    } else if (Variety == "CXX11") {
      Prefix = " [[";
      Suffix = "]]";
      std::string Namespace = Spellings[I]->getValueAsString("Namespace");
      if (Namespace != "") {
        Spelling += Namespace;
        Spelling += "::";
      }
    } else if (Variety == "Declspec") {
      Prefix = " __declspec(";
      Suffix = ")";
    } else if (Variety == "Keyword") {
      Prefix = " ";
      Suffix = "";
    } else {
      llvm_unreachable("Unknown attribute syntax variety!");
    }

    Spelling += Name;

    OS <<
      "  case " << I << " : {\n"
      "    OS << \"" + Prefix.str() + Spelling.str();

    if (Args.size()) OS << "(";
    if (Spelling == "availability") {
      writeAvailabilityValue(OS);
    } else {
      for (std::vector<Argument*>::const_iterator I = Args.begin(),
           E = Args.end(); I != E; ++ I) {
        if (I != Args.begin()) OS << ", ";
        (*I)->writeValue(OS);
      }
    }

    if (Args.size()) OS << ")";
    OS << Suffix.str() + "\";\n";

    OS <<
      "    break;\n"
      "  }\n";
  }

  // End of the switch statement.
  OS << "}\n";
  // End of the print function.
  OS << "}\n\n";
}

/// \brief Return the index of a spelling in a spelling list.
static unsigned getSpellingListIndex(const std::vector<Record*> &SpellingList,
                                     const Record &Spelling) {
  assert(SpellingList.size() && "Spelling list is empty!");

  for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
    Record *S = SpellingList[Index];
    if (S->getValueAsString("Variety") != Spelling.getValueAsString("Variety"))
      continue;
    if (S->getValueAsString("Variety") == "CXX11" &&
        S->getValueAsString("Namespace") !=
        Spelling.getValueAsString("Namespace"))
      continue;
    if (S->getValueAsString("Name") != Spelling.getValueAsString("Name"))
      continue;

    return Index;
  }

  llvm_unreachable("Unknown spelling!");
}

static void writeAttrAccessorDefinition(Record &R, raw_ostream &OS) {
  std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
  for (std::vector<Record*>::const_iterator I = Accessors.begin(),
       E = Accessors.end(); I != E; ++I) {
    Record *Accessor = *I;
    std::string Name = Accessor->getValueAsString("Name");
    std::vector<Record*> Spellings = Accessor->getValueAsListOfDefs(
      "Spellings");
    std::vector<Record*> SpellingList = R.getValueAsListOfDefs("Spellings");
    assert(SpellingList.size() &&
           "Attribute with empty spelling list can't have accessors!");

    OS << "  bool " << Name << "() const { return SpellingListIndex == ";
    for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
      OS << getSpellingListIndex(SpellingList, *Spellings[Index]);
      if (Index != Spellings.size() -1)
        OS << " ||\n    SpellingListIndex == ";
      else
        OS << "; }\n";
    }
  }
}

namespace clang {

// Emits the class definitions for attributes.
void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute classes' definitions", OS);

  OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
  OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end();
       i != e; ++i) {
    Record &R = **i;
    
    if (!R.getValueAsBit("ASTNode"))
      continue;
    
    const std::vector<Record *> Supers = R.getSuperClasses();
    assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
    std::string SuperName;
    for (std::vector<Record *>::const_reverse_iterator I = Supers.rbegin(),
         E = Supers.rend(); I != E; ++I) {
      const Record &R = **I;
      if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
        SuperName = R.getName();
    }

    OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";

    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    std::vector<Argument*> Args;
    std::vector<Argument*>::iterator ai, ae;
    Args.reserve(ArgRecords.size());

    for (std::vector<Record*>::iterator ri = ArgRecords.begin(),
                                        re = ArgRecords.end();
         ri != re; ++ri) {
      Record &ArgRecord = **ri;
      Argument *Arg = createArgument(ArgRecord, R.getName());
      assert(Arg);
      Args.push_back(Arg);

      Arg->writeDeclarations(OS);
      OS << "\n\n";
    }

    ae = Args.end();

    OS << "\n public:\n";
    OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
    
    bool HasOpt = false;
    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << "              , ";
      (*ai)->writeCtorParameters(OS);
      OS << "\n";
      if ((*ai)->isOptional())
        HasOpt = true;
    }

    OS << "              , ";
    OS << "unsigned SI = 0\n";

    OS << "             )\n";
    OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";

    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << "              , ";
      (*ai)->writeCtorInitializers(OS);
      OS << "\n";
    }

    OS << "  {\n";
  
    for (ai = Args.begin(); ai != ae; ++ai) {
      (*ai)->writeCtorBody(OS);
      OS << "\n";
    }
    OS << "  }\n\n";

    // If there are optional arguments, write out a constructor that elides the
    // optional arguments as well.
    if (HasOpt) {
      OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
      for (ai = Args.begin(); ai != ae; ++ai) {
        if (!(*ai)->isOptional()) {
          OS << "              , ";
          (*ai)->writeCtorParameters(OS);
          OS << "\n";
        }
      }

      OS << "              , ";
      OS << "unsigned SI = 0\n";

      OS << "             )\n";
      OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";

      for (ai = Args.begin(); ai != ae; ++ai) {
        OS << "              , ";
        (*ai)->writeCtorDefaultInitializers(OS);
        OS << "\n";
      }

      OS << "  {\n";
  
      for (ai = Args.begin(); ai != ae; ++ai) {
        if (!(*ai)->isOptional()) {
          (*ai)->writeCtorBody(OS);
          OS << "\n";
        }
      }
      OS << "  }\n\n";
    }

    OS << "  virtual " << R.getName() << "Attr *clone (ASTContext &C) const;\n";
    OS << "  virtual void printPretty(raw_ostream &OS,\n"
       << "                           const PrintingPolicy &Policy) const;\n";

    writeAttrAccessorDefinition(R, OS);

    for (ai = Args.begin(); ai != ae; ++ai) {
      (*ai)->writeAccessors(OS);
      OS << "\n\n";

      if ((*ai)->isEnumArg()) {
        EnumArgument *EA = (EnumArgument *)*ai;
        EA->writeConversion(OS);
      } else if ((*ai)->isVariadicEnumArg()) {
        VariadicEnumArgument *VEA = (VariadicEnumArgument *)*ai;
        VEA->writeConversion(OS);
      }
    }

    OS << R.getValueAsString("AdditionalMembers");
    OS << "\n\n";

    OS << "  static bool classof(const Attr *A) { return A->getKind() == "
       << "attr::" << R.getName() << "; }\n";

    bool LateParsed = R.getValueAsBit("LateParsed");
    OS << "  virtual bool isLateParsed() const { return "
       << LateParsed << "; }\n";

    OS << "};\n\n";
  }

  OS << "#endif\n";
}

static bool isIdentifierArgument(Record *Arg) {
  return !Arg->getSuperClasses().empty() &&
         llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
             .Case("IdentifierArgument", true)
             .Case("EnumArgument", true)
             .Default(false);
}

/// \brief Emits the first-argument-is-type property for attributes.
void EmitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("llvm::StringSwitch code to match attributes with a "
                       "type argument", OS);

  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record *>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    // Determine whether the first argument is a type.
    std::vector<Record *> Args = Attr.getValueAsListOfDefs("Args");
    if (Args.empty())
      continue;

    if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
      continue;

    // All these spellings take a single type argument.
    std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
    std::set<std::string> Emitted;
    for (std::vector<Record*>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      if (Emitted.insert((*I)->getValueAsString("Name")).second)
        OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", "
           << "true" << ")\n";
    }
  }
}

// Emits the first-argument-is-identifier property for attributes.
void EmitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("llvm::StringSwitch code to match attributes with "
                       "an identifier argument", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    // Determine whether the first argument is an identifier.
    std::vector<Record *> Args = Attr.getValueAsListOfDefs("Args");
    if (Args.empty() || !isIdentifierArgument(Args[0]))
      continue;

    // All these spellings take an identifier argument.
    std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
    std::set<std::string> Emitted;
    for (std::vector<Record*>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      if (Emitted.insert((*I)->getValueAsString("Name")).second)
        OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", "
           << "true" << ")\n";
    }
  }
}

// Emits the class method definitions for attributes.
void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute classes' member function definitions", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end(), ri, re;
  std::vector<Argument*>::iterator ai, ae;

  for (; i != e; ++i) {
    Record &R = **i;
    
    if (!R.getValueAsBit("ASTNode"))
      continue;
    
    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    std::vector<Argument*> Args;
    for (ri = ArgRecords.begin(), re = ArgRecords.end(); ri != re; ++ri)
      Args.push_back(createArgument(**ri, R.getName()));

    for (ai = Args.begin(), ae = Args.end(); ai != ae; ++ai)
      (*ai)->writeAccessorDefinitions(OS);

    OS << R.getName() << "Attr *" << R.getName()
       << "Attr::clone(ASTContext &C) const {\n";
    OS << "  return new (C) " << R.getName() << "Attr(getLocation(), C";
    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << ", ";
      (*ai)->writeCloneArgs(OS);
    }
    OS << ", getSpellingListIndex());\n}\n\n";

    writePrettyPrintFunction(R, Args, OS);
  }
}

} // end namespace clang

static void EmitAttrList(raw_ostream &OS, StringRef Class,
                         const std::vector<Record*> &AttrList) {
  std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end();

  if (i != e) {
    // Move the end iterator back to emit the last attribute.
    for(--e; i != e; ++i) {
      if (!(*i)->getValueAsBit("ASTNode"))
        continue;
      
      OS << Class << "(" << (*i)->getName() << ")\n";
    }
    
    OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
  }
}

namespace clang {

// Emits the enumeration list for attributes.
void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);

  OS << "#ifndef LAST_ATTR\n";
  OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef INHERITABLE_ATTR\n";
  OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef LAST_INHERITABLE_ATTR\n";
  OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
  OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
  OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
        " INHERITABLE_PARAM_ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef MS_INHERITANCE_ATTR\n";
  OS << "#define MS_INHERITANCE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef LAST_MS_INHERITANCE_ATTR\n";
  OS << "#define LAST_MS_INHERITANCE_ATTR(NAME)"
        " MS_INHERITANCE_ATTR(NAME)\n";
  OS << "#endif\n\n";

  Record *InhClass = Records.getClass("InheritableAttr");
  Record *InhParamClass = Records.getClass("InheritableParamAttr");
  Record *MSInheritanceClass = Records.getClass("MSInheritanceAttr");
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
                       NonInhAttrs, InhAttrs, InhParamAttrs, MSInhAttrs;
  for (std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end();
       i != e; ++i) {
    if (!(*i)->getValueAsBit("ASTNode"))
      continue;
    
    if ((*i)->isSubClassOf(InhParamClass))
      InhParamAttrs.push_back(*i);
    else if ((*i)->isSubClassOf(MSInheritanceClass))
      MSInhAttrs.push_back(*i);
    else if ((*i)->isSubClassOf(InhClass))
      InhAttrs.push_back(*i);
    else
      NonInhAttrs.push_back(*i);
  }

  EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
  EmitAttrList(OS, "MS_INHERITANCE_ATTR", MSInhAttrs);
  EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
  EmitAttrList(OS, "ATTR", NonInhAttrs);

  OS << "#undef LAST_ATTR\n";
  OS << "#undef INHERITABLE_ATTR\n";
  OS << "#undef MS_INHERITANCE_ATTR\n";
  OS << "#undef LAST_INHERITABLE_ATTR\n";
  OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
  OS << "#undef LAST_MS_INHERITANCE_ATTR\n";
  OS << "#undef ATTR\n";
}

// Emits the code to read an attribute from a precompiled header.
void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute deserialization code", OS);

  Record *InhClass = Records.getClass("InheritableAttr");
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
                       ArgRecords;
  std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end(), ai, ae;
  std::vector<Argument*> Args;
  std::vector<Argument*>::iterator ri, re;

  OS << "  switch (Kind) {\n";
  OS << "  default:\n";
  OS << "    assert(0 && \"Unknown attribute!\");\n";
  OS << "    break;\n";
  for (; i != e; ++i) {
    Record &R = **i;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    
    OS << "  case attr::" << R.getName() << ": {\n";
    if (R.isSubClassOf(InhClass))
      OS << "    bool isInherited = Record[Idx++];\n";
    ArgRecords = R.getValueAsListOfDefs("Args");
    Args.clear();
    for (ai = ArgRecords.begin(), ae = ArgRecords.end(); ai != ae; ++ai) {
      Argument *A = createArgument(**ai, R.getName());
      Args.push_back(A);
      A->writePCHReadDecls(OS);
    }
    OS << "    New = new (Context) " << R.getName() << "Attr(Range, Context";
    for (ri = Args.begin(), re = Args.end(); ri != re; ++ri) {
      OS << ", ";
      (*ri)->writePCHReadArgs(OS);
    }
    OS << ");\n";
    if (R.isSubClassOf(InhClass))
      OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
    OS << "    break;\n";
    OS << "  }\n";
  }
  OS << "  }\n";
}

// Emits the code to write an attribute to a precompiled header.
void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute serialization code", OS);

  Record *InhClass = Records.getClass("InheritableAttr");
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end(), ai, ae;

  OS << "  switch (A->getKind()) {\n";
  OS << "  default:\n";
  OS << "    llvm_unreachable(\"Unknown attribute kind!\");\n";
  OS << "    break;\n";
  for (; i != e; ++i) {
    Record &R = **i;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    OS << "  case attr::" << R.getName() << ": {\n";
    Args = R.getValueAsListOfDefs("Args");
    if (R.isSubClassOf(InhClass) || !Args.empty())
      OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
         << "Attr>(A);\n";
    if (R.isSubClassOf(InhClass))
      OS << "    Record.push_back(SA->isInherited());\n";
    for (ai = Args.begin(), ae = Args.end(); ai != ae; ++ai)
      createArgument(**ai, R.getName())->writePCHWrite(OS);
    OS << "    break;\n";
    OS << "  }\n";
  }
  OS << "  }\n";
}

// Emits the list of spellings for attributes.
void EmitClangAttrSpellingList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("llvm::StringSwitch code to match all known attributes",
                       OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
    Record &Attr = **I;

    std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");

    for (std::vector<Record*>::const_iterator I = Spellings.begin(), E = Spellings.end(); I != E; ++I) {
      OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", true)\n";
    }
  }

}

void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Code to translate different attribute spellings "
                       "into internal identifiers", OS);

  OS <<
    "  unsigned Index = 0;\n"
    "  switch (AttrKind) {\n"
    "  default:\n"
    "    llvm_unreachable(\"Unknown attribute kind!\");\n"
    "    break;\n";

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  for (std::vector<Record*>::const_iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    // We only care about attributes that participate in Sema checking, so
    // skip those attributes that are not able to make their way to Sema.
    if (!R.getValueAsBit("SemaHandler"))
      continue;

    std::vector<Record*> Spellings = R.getValueAsListOfDefs("Spellings");
    // Each distinct spelling yields an attribute kind.
    if (R.getValueAsBit("DistinctSpellings")) {
      for (unsigned I = 0; I < Spellings.size(); ++ I) {
        OS <<
          "  case AT_" << Spellings[I]->getValueAsString("Name") << ": \n"
          "    Index = " << I << ";\n"
          "  break;\n";
      }
    } else {
      OS << "  case AT_" << R.getName() << " : {\n";
      for (unsigned I = 0; I < Spellings.size(); ++ I) {
        SmallString<16> Namespace;
        if (Spellings[I]->getValueAsString("Variety") == "CXX11")
          Namespace = Spellings[I]->getValueAsString("Namespace");
        else
          Namespace = "";

        OS << "    if (Name == \""
          << Spellings[I]->getValueAsString("Name") << "\" && "
          << "SyntaxUsed == "
          << StringSwitch<unsigned>(Spellings[I]->getValueAsString("Variety"))
            .Case("GNU", 0)
            .Case("CXX11", 1)
            .Case("Declspec", 2)
            .Case("Keyword", 3)
            .Default(0)
          << " && Scope == \"" << Namespace << "\")\n"
          << "        return " << I << ";\n";
      }

      OS << "    break;\n";
      OS << "  }\n";
    }
  }

  OS << "  }\n";
  OS << "  return Index;\n";
}

// Emits the LateParsed property for attributes.
void EmitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("llvm::StringSwitch code to match late parsed "
                       "attributes", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    bool LateParsed = Attr.getValueAsBit("LateParsed");

    if (LateParsed) {
      std::vector<Record*> Spellings =
        Attr.getValueAsListOfDefs("Spellings");

      // FIXME: Handle non-GNU attributes
      for (std::vector<Record*>::const_iterator I = Spellings.begin(),
           E = Spellings.end(); I != E; ++I) {
        if ((*I)->getValueAsString("Variety") != "GNU")
          continue;
        OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", "
           << LateParsed << ")\n";
      }
    }
  }
}

// Emits code to instantiate dependent attributes on templates.
void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Template instantiation code for attributes", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  OS << "namespace clang {\n"
     << "namespace sema {\n\n"
     << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
     << "Sema &S,\n"
     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
     << "  switch (At->getKind()) {\n"
     << "    default:\n"
     << "      break;\n";

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    if (!R.getValueAsBit("ASTNode"))
      continue;

    OS << "    case attr::" << R.getName() << ": {\n";
    bool ShouldClone = R.getValueAsBit("Clone");

    if (!ShouldClone) {
      OS << "      return NULL;\n";
      OS << "    }\n";
      continue;
    }

    OS << "      const " << R.getName() << "Attr *A = cast<"
       << R.getName() << "Attr>(At);\n";
    bool TDependent = R.getValueAsBit("TemplateDependent");

    if (!TDependent) {
      OS << "      return A->clone(C);\n";
      OS << "    }\n";
      continue;
    }

    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    std::vector<Argument*> Args;
    std::vector<Argument*>::iterator ai, ae;
    Args.reserve(ArgRecords.size());

    for (std::vector<Record*>::iterator ri = ArgRecords.begin(),
                                        re = ArgRecords.end();
         ri != re; ++ri) {
      Record &ArgRecord = **ri;
      Argument *Arg = createArgument(ArgRecord, R.getName());
      assert(Arg);
      Args.push_back(Arg);
    }
    ae = Args.end();

    for (ai = Args.begin(); ai != ae; ++ai) {
      (*ai)->writeTemplateInstantiation(OS);
    }
    OS << "      return new (C) " << R.getName() << "Attr(A->getLocation(), C";
    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << ", ";
      (*ai)->writeTemplateInstantiationArgs(OS);
    }
    OS << ");\n    }\n";
  }
  OS << "  } // end switch\n"
     << "  llvm_unreachable(\"Unknown attribute!\");\n"
     << "  return 0;\n"
     << "}\n\n"
     << "} // end namespace sema\n"
     << "} // end namespace clang\n";
}

typedef std::vector<std::pair<std::string, Record *> > ParsedAttrMap;

static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records) {
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  ParsedAttrMap R;
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;
    
    bool SemaHandler = Attr.getValueAsBit("SemaHandler");
    bool DistinctSpellings = Attr.getValueAsBit("DistinctSpellings");

    if (SemaHandler) {
      if (DistinctSpellings) {
        std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
        
        for (std::vector<Record*>::const_iterator I = Spellings.begin(),
             E = Spellings.end(); I != E; ++I) {
          std::string AttrName = (*I)->getValueAsString("Name");

          StringRef Spelling = NormalizeAttrName(AttrName);
          R.push_back(std::make_pair(Spelling.str(), &Attr));
        }
      } else {
        StringRef AttrName = Attr.getName();
        AttrName = NormalizeAttrName(AttrName);
        R.push_back(std::make_pair(AttrName.str(), *I));
      }
    }
  }
  return R;
}

// Emits the list of parsed attributes.
void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);

  OS << "#ifndef PARSED_ATTR\n";
  OS << "#define PARSED_ATTR(NAME) NAME\n";
  OS << "#endif\n\n";
  
  ParsedAttrMap Names = getParsedAttrList(Records);
  for (ParsedAttrMap::iterator I = Names.begin(), E = Names.end(); I != E;
       ++I) {
    OS << "PARSED_ATTR(" << I->first << ")\n";
  }
}

static void emitArgInfo(const Record &R, raw_ostream &OS) {
  // This function will count the number of arguments specified for the
  // attribute and emit the number of required arguments followed by the
  // number of optional arguments.
  std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
  unsigned ArgCount = 0, OptCount = 0;
  for (std::vector<Record *>::const_iterator I = Args.begin(), E = Args.end();
       I != E; ++I) {
    const Record &Arg = **I;
    Arg.getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
  }
  OS << ArgCount << ", " << OptCount;
}

/// Emits the parsed attribute helpers
void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Parsed attribute helpers", OS);

  ParsedAttrMap Attrs = getParsedAttrList(Records);

  OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
  for (ParsedAttrMap::iterator I = Attrs.begin(), E = Attrs.end(); I != E;
       ++I) {
    // We need to generate struct instances based off ParsedAttrInfo from
    // AttributeList.cpp.
    OS << "  { ";
    emitArgInfo(*I->second, OS);
    OS << ", " << I->second->getValueAsBit("HasCustomParsing");
    OS << " }";

    if (I + 1 != E)
      OS << ",";
    
    OS << "  // AT_" << I->first << "\n";
  }
  OS << "};\n\n";
}

// Emits the kind list of parsed attributes
void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute name matcher", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  std::vector<StringMatcher::StringPair> Matches;
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;
    
    bool SemaHandler = Attr.getValueAsBit("SemaHandler");
    bool Ignored = Attr.getValueAsBit("Ignored");
    bool DistinctSpellings = Attr.getValueAsBit("DistinctSpellings");
    if (SemaHandler || Ignored) {
      std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");

      for (std::vector<Record*>::const_iterator I = Spellings.begin(),
           E = Spellings.end(); I != E; ++I) {
        std::string RawSpelling = (*I)->getValueAsString("Name");
        StringRef AttrName = NormalizeAttrName(DistinctSpellings
                                                 ? StringRef(RawSpelling)
                                                 : StringRef(Attr.getName()));

        SmallString<64> Spelling;
        if ((*I)->getValueAsString("Variety") == "CXX11") {
          Spelling += (*I)->getValueAsString("Namespace");
          Spelling += "::";
        }
        Spelling += NormalizeAttrSpelling(RawSpelling);

        if (SemaHandler)
          Matches.push_back(
            StringMatcher::StringPair(
              StringRef(Spelling),
              "return AttributeList::AT_" + AttrName.str() + ";"));
        else
          Matches.push_back(
            StringMatcher::StringPair(
              StringRef(Spelling),
              "return AttributeList::IgnoredAttribute;"));
      }
    }
  }
  
  OS << "static AttributeList::Kind getAttrKind(StringRef Name) {\n";
  StringMatcher("Name", Matches, OS).Emit();
  OS << "return AttributeList::UnknownAttribute;\n"
     << "}\n";
}

// Emits the code to dump an attribute.
void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute dumper", OS);

  OS <<
    "  switch (A->getKind()) {\n"
    "  default:\n"
    "    llvm_unreachable(\"Unknown attribute kind!\");\n"
    "    break;\n";
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    OS << "  case attr::" << R.getName() << ": {\n";
    Args = R.getValueAsListOfDefs("Args");
    if (!Args.empty()) {
      OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
         << "Attr>(A);\n";
      for (std::vector<Record*>::iterator I = Args.begin(), E = Args.end();
           I != E; ++I)
        createArgument(**I, R.getName())->writeDump(OS);

      // Code for detecting the last child.
      OS << "    bool OldMoreChildren = hasMoreChildren();\n";
      OS << "    bool MoreChildren = OldMoreChildren;\n";     

      for (std::vector<Record*>::iterator I = Args.begin(), E = Args.end();
           I != E; ++I) {
        // More code for detecting the last child.
        OS << "    MoreChildren = OldMoreChildren";
        for (std::vector<Record*>::iterator Next = I + 1; Next != E; ++Next) {
          OS << " || ";
          createArgument(**Next, R.getName())->writeHasChildren(OS);
        }
        OS << ";\n";
        OS << "    setMoreChildren(MoreChildren);\n";

        createArgument(**I, R.getName())->writeDumpChildren(OS);
      }

      // Reset the last child.
      OS << "    setMoreChildren(OldMoreChildren);\n";
    }
    OS <<
      "    break;\n"
      "  }\n";
  }
  OS << "  }\n";
}

} // end namespace clang
@


1.1.1.1
log
@Import Clang 3.4rc1 r195771.
@
text
@@


1.1.1.2
log
@Import clang 3.5svn r198450.
@
text
@a19 1
#include "llvm/TableGen/Error.h"
a21 2
#include <sstream>
#include <set>
d53 1
d67 2
a95 29
typedef std::vector<std::pair<std::string, Record *> > ParsedAttrMap;

static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records) {
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::set<std::string> Seen;
  ParsedAttrMap R;
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;
    if (Attr.getValueAsBit("SemaHandler")) {
      std::string AN;
      if (Attr.isSubClassOf("TargetSpecificAttr") &&
          !Attr.isValueUnset("ParseKind")) {
        AN = Attr.getValueAsString("ParseKind");

        // If this attribute has already been handled, it does not need to be
        // handled again.
        if (Seen.find(AN) != Seen.end())
          continue;
        Seen.insert(AN);
      } else
        AN = NormalizeAttrName(Attr.getName()).str();

      R.push_back(std::make_pair(AN, *I));
    }
  }
  return R;
}

a122 1
    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
d195 2
d211 3
a224 16
  class DefaultSimpleArgument : public SimpleArgument {
    int64_t Default;

  public:
    DefaultSimpleArgument(Record &Arg, StringRef Attr,
                          std::string T, int64_t Default)
      : SimpleArgument(Arg, Attr, T), Default(Default) {}

    void writeAccessors(raw_ostream &OS) const {
      SimpleArgument::writeAccessors(OS);

      OS << "\n\n  static const " << getType() << " Default" << getUpperName()
         << " = " << Default << ";";
    }
  };

a756 6
    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {
      OS << "  if (!"
         << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
      OS << "    return false;\n";
    }

a788 13
    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {
      OS << "  {\n";
      OS << "    " << getType() << " *I = A->" << getLowerName()
         << "_begin();\n";
      OS << "    " << getType() << " *E = A->" << getLowerName()
         << "_end();\n";
      OS << "    for (; I != E; ++I) {\n";
      OS << "      if (!getDerived().TraverseStmt(*I))\n";
      OS << "        return false;\n";
      OS << "    }\n";
      OS << "  }\n";
    }

a873 3
  else if (ArgName == "DefaultIntArgument")
    Ptr = new DefaultSimpleArgument(Arg, Attr, "int",
                                    Arg.getValueAsInt("Default"));
d879 2
a890 1
    // Search in reverse order so that the most-derived type is handled first.
d892 2
a893 2
    for (std::vector<Record*>::reverse_iterator i = Bases.rbegin(),
         e = Bases.rend(); i != e; ++i) {
a914 23
static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
  std::vector<Record *> Spellings = R.getValueAsListOfDefs("Spellings");

  OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
  if (Spellings.empty()) {
    OS << "  return \"(No spelling)\";\n}\n\n";
    return;
  }

  OS << "  switch (SpellingListIndex) {\n"
        "  default:\n"
        "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
        "    return \"(No spelling)\";\n";

  for (unsigned I = 0; I < Spellings.size(); ++I)
    OS << "  case " << I << ":\n"
          "    return \"" << Spellings[I]->getValueAsString("Name") << "\";\n";
  // End of the switch statement.
  OS << "  }\n";
  // End of the getSpelling function.
  OS << "}\n\n";
}

a1157 1
    OS << "  virtual const char *getSpelling() const;\n";
a1288 1
    writeGetSpellingFunction(R, OS);
d1338 9
d1349 1
d1351 1
a1351 1
                       NonInhAttrs, InhAttrs, InhParamAttrs;
d1359 2
d1368 1
d1374 1
d1377 1
d1480 1
a1485 38
  ParsedAttrMap Attrs = getParsedAttrList(Records);
  for (ParsedAttrMap::const_iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = *I->second;
    std::vector<Record*> Spellings = R.getValueAsListOfDefs("Spellings");
    OS << "  case AT_" << I->first << ": {\n";
    for (unsigned I = 0; I < Spellings.size(); ++ I) {
      SmallString<16> Namespace;
      if (Spellings[I]->getValueAsString("Variety") == "CXX11")
        Namespace = Spellings[I]->getValueAsString("Namespace");
      else
        Namespace = "";

      OS << "    if (Name == \""
        << Spellings[I]->getValueAsString("Name") << "\" && "
        << "SyntaxUsed == "
        << StringSwitch<unsigned>(Spellings[I]->getValueAsString("Variety"))
          .Case("GNU", 0)
          .Case("CXX11", 1)
          .Case("Declspec", 2)
          .Case("Keyword", 3)
          .Default(0)
        << " && Scope == \"" << Namespace << "\")\n"
        << "        return " << I << ";\n";
    }

    OS << "    break;\n";
    OS << "  }\n";
  }

  OS << "  }\n";
  OS << "  return 0;\n";
}

// Emits code used by RecursiveASTVisitor to visit attributes
void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);

d1487 1
a1487 6

  // Write method declarations for Traverse* methods.
  // We emit this here because we only generate methods for attributes that
  // are declared as ASTNodes.
  OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
d1490 3
a1492 1
    if (!R.getValueAsBit("ASTNode"))
a1493 8
    OS << "  bool Traverse"
       << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
    OS << "  bool Visit"
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
       << "    return true; \n"
       << "  };\n";
  }
  OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
d1495 17
a1511 6
  // Write individual Traverse* methods for each attribute class.
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    if (!R.getValueAsBit("ASTNode"))
      continue;
d1513 12
a1524 7
    OS << "template <typename Derived>\n"
       << "bool VISITORCLASS<Derived>::Traverse"
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
       << "  if (!getDerived().VisitAttr(A))\n"
       << "    return false;\n"
       << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
       << "    return false;\n";
d1526 2
a1527 8
    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    for (std::vector<Record*>::iterator ri = ArgRecords.begin(),
                                        re = ArgRecords.end();
         ri != re; ++ri) {
      Record &ArgRecord = **ri;
      Argument *Arg = createArgument(ArgRecord, R.getName());
      assert(Arg);
      Arg->writeASTVisitorTraversal(OS);
a1528 3

    OS << "  return true;\n";
    OS << "}\n\n";
d1531 2
a1532 23
  // Write generic Traverse routine
  OS << "template <typename Derived>\n"
     << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
     << "  if (!A)\n"
     << "    return true;\n"
     << "\n"
     << "  switch (A->getKind()) {\n"
     << "    default:\n"
     << "      return true;\n";

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    if (!R.getValueAsBit("ASTNode"))
      continue;

    OS << "    case attr::" << R.getName() << ":\n"
       << "      return getDerived().Traverse" << R.getName() << "Attr("
       << "cast<" << R.getName() << "Attr>(A));\n";
  }
  OS << "  }\n";  // end case
  OS << "}\n";  // end function
  OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
a1534 1

d1637 33
d1685 1
a1685 1
static void emitArgInfo(const Record &R, std::stringstream &OS) {
a1698 259
static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
  OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
  OS << "const Decl *) {\n";
  OS << "  return true;\n";
  OS << "}\n\n";
}

static std::string CalculateDiagnostic(const Record &S) {
  // If the SubjectList object has a custom diagnostic associated with it,
  // return that directly.
  std::string CustomDiag = S.getValueAsString("CustomDiag");
  if (!CustomDiag.empty())
    return CustomDiag;

  // Given the list of subjects, determine what diagnostic best fits.
  enum {
    Func = 1U << 0,
    Var = 1U << 1,
    ObjCMethod = 1U << 2,
    Param = 1U << 3,
    Class = 1U << 4,
    GenericRecord = 1U << 5,
    Type = 1U << 6,
    ObjCIVar = 1U << 7,
    ObjCProp = 1U << 8,
    ObjCInterface = 1U << 9,
    Block = 1U << 10,
    Namespace = 1U << 11,
    FuncTemplate = 1U << 12,
    Field = 1U << 13,
    CXXMethod = 1U << 14,
    ObjCProtocol = 1U << 15
  };
  uint32_t SubMask = 0;

  std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
  for (std::vector<Record *>::const_iterator I = Subjects.begin(),
       E = Subjects.end(); I != E; ++I) {
    const Record &R = (**I);
    std::string Name;

    if (R.isSubClassOf("SubsetSubject")) {
      PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
      // As a fallback, look through the SubsetSubject to see what its base
      // type is, and use that. This needs to be updated if SubsetSubjects
      // are allowed within other SubsetSubjects.
      Name = R.getValueAsDef("Base")->getName();
    } else
      Name = R.getName();

    uint32_t V = StringSwitch<uint32_t>(Name)
                   .Case("Function", Func)
                   .Case("Var", Var)
                   .Case("ObjCMethod", ObjCMethod)
                   .Case("ParmVar", Param)
                   .Case("TypedefName", Type)
                   .Case("ObjCIvar", ObjCIVar)
                   .Case("ObjCProperty", ObjCProp)
                   .Case("Record", GenericRecord)
                   .Case("ObjCInterface", ObjCInterface)
                   .Case("ObjCProtocol", ObjCProtocol)
                   .Case("Block", Block)
                   .Case("CXXRecord", Class)
                   .Case("Namespace", Namespace)
                   .Case("FunctionTemplate", FuncTemplate)
                   .Case("Field", Field)
                   .Case("CXXMethod", CXXMethod)
                   .Default(0);
    if (!V) {
      // Something wasn't in our mapping, so be helpful and let the developer
      // know about it.
      PrintFatalError((*I)->getLoc(), "Unknown subject type: " +
                      (*I)->getName());
      return "";
    }

    SubMask |= V;
  }

  switch (SubMask) {
    // For the simple cases where there's only a single entry in the mask, we
    // don't have to resort to bit fiddling.
    case Func:  return "ExpectedFunction";
    case Var:   return "ExpectedVariable";
    case Param: return "ExpectedParameter";
    case Class: return "ExpectedClass";
    case CXXMethod:
      // FIXME: Currently, this maps to ExpectedMethod based on existing code,
      // but should map to something a bit more accurate at some point.
    case ObjCMethod:  return "ExpectedMethod";
    case Type:  return "ExpectedType";
    case ObjCInterface: return "ExpectedObjectiveCInterface";
    case ObjCProtocol: return "ExpectedObjectiveCProtocol";
    
    // "GenericRecord" means struct, union or class; check the language options
    // and if not compiling for C++, strip off the class part. Note that this
    // relies on the fact that the context for this declares "Sema &S".
    case GenericRecord:
      return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
                                           "ExpectedStructOrUnion)";
    case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
    case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
    case Func | Param:
    case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
    case Func | FuncTemplate:
    case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
    case Func | Var: return "ExpectedVariableOrFunction";

    // If not compiling for C++, the class portion does not apply.
    case Func | Var | Class:
      return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
                                           "ExpectedVariableOrFunction)";

    case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
    case Field | Var: return "ExpectedFieldOrGlobalVar";
  }

  PrintFatalError(S.getLoc(),
                  "Could not deduce diagnostic argument for Attr subjects");

  return "";
}

static std::string GenerateCustomAppertainsTo(const Record &Subject,
                                              raw_ostream &OS) {
  std::string FnName = "is" + Subject.getName();

  // If this code has already been generated, simply return the previous
  // instance of it.
  static std::set<std::string> CustomSubjectSet;
  std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
  if (I != CustomSubjectSet.end())
    return *I;

  Record *Base = Subject.getValueAsDef("Base");

  // Not currently support custom subjects within custom subjects.
  if (Base->isSubClassOf("SubsetSubject")) {
    PrintFatalError(Subject.getLoc(),
                    "SubsetSubjects within SubsetSubjects is not supported");
    return "";
  }

  OS << "static bool " << FnName << "(const Decl *D) {\n";
  OS << "  const " << Base->getName() << "Decl *S = dyn_cast<";
  OS << Base->getName();
  OS << "Decl>(D);\n";
  OS << "  return S && " << Subject.getValueAsString("CheckCode") << ";\n";
  OS << "}\n\n";

  CustomSubjectSet.insert(FnName);
  return FnName;
}

static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
  // If the attribute does not contain a Subjects definition, then use the
  // default appertainsTo logic.
  if (Attr.isValueUnset("Subjects"))
    return "defaultAppertainsTo";

  const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");

  // If the list of subjects is empty, it is assumed that the attribute
  // appertains to everything.
  if (Subjects.empty())
    return "defaultAppertainsTo";

  bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");

  // Otherwise, generate an appertainsTo check specific to this attribute which
  // checks all of the given subjects against the Decl passed in. Return the
  // name of that check to the caller.
  std::string FnName = "check" + Attr.getName() + "AppertainsTo";
  std::stringstream SS;
  SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
  SS << "const Decl *D) {\n";
  SS << "  if (";
  for (std::vector<Record *>::const_iterator I = Subjects.begin(),
       E = Subjects.end(); I != E; ++I) {
    // If the subject has custom code associated with it, generate a function
    // for it. The function cannot be inlined into this check (yet) because it
    // requires the subject to be of a specific type, and were that information
    // inlined here, it would not support an attribute with multiple custom
    // subjects.
    if ((*I)->isSubClassOf("SubsetSubject")) {
      SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
    } else {
      SS << "!isa<" << (*I)->getName() << "Decl>(D)";
    }

    if (I + 1 != E)
      SS << " && ";
  }
  SS << ") {\n";
  SS << "    S.Diag(Attr.getLoc(), diag::";
  SS << (Warn ? "warn_attribute_wrong_decl_type" :
               "err_attribute_wrong_decl_type");
  SS << ")\n";
  SS << "      << Attr.getName() << ";
  SS << CalculateDiagnostic(*SubjectObj) << ";\n";
  SS << "    return false;\n";
  SS << "  }\n";
  SS << "  return true;\n";
  SS << "}\n\n";

  OS << SS.str();
  return FnName;
}

static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
  OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
  OS << "const AttributeList &) {\n";
  OS << "  return true;\n";
  OS << "}\n\n";
}

static std::string GenerateLangOptRequirements(const Record &R,
                                               raw_ostream &OS) {
  // If the attribute has an empty or unset list of language requirements,
  // return the default handler.
  std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
  if (LangOpts.empty())
    return "defaultDiagnoseLangOpts";

  // Generate the test condition, as well as a unique function name for the
  // diagnostic test. The list of options should usually be short (one or two
  // options), and the uniqueness isn't strictly necessary (it is just for
  // codegen efficiency).
  std::string FnName = "check", Test;
  for (std::vector<Record *>::const_iterator I = LangOpts.begin(),
       E = LangOpts.end(); I != E; ++I) {
    std::string Part = (*I)->getValueAsString("Name");
    Test += "S.LangOpts." + Part;
    if (I + 1 != E)
      Test += " || ";
    FnName += Part;
  }
  FnName += "LangOpts";

  // If this code has already been generated, simply return the previous
  // instance of it.
  static std::set<std::string> CustomLangOptsSet;
  std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
  if (I != CustomLangOptsSet.end())
    return *I;

  OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
  OS << "  if (" << Test << ")\n";
  OS << "    return true;\n\n";
  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
  OS << "<< Attr.getName();\n";
  OS << "  return false;\n";
  OS << "}\n\n";

  CustomLangOptsSet.insert(FnName);
  return FnName;
}

d1705 1
a1705 9
  // Generate the default appertainsTo and language option diagnostic methods.
  GenerateDefaultAppertainsTo(OS);
  GenerateDefaultLangOptRequirements(OS);

  // Generate the appertainsTo diagnostic methods and write their names into
  // another mapping. At the same time, generate the AttrInfoMap object
  // contents. Due to the reliance on generated code, use separate streams so
  // that code will not be interleaved.
  std::stringstream SS;
d1710 4
a1713 6
    SS << "  { ";
    emitArgInfo(*I->second, SS);
    SS << ", " << I->second->getValueAsBit("HasCustomParsing");
    SS << ", " << GenerateAppertainsTo(*I->second, OS);
    SS << ", " << GenerateLangOptRequirements(*I->second, OS);
    SS << " }";
d1716 3
a1718 3
      SS << ",";

    SS << "  // AT_" << I->first << "\n";
a1719 3

  OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
  OS << SS.str();
a1729 1
  std::set<std::string> Seen;
d1733 1
a1733 1

d1736 1
a1739 10
      std::string AttrName;
      if (Attr.isSubClassOf("TargetSpecificAttr") &&
          !Attr.isValueUnset("ParseKind")) {
        AttrName = Attr.getValueAsString("ParseKind");
        if (Seen.find(AttrName) != Seen.end())
          continue;
        Seen.insert(AttrName);
      } else
        AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();

d1743 3
d1758 1
a1758 1
              "return AttributeList::AT_" + AttrName + ";"));
@


1.1.1.3
log
@Import Clang 3.5svn r199312
@
text
@d15 1
a16 2
#include "llvm/ADT/StringSwitch.h"
#include "llvm/TableGen/Error.h"
d20 1
d23 1
a24 1
#include <sstream>
d28 21
d98 1
a98 2
static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
                                       ParsedAttrMap *Dupes = 0) {
d113 1
a113 3
        if (Seen.find(AN) != Seen.end()) {
          if (Dupes)
            Dupes->push_back(std::make_pair(AN, *I));
a114 1
        }
d558 1
a558 1
    std::vector<std::string> values, enums, uniques;
d562 2
a563 2
        values(Arg.getValueAsListOfStrings("Values")),
        enums(Arg.getValueAsListOfStrings("Enums")),
d596 2
a597 2
      std::vector<std::string>::const_iterator i = uniques.begin(),
                                               e = uniques.end();
d626 1
a626 1
      for (std::vector<std::string>::const_iterator I = uniques.begin(),
d654 1
a654 1
    std::vector<std::string> values, enums, uniques;
d659 2
a660 2
        values(Arg.getValueAsListOfStrings("Values")),
        enums(Arg.getValueAsListOfStrings("Enums")),
d676 2
a677 2
      std::vector<std::string>::const_iterator i = uniques.begin(),
                                               e = uniques.end();
d696 1
a696 1
      for (std::vector<std::string>::const_iterator UI = uniques.begin(),
a1314 27
/// \brief Emits the parse-arguments-in-unevaluated-context property for
/// attributes.
void EmitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("StringSwitch code to match attributes which require "
                       "an unevaluated context", OS);

  ParsedAttrMap Attrs = getParsedAttrList(Records);
  for (ParsedAttrMap::const_iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    const Record &Attr = *I->second;

    if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
      continue;

    // All these spellings take are parsed unevaluated.
    std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
    std::set<std::string> Emitted;
    for (std::vector<Record*>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      if (Emitted.insert((*I)->getValueAsString("Name")).second)
        OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", "
        << "true" << ")\n";
    }

  }
}

d1530 2
a1531 2
  emitSourceFileHeader("llvm::StringSwitch code to match attributes based on "
                       "the target triple, T", OS);
d1535 1
a1535 2
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
d1538 1
a1538 34
    // It is assumed that there will be an llvm::Triple object named T within
    // scope that can be used to determine whether the attribute exists in
    // a given target.
    std::string Test;
    if (Attr.isSubClassOf("TargetSpecificAttr")) {
      const Record *R = Attr.getValueAsDef("Target");
      std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");

      Test += "(";
      for (std::vector<std::string>::const_iterator AI = Arches.begin(),
           AE = Arches.end(); AI != AE; ++AI) {
        std::string Part = *AI;
        Test += "T.getArch() == llvm::Triple::" + Part;
        if (AI + 1 != AE)
          Test += " || ";
      }
      Test += ")";

      std::vector<std::string> OSes;
      if (!R->isValueUnset("OSes")) {
        Test += " && (";
        std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
        for (std::vector<std::string>::const_iterator AI = OSes.begin(),
             AE = OSes.end(); AI != AE; ++AI) {
          std::string Part = *AI;

          Test += "T.getOS() == llvm::Triple::" + Part;
          if (AI + 1 != AE)
            Test += " || ";
        }
        Test += ")";
      }
    } else
      Test = "true";
d1540 2
a1541 5
    std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
    for (std::vector<Record*>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", " << Test;
      OS << ")\n";
a2059 91
static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
  OS << "static bool defaultTargetRequirements(llvm::Triple) {\n";
  OS << "  return true;\n";
  OS << "}\n\n";
}

static std::string GenerateTargetRequirements(const Record &Attr,
                                              const ParsedAttrMap &Dupes,
                                              raw_ostream &OS) {
  // If the attribute is not a target specific attribute, return the default
  // target handler.
  if (!Attr.isSubClassOf("TargetSpecificAttr"))
    return "defaultTargetRequirements";

  // Get the list of architectures to be tested for.
  const Record *R = Attr.getValueAsDef("Target");
  std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
  if (Arches.empty()) {
    PrintError(Attr.getLoc(), "Empty list of target architectures for a "
                              "target-specific attr");
    return "defaultTargetRequirements";
  }

  // If there are other attributes which share the same parsed attribute kind,
  // such as target-specific attributes with a shared spelling, collapse the
  // duplicate architectures. This is required because a shared target-specific
  // attribute has only one AttributeList::Kind enumeration value, but it
  // applies to multiple target architectures. In order for the attribute to be
  // considered valid, all of its architectures need to be included.
  if (!Attr.isValueUnset("ParseKind")) {
    std::string APK = Attr.getValueAsString("ParseKind");
    for (ParsedAttrMap::const_iterator I = Dupes.begin(), E = Dupes.end();
         I != E; ++I) {
      if (I->first == APK) {
        std::vector<std::string> DA = I->second->getValueAsDef("Target")->
                                            getValueAsListOfStrings("Arches");
        std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
      }
    }
  }

  std::string FnName = "isTarget", Test = "(";
  for (std::vector<std::string>::const_iterator I = Arches.begin(),
       E = Arches.end(); I != E; ++I) {
    std::string Part = *I;
    Test += "Arch == llvm::Triple::" + Part;
    if (I + 1 != E)
      Test += " || ";
    FnName += Part;
  }
  Test += ")";

  // If the target also requires OS testing, generate those tests as well.
  bool UsesOS = false;
  if (!R->isValueUnset("OSes")) {
    UsesOS = true;
    
    // We know that there was at least one arch test, so we need to and in the
    // OS tests.
    Test += " && (";
    std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
    for (std::vector<std::string>::const_iterator I = OSes.begin(),
         E = OSes.end(); I != E; ++I) {
      std::string Part = *I;

      Test += "OS == llvm::Triple::" + Part;
      if (I + 1 != E)
        Test += " || ";
      FnName += Part;
    }
    Test += ")";
  }

  // If this code has already been generated, simply return the previous
  // instance of it.
  static std::set<std::string> CustomTargetSet;
  std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
  if (I != CustomTargetSet.end())
    return *I;

  OS << "static bool " << FnName << "(llvm::Triple T) {\n";
  OS << "  llvm::Triple::ArchType Arch = T.getArch();\n";
  if (UsesOS)
    OS << "  llvm::Triple::OSType OS = T.getOS();\n";
  OS << "  return " << Test << ";\n";
  OS << "}\n\n";

  CustomTargetSet.insert(FnName);
  return FnName;
}

d2064 1
a2064 4
  // Get the list of parsed attributes, and accept the optional list of
  // duplicates due to the ParseKind.
  ParsedAttrMap Dupes;
  ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
d2066 1
a2066 2
  // Generate the default appertainsTo, target and language option diagnostic
  // methods.
a2068 1
  GenerateDefaultTargetRequirements(OS);
a2076 6
    // TODO: If the attribute's kind appears in the list of duplicates, that is
    // because it is a target-specific attribute that appears multiple times.
    // It would be beneficial to test whether the duplicates are "similar
    // enough" to each other to not cause problems. For instance, check that
    // the spellings are identicial, and custom parsing rules match, etc.

a2081 2
    SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
    SS << ", " << I->second->isSubClassOf("TypeAttr");
a2083 1
    SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
d2101 3
a2103 2
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords;
d2112 2
a2113 10
      // Attribute spellings can be shared between target-specific attributes,
      // and can be shared between syntaxes for the same attribute. For
      // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
      // specific attribute, or MSP430-specific attribute. Additionally, an
      // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
      // for the same semantic attribute. Ultimately, we need to map each of
      // these to a single AttributeList::Kind value, but the StringMatcher
      // class cannot handle duplicate match strings. So we generate a list of
      // string to match based on the syntax, and emit multiple string matchers
      // depending on the syntax used.
a2123 1
      std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
d2127 3
a2129 4
        std::vector<StringMatcher::StringPair> *Matches = 0;
        std::string Spelling, Variety = (*I)->getValueAsString("Variety");
        if (Variety == "CXX11") {
          Matches = &CXX11;
d2132 2
a2133 8
        } else if (Variety == "GNU")
          Matches = &GNU;
        else if (Variety == "Declspec")
          Matches = &Declspec;
        else if (Variety == "Keyword")
          Matches = &Keywords;

        assert(Matches && "Unsupported spelling variety found");
a2134 1
        Spelling += NormalizeAttrSpelling(RawSpelling);
d2136 4
a2139 2
          Matches->push_back(StringMatcher::StringPair(Spelling,
                              "return AttributeList::AT_" + AttrName + ";"));
d2141 4
a2144 2
          Matches->push_back(StringMatcher::StringPair(Spelling,
                              "return AttributeList::IgnoredAttribute;"));
d2149 3
a2151 12
  OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
  OS << "AttributeList::Syntax Syntax) {\n";
  OS << "  if (AttributeList::AS_GNU == Syntax) {\n";
  StringMatcher("Name", GNU, OS).Emit();
  OS << "  } else if (AttributeList::AS_Declspec == Syntax) {\n";
  StringMatcher("Name", Declspec, OS).Emit();
  OS << "  } else if (AttributeList::AS_CXX11 == Syntax) {\n";
  StringMatcher("Name", CXX11, OS).Emit();
  OS << "  } else if (AttributeList::AS_Keyword == Syntax) {\n";
  StringMatcher("Name", Keywords, OS).Emit();
  OS << "  }\n";
  OS << "  return AttributeList::UnknownAttribute;\n"
@


1.1.1.4
log
@Import Clang 3.5svn r201163.
@
text
@a16 1
#include "llvm/ADT/STLExtras.h"
a27 48
class FlattenedSpelling {
  std::string V, N, NS;
  bool K;

public:
  FlattenedSpelling(const std::string &Variety, const std::string &Name,
                    const std::string &Namespace, bool KnownToGCC) :
    V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
  explicit FlattenedSpelling(const Record &Spelling) :
    V(Spelling.getValueAsString("Variety")),
    N(Spelling.getValueAsString("Name")) {

    assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
           "flattened!");
    if (V == "CXX11")
      NS = Spelling.getValueAsString("Namespace");
    bool Unset;
    K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
  }

  const std::string &variety() const { return V; }
  const std::string &name() const { return N; }
  const std::string &nameSpace() const { return NS; }
  bool knownToGCC() const { return K; }
};

std::vector<FlattenedSpelling> GetFlattenedSpellings(const Record &Attr) {
  std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
  std::vector<FlattenedSpelling> Ret;

  for (std::vector<Record *>::const_iterator I = Spellings.begin(),
       E = Spellings.end(); I != E; ++I) {
    const Record &Spelling = **I;

    if (Spelling.getValueAsString("Variety") == "GCC") {
      // Gin up two new spelling objects to add into the list.
      Ret.push_back(FlattenedSpelling("GNU", Spelling.getValueAsString("Name"),
                                      "", true));
      Ret.push_back(FlattenedSpelling("CXX11",
                                      Spelling.getValueAsString("Name"),
                                      "gnu", true));
    } else
      Ret.push_back(FlattenedSpelling(Spelling));
  }

  return Ret;
}

a63 11
// Normalize the name by removing any and all leading and trailing underscores.
// This is different from NormalizeAttrName in that it also handles names like
// _pascal and __pascal.
static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
  while (Name.startswith("_"))
    Name = Name.substr(1, Name.size());
  while (Name.endswith("_"))
    Name = Name.substr(0, Name.size() - 1);
  return Name;
}

a153 4

    virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
      OS << getUpperName();
    }
a396 3
    void writeImplicitCtorArgs(raw_ostream &OS) const {
      OS << "Is" << getUpperName() << "Expr, " << getUpperName();
    }
a493 3
    void writeImplicitCtorArgs(raw_ostream &OS) const {
      OS << getUpperName() << ", " << getUpperName() << "Size";
    }
a914 3
  else if (ArgName == "DefaultBoolArgument")
    Ptr = new DefaultSimpleArgument(Arg, Attr, "bool",
                                    Arg.getValueAsBit("Default"));
d961 1
a961 1
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
d976 1
a976 1
          "    return \"" << Spellings[I].name() << "\";\n";
d985 1
a985 1
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
d1007 2
a1008 2
    std::string Name = Spellings[I].name();
    std::string Variety = Spellings[I].variety();
d1016 1
a1016 1
      std::string Namespace = Spellings[I].nameSpace();
d1063 2
a1064 3
static unsigned
getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
                     const FlattenedSpelling &Spelling) {
d1068 2
a1069 2
    const FlattenedSpelling &S = SpellingList[Index];
    if (S.variety() != Spelling.variety())
d1071 3
a1073 1
    if (S.nameSpace() != Spelling.nameSpace())
d1075 1
a1075 1
    if (S.name() != Spelling.name())
d1090 3
a1092 3
    std::vector<FlattenedSpelling> Spellings = 
      GetFlattenedSpellings(*Accessor);
    std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
d1098 1
a1098 1
      OS << getSpellingListIndex(SpellingList, Spellings[Index]);
a1106 183
static bool
SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
  assert(!Spellings.empty() && "An empty list of spellings was provided");
  std::string FirstName = NormalizeNameForSpellingComparison(
    Spellings.front().name());
  for (std::vector<FlattenedSpelling>::const_iterator
       I = llvm::next(Spellings.begin()), E = Spellings.end(); I != E; ++I) {
    std::string Name = NormalizeNameForSpellingComparison(I->name());
    if (Name != FirstName)
      return false;
  }
  return true;
}

typedef std::map<unsigned, std::string> SemanticSpellingMap;
static std::string
CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
                        SemanticSpellingMap &Map) {
  // The enumerants are automatically generated based on the variety,
  // namespace (if present) and name for each attribute spelling. However,
  // care is taken to avoid trampling on the reserved namespace due to
  // underscores.
  std::string Ret("  enum Spelling {\n");
  std::set<std::string> Uniques;
  unsigned Idx = 0;
  for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
        E = Spellings.end(); I != E; ++I, ++Idx) {
    const FlattenedSpelling &S = *I;
    std::string Variety = S.variety();
    std::string Spelling = S.name();
    std::string Namespace = S.nameSpace();
    std::string EnumName = "";

    EnumName += (Variety + "_");
    if (!Namespace.empty())
      EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
      "_");
    EnumName += NormalizeNameForSpellingComparison(Spelling);

    // Even if the name is not unique, this spelling index corresponds to a
    // particular enumerant name that we've calculated.
    Map[Idx] = EnumName;

    // Since we have been stripping underscores to avoid trampling on the
    // reserved namespace, we may have inadvertently created duplicate
    // enumerant names. These duplicates are not considered part of the
    // semantic spelling, and can be elided.
    if (Uniques.find(EnumName) != Uniques.end())
      continue;

    Uniques.insert(EnumName);
    if (I != Spellings.begin())
      Ret += ",\n";
    Ret += "    " + EnumName;
  }
  Ret += "\n  };\n\n";
  return Ret;
}

void WriteSemanticSpellingSwitch(const std::string &VarName,
                                 const SemanticSpellingMap &Map,
                                 raw_ostream &OS) {
  OS << "  switch (" << VarName << ") {\n    default: "
    << "llvm_unreachable(\"Unknown spelling list index\");\n";
  for (SemanticSpellingMap::const_iterator I = Map.begin(), E = Map.end();
       I != E; ++I)
       OS << "    case " << I->first << ": return " << I->second << ";\n";
  OS << "  }\n";
}

// Emits the LateParsed property for attributes.
static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    bool LateParsed = Attr.getValueAsBit("LateParsed");

    if (LateParsed) {
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);

      // FIXME: Handle non-GNU attributes
      for (std::vector<FlattenedSpelling>::const_iterator
           I = Spellings.begin(), E = Spellings.end(); I != E; ++I) {
        if (I->variety() != "GNU")
          continue;
        OS << ".Case(\"" << I->name() << "\", " << LateParsed << ")\n";
      }
    }
  }
  OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
}

/// \brief Emits the first-argument-is-type property for attributes.
static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record *>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    // Determine whether the first argument is a type.
    std::vector<Record *> Args = Attr.getValueAsListOfDefs("Args");
    if (Args.empty())
      continue;

    if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
      continue;

    // All these spellings take a single type argument.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
    std::set<std::string> Emitted;
    for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      if (Emitted.insert(I->name()).second)
        OS << ".Case(\"" << I->name() << "\", " << "true" << ")\n";
    }
  }
  OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
}

/// \brief Emits the parse-arguments-in-unevaluated-context property for
/// attributes.
static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
  ParsedAttrMap Attrs = getParsedAttrList(Records);
  for (ParsedAttrMap::const_iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    const Record &Attr = *I->second;

    if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
      continue;

    // All these spellings take are parsed unevaluated.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
    std::set<std::string> Emitted;
    for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      if (Emitted.insert(I->name()).second)
        OS << ".Case(\"" << I->name() << "\", " << "true" << ")\n";
    }
  }
  OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
}

static bool isIdentifierArgument(Record *Arg) {
  return !Arg->getSuperClasses().empty() &&
    llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
    .Case("IdentifierArgument", true)
    .Case("EnumArgument", true)
    .Default(false);
}

// Emits the first-argument-is-identifier property for attributes.
static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    // Determine whether the first argument is an identifier.
    std::vector<Record *> Args = Attr.getValueAsListOfDefs("Args");
    if (Args.empty() || !isIdentifierArgument(Args[0]))
      continue;

    // All these spellings take an identifier argument.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
    std::set<std::string> Emitted;
    for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      if (Emitted.insert(I->name()).second)
        OS << ".Case(\"" << I->name() << "\", " << "true" << ")\n";
    }
  }
  OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
}

d1156 1
a1156 36
    OS << "\npublic:\n";

    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);

    // If there are zero or one spellings, all spelling-related functionality
    // can be elided. If all of the spellings share the same name, the spelling
    // functionality can also be elided.
    bool ElideSpelling = (Spellings.size() <= 1) ||
                         SpellingNamesAreCommon(Spellings);

    // This maps spelling index values to semantic Spelling enumerants.
    SemanticSpellingMap SemanticToSyntacticMap;

    if (!ElideSpelling)
      OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);

    OS << "  static " << R.getName() << "Attr *CreateImplicit(";
    OS << "ASTContext &Ctx";
    if (!ElideSpelling)
      OS << ", Spelling S";
    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << ", ";
      (*ai)->writeCtorParameters(OS);
    }
    OS << ", SourceRange Loc = SourceRange()";
    OS << ") {\n";
    OS << "    " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
    OS << "Attr(Loc, Ctx, ";
    for (ai = Args.begin(); ai != ae; ++ai) {
      (*ai)->writeImplicitCtorArgs(OS);
      OS << ", ";
    }
    OS << (ElideSpelling ? "0" : "S") << ");\n";
    OS << "    A->setImplicit(true);\n";
    OS << "    return A;\n  }\n\n";

d1169 1
a1169 1
    OS << "unsigned SI\n";
d1201 1
a1201 1
      OS << "unsigned SI\n";
a1226 8
    
    if (!ElideSpelling) {
      assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
      OS << "  Spelling getSemanticSpelling() const {\n";
      WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
                                  OS);
      OS << "  }\n";
    }
a1252 3
    if (R.getValueAsBit("DuplicatesAllowedWhileMerging"))
      OS << "  virtual bool duplicatesAllowed() const { return true; }\n\n";

d1259 94
a1485 2
    OS << "    bool isImplicit = Record[Idx++];\n";
    OS << "    unsigned Spelling = Record[Idx++];\n";
d1498 1
a1498 1
    OS << ", Spelling);\n";
a1500 1
    OS << "    New->setImplicit(isImplicit);\n";
a1529 3
    OS << "    Record.push_back(A->isImplicit());\n";
    OS << "    Record.push_back(A->getSpellingListIndex());\n";

d1584 6
a1589 4
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
    for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I)
      OS << ".Case(\"" << I->name() << "\", " << Test << ")\n";
d1608 1
a1608 1
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
d1611 6
d1618 1
a1618 1
        << Spellings[I].name() << "\" && "
d1620 1
a1620 1
        << StringSwitch<unsigned>(Spellings[I].variety())
d1626 1
a1626 1
        << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
d1716 30
d1809 1
a1809 1
    OS << ", A->getSpellingListIndex());\n    }\n";
a1970 6
static std::string GetSubjectWithSuffix(const Record *R) {
  std::string B = R->getName();
  if (B == "DeclBase")
    return "Decl";
  return B + "Decl";
}
d1992 4
a1995 5
  OS << "  if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
  OS << GetSubjectWithSuffix(Base);
  OS << ">(D))\n";
  OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
  OS << "  return false;\n";
d2036 1
a2036 1
      SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
a2197 46
static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
  OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
     << "const AttributeList &Attr) {\n";
  OS << "  return UINT_MAX;\n";
  OS << "}\n\n";
}

static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
                                                           raw_ostream &OS) {
  // If the attribute does not have a semantic form, we can bail out early.
  if (!Attr.getValueAsBit("ASTNode"))
    return "defaultSpellingIndexToSemanticSpelling";

  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);

  // If there are zero or one spellings, or all of the spellings share the same
  // name, we can also bail out early.
  if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
    return "defaultSpellingIndexToSemanticSpelling";

  // Generate the enumeration we will use for the mapping.
  SemanticSpellingMap SemanticToSyntacticMap;
  std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
  std::string Name = Attr.getName() + "AttrSpellingMap";

  OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
  OS << Enum;
  OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
  WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
  OS << "}\n\n";

  return Name;
}

static bool IsKnownToGCC(const Record &Attr) {
  // Look at the spellings for this subject; if there are any spellings which
  // claim to be known to GCC, the attribute is known to GCC.
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
       E = Spellings.end(); I != E; ++I) {
    if (I->knownToGCC())
      return true;
  }
  return false;
}

d2207 2
a2208 2
  // Generate the default appertainsTo, target and language option diagnostic,
  // and spelling list index mapping methods.
a2211 1
  GenerateDefaultSpellingIndexToSemanticSpelling(OS);
d2224 1
a2224 1
    // the spellings are identical, and custom parsing rules match, etc.
a2232 1
    SS << ", " << IsKnownToGCC(*I->second);
a2235 1
    SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
d2283 4
a2286 4
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
      for (std::vector<FlattenedSpelling>::const_iterator
           I = Spellings.begin(), E = Spellings.end(); I != E; ++I) {
        std::string RawSpelling = I->name();
d2288 1
a2288 1
        std::string Spelling, Variety = I->variety();
d2291 1
a2291 1
          Spelling += I->nameSpace();
a2343 8

    // If the attribute has a semantically-meaningful name (which is determined
    // by whether there is a Spelling enumeration for it), then write out the
    // spelling used for the attribute.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
    if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
      OS << "    OS << \" \" << A->getSpelling();\n";

a2379 9
void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
                                       raw_ostream &OS) {
  emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
  emitClangAttrArgContextList(Records, OS);
  emitClangAttrIdentifierArgList(Records, OS);
  emitClangAttrTypeArgList(Records, OS);
  emitClangAttrLateParsedList(Records, OS);
}

@


1.1.1.5
log
@Import Clang 3.5svn r202566.
@
text
@a608 17
  // Unique the enums, but maintain the original declaration ordering.
  std::vector<std::string>
  uniqueEnumsInOrder(const std::vector<std::string> &enums) {
    std::vector<std::string> uniques;
    std::set<std::string> unique_set(enums.begin(), enums.end());
    for (std::vector<std::string>::const_iterator i = enums.begin(),
                                                  e = enums.end();
         i != e; ++i) {
      std::set<std::string>::iterator set_i = unique_set.find(*i);
      if (set_i != unique_set.end()) {
        uniques.push_back(*i);
        unique_set.erase(set_i);
      }
    }
    return uniques;
  }

d617 1
a617 1
        uniques(uniqueEnumsInOrder(enums))
d619 3
d714 1
a714 1
        uniques(uniqueEnumsInOrder(enums))
d716 4
a1375 11

    // FIXME: Currently, documentation is generated as-needed due to the fact
    // that there is no way to allow a generated project "reach into" the docs
    // directory (for instance, it may be an out-of-tree build). However, we want
    // to ensure that every attribute has a Documentation field, and produce an
    // error if it has been neglected. Otherwise, the on-demand generation which
    // happens server-side will fail. This code is ensuring that functionality,
    // even though this Emitter doesn't technically need the documentation.
    // When attribute documentation can be generated as part of the build
    // itself, this code can be removed.
    (void)R.getValueAsListOfDefs("Documentation");
a2627 212
class DocumentationData {
public:
  const Record *Documentation;
  const Record *Attribute;

  DocumentationData(const Record &Documentation, const Record &Attribute)
      : Documentation(&Documentation), Attribute(&Attribute) {}
};

static void WriteCategoryHeader(const Record *DocCategory,
                                raw_ostream &OS) {
  const std::string &Name = DocCategory->getValueAsString("Name");
  OS << Name << "\n" << std::string(Name.length(), '=') << "\n";

  // If there is content, print that as well.
  std::string ContentStr = DocCategory->getValueAsString("Content");
  if (!ContentStr.empty()) {
    // Trim leading and trailing newlines and spaces.
    StringRef Content(ContentStr);
    while (Content.startswith("\r") || Content.startswith("\n") ||
           Content.startswith(" ") || Content.startswith("\t"))
           Content = Content.substr(1);
    while (Content.endswith("\r") || Content.endswith("\n") ||
           Content.endswith(" ") || Content.endswith("\t"))
           Content = Content.substr(0, Content.size() - 1);
    OS << Content;
  }
  OS << "\n\n";
}

enum SpellingKind {
  GNU = 1 << 0,
  CXX11 = 1 << 1,
  Declspec = 1 << 2,
  Keyword = 1 << 3
};

static void WriteDocumentation(const DocumentationData &Doc,
                               raw_ostream &OS) {
  // FIXME: there is no way to have a per-spelling category for the attribute
  // documentation. This may not be a limiting factor since the spellings
  // should generally be consistently applied across the category.

  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);

  // Determine the heading to be used for this attribute.
  std::string Heading = Doc.Documentation->getValueAsString("Heading");
  bool CustomHeading = !Heading.empty();
  if (Heading.empty()) {
    // If there's only one spelling, we can simply use that.
    if (Spellings.size() == 1)
      Heading = Spellings.begin()->name();
    else {
      std::set<std::string> Uniques;
      for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
           E = Spellings.end(); I != E && Uniques.size() <= 1; ++I) {
        std::string Spelling = NormalizeNameForSpellingComparison(I->name());
        Uniques.insert(Spelling);
      }
      // If the semantic map has only one spelling, that is sufficient for our
      // needs.
      if (Uniques.size() == 1)
        Heading = *Uniques.begin();
    }
  }

  // If the heading is still empty, it is an error.
  if (Heading.empty())
    PrintFatalError(Doc.Attribute->getLoc(),
                    "This attribute requires a heading to be specified");

  // Gather a list of unique spellings; this is not the same as the semantic
  // spelling for the attribute. Variations in underscores and other non-
  // semantic characters are still acceptable.
  std::vector<std::string> Names;

  unsigned SupportedSpellings = 0;
  for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
       E = Spellings.end(); I != E; ++I) {
    SpellingKind Kind = StringSwitch<SpellingKind>(I->variety())
      .Case("GNU", GNU)
      .Case("CXX11", CXX11)
      .Case("Declspec", Declspec)
      .Case("Keyword", Keyword);

    // Mask in the supported spelling.
    SupportedSpellings |= Kind;

    std::string Name;
    if (Kind == CXX11 && !I->nameSpace().empty())
      Name = I->nameSpace() + "::";
    Name += I->name();

    // If this name is the same as the heading, do not add it.
    if (Name != Heading)
      Names.push_back(Name);
  }

  // Print out the heading for the attribute. If there are alternate spellings,
  // then display those after the heading.
  if (!CustomHeading && !Names.empty()) {
    Heading += " (";
    for (std::vector<std::string>::const_iterator I = Names.begin(),
         E = Names.end(); I != E; ++I) {
      if (I != Names.begin())
        Heading += ", ";
      Heading += *I;
    }
    Heading += ")";
  }
  OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";

  if (!SupportedSpellings)
    PrintFatalError(Doc.Attribute->getLoc(),
                    "Attribute has no supported spellings; cannot be "
                    "documented");

  // List what spelling syntaxes the attribute supports.
  OS << ".. csv-table:: Supported Syntaxes\n";
  OS << "   :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\"\n\n";
  OS << "   \"";
  if (SupportedSpellings & GNU) OS << "X";
  OS << "\",\"";
  if (SupportedSpellings & CXX11) OS << "X";
  OS << "\",\"";
  if (SupportedSpellings & Declspec) OS << "X";
  OS << "\",\"";
  if (SupportedSpellings & Keyword) OS << "X";
  OS << "\"\n\n";

  // If the attribute is deprecated, print a message about it, and possibly
  // provide a replacement attribute.
  if (!Doc.Documentation->isValueUnset("Deprecated")) {
    OS << "This attribute has been deprecated, and may be removed in a future "
       << "version of Clang.";
    const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
    std::string Replacement = Deprecated.getValueAsString("Replacement");
    if (!Replacement.empty())
      OS << "  This attribute has been superseded by ``"
         << Replacement << "``.";
    OS << "\n\n";
  }

  std::string ContentStr = Doc.Documentation->getValueAsString("Content");
  // Trim leading and trailing newlines and spaces.
  StringRef Content(ContentStr);
  while (Content.startswith("\r") || Content.startswith("\n") ||
         Content.startswith(" ") || Content.startswith("\t"))
    Content = Content.substr(1);
  while (Content.endswith("\r") || Content.endswith("\n") ||
         Content.endswith(" ") || Content.endswith("\t"))
    Content = Content.substr(0, Content.size() - 1);
  OS << Content;

  OS << "\n\n\n";
}

void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
  // Get the documentation introduction paragraph.
  const Record *Documentation = Records.getDef("GlobalDocumentation");
  if (!Documentation) {
    PrintFatalError("The Documentation top-level definition is missing, "
                    "no documentation will be generated.");
    return;
  }

  OS << Documentation->getValueAsString("Intro") << "\n";

  typedef std::map<const Record *,
                   std::vector<DocumentationData> > CategoryMap;
  CategoryMap SplitDocs;

  // Gather the Documentation lists from each of the attributes, based on the
  // category provided.
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  for (std::vector<Record *>::const_iterator I = Attrs.begin(),
       E = Attrs.end(); I != E; ++I) {
    const Record &Attr = **I;
    std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
    for (std::vector<Record *>::const_iterator DI = Docs.begin(),
         DE = Docs.end(); DI != DE; ++DI) {
      const Record &Doc = **DI;
      const Record *Category = Doc.getValueAsDef("Category");
      // If the category is "undocumented", then there cannot be any other
      // documentation categories (otherwise, the attribute would become
      // documented).
      std::string Cat = Category->getValueAsString("Name");
      bool Undocumented = Cat == "Undocumented";
      if (Undocumented && Docs.size() > 1)
        PrintFatalError(Doc.getLoc(),
                        "Attribute is \"Undocumented\", but has multiple "
                        "documentation categories");      

      if (!Undocumented)
        SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
    }
  }

  // Having split the attributes out based on what documentation goes where,
  // we can begin to generate sections of documentation.
  for (CategoryMap::const_iterator I = SplitDocs.begin(), E = SplitDocs.end();
       I != E; ++I) {
    WriteCategoryHeader(I->first, OS);

    // Walk over each of the attributes in the category and write out their
    // documentation.
    for (std::vector<DocumentationData>::const_iterator D = I->second.begin(),
         DE = I->second.end(); D != DE; ++D)
      WriteDocumentation(*D, OS);
  }
}

@


1.1.1.5.2.1
log
@Rebase.
@
text
@a14 1
#include "llvm/ADT/STLExtras.h"
d17 1
a23 1
#include <memory>
d59 5
a63 2
  for (const auto &Spelling : Spellings) {
    if (Spelling->getValueAsString("Variety") == "GCC") {
d65 1
a65 1
      Ret.push_back(FlattenedSpelling("GNU", Spelling->getValueAsString("Name"),
d67 3
a69 2
      Ret.push_back(FlattenedSpelling(
          "CXX11", Spelling->getValueAsString("Name"), "gnu", true));
d71 1
a71 1
      Ret.push_back(FlattenedSpelling(*Spelling));
d135 1
a135 1
typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
d138 2
a139 2
                                       ParsedAttrMap *Dupes = nullptr) {
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
d142 4
a145 2
  for (const auto *Attr : Attrs) {
    if (Attr->getValueAsBit("SemaHandler")) {
d147 3
a149 3
      if (Attr->isSubClassOf("TargetSpecificAttr") &&
          !Attr->isValueUnset("ParseKind")) {
        AN = Attr->getValueAsString("ParseKind");
d155 1
a155 1
            Dupes->push_back(std::make_pair(AN, Attr));
d160 1
a160 1
        AN = NormalizeAttrName(Attr->getName()).str();
d162 1
a162 1
      R.push_back(std::make_pair(AN, Attr));
d175 1
a175 1
    Argument(const Record &Arg, StringRef Attr)
d224 1
a224 1
    SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
d230 1
a230 1
    void writeAccessors(raw_ostream &OS) const override {
d235 1
a235 1
    void writeCloneArgs(raw_ostream &OS) const override {
d238 1
a238 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d241 1
a241 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d244 1
a244 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d247 1
a247 1
    void writeCtorParameters(raw_ostream &OS) const override {
d250 1
a250 1
    void writeDeclarations(raw_ostream &OS) const override {
d253 1
a253 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d257 1
a257 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d260 1
a260 1
    void writePCHWrite(raw_ostream &OS) const override {
d264 1
a264 1
    void writeValue(raw_ostream &OS) const override {
d276 1
a276 1
    void writeDump(raw_ostream &OS) const override {
d301 1
a301 1
    DefaultSimpleArgument(const Record &Arg, StringRef Attr,
d305 1
a305 1
    void writeAccessors(raw_ostream &OS) const override {
d315 1
a315 1
    StringArgument(const Record &Arg, StringRef Attr)
d319 1
a319 1
    void writeAccessors(raw_ostream &OS) const override {
d336 1
a336 1
    void writeCloneArgs(raw_ostream &OS) const override {
d339 1
a339 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d342 1
a342 1
    void writeCtorBody(raw_ostream &OS) const override {
d346 1
a346 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d351 1
a351 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d354 1
a354 1
    void writeCtorParameters(raw_ostream &OS) const override {
d357 1
a357 1
    void writeDeclarations(raw_ostream &OS) const override {
d361 1
a361 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d365 1
a365 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d368 1
a368 1
    void writePCHWrite(raw_ostream &OS) const override {
d371 1
a371 1
    void writeValue(raw_ostream &OS) const override {
d374 1
a374 1
    void writeDump(raw_ostream &OS) const override {
d382 1
a382 1
    AlignedArgument(const Record &Arg, StringRef Attr)
d386 1
a386 1
    void writeAccessors(raw_ostream &OS) const override {
d405 1
a405 1
    void writeAccessorDefinitions(raw_ostream &OS) const override {
d433 1
a433 1
    void writeCloneArgs(raw_ostream &OS) const override {
d439 1
a439 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d443 1
a443 1
    void writeCtorBody(raw_ostream &OS) const override {
d452 1
a452 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d455 1
a455 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d458 1
a458 1
    void writeCtorParameters(raw_ostream &OS) const override {
d461 1
a461 1
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
d464 1
a464 1
    void writeDeclarations(raw_ostream &OS) const override {
d471 1
a471 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d474 1
a474 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d483 1
a483 1
    void writePCHWrite(raw_ostream &OS) const override {
d491 1
a491 1
    void writeValue(raw_ostream &OS) const override {
d496 1
a496 1
    void writeDump(raw_ostream &OS) const override {
d498 1
a498 1
    void writeDumpChildren(raw_ostream &OS) const override {
d506 1
a506 1
    void writeHasChildren(raw_ostream &OS) const override {
d512 1
a512 1
    std::string Type, ArgName, ArgSizeName, RangeName;
d515 20
a534 21
    VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
        : Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
          ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}

    std::string getType() const { return Type; }

    void writeAccessors(raw_ostream &OS) const override {
      std::string IteratorType = getLowerName().str() + "_iterator";
      std::string BeginFn = getLowerName().str() + "_begin()";
      std::string EndFn = getLowerName().str() + "_end()";
      
      OS << "  typedef " << Type << "* " << IteratorType << ";\n";
      OS << "  " << IteratorType << " " << BeginFn << " const {"
         << " return " << ArgName << "; }\n";
      OS << "  " << IteratorType << " " << EndFn << " const {"
         << " return " << ArgName << " + " << ArgSizeName << "; }\n";
      OS << "  unsigned " << getLowerName() << "_size() const {"
         << " return " << ArgSizeName << "; }\n";
      OS << "  llvm::iterator_range<" << IteratorType << "> " << RangeName
         << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
         << "); }\n";
d536 2
a537 2
    void writeCloneArgs(raw_ostream &OS) const override {
      OS << ArgName << ", " << ArgSizeName;
d539 1
a539 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d544 9
a552 8
    void writeCtorBody(raw_ostream &OS) const override {
      OS << "    std::copy(" << getUpperName() << ", " << getUpperName()
         << " + " << ArgSizeName << ", " << ArgName << ");";
    }
    void writeCtorInitializers(raw_ostream &OS) const override {
      OS << ArgSizeName << "(" << getUpperName() << "Size), "
         << ArgName << "(new (Ctx, 16) " << getType() << "["
         << ArgSizeName << "])";
d554 2
a555 2
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
      OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
d557 1
a557 1
    void writeCtorParameters(raw_ostream &OS) const override {
d561 1
a561 1
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
d564 3
a566 3
    void writeDeclarations(raw_ostream &OS) const override {
      OS << "  unsigned " << ArgSizeName << ";\n";
      OS << "  " << getType() << " *" << ArgName << ";";
d568 1
a568 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d570 1
a570 1
      OS << "  SmallVector<" << Type << ", 4> " << getLowerName()
d576 1
a576 1
      std::string read = ReadPCHRecord(Type);
d579 1
a579 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d582 1
a582 1
    void writePCHWrite(raw_ostream &OS) const override {
d584 4
a587 2
      OS << "    for (auto &Val : SA->" << RangeName << "())\n";
      OS << "      " << WritePCHRecord(Type, "Val");
d589 1
a589 1
    void writeValue(raw_ostream &OS) const override {
d592 3
a594 1
         << "  for (const auto &Val : " << RangeName << "()) {\n"
d597 1
a597 1
         << "    OS << Val;\n"
d601 5
a605 3
    void writeDump(raw_ostream &OS) const override {
      OS << "    for (const auto &Val : SA->" << RangeName << "())\n";
      OS << "      OS << \" \" << Val;\n";
d614 4
a617 2
    for (const auto &i : enums) {
      std::set<std::string>::iterator set_i = unique_set.find(i);
d619 1
a619 1
        uniques.push_back(i);
d630 1
a630 1
    EnumArgument(const Record &Arg, StringRef Attr)
d640 1
a640 1
    bool isEnumArg() const override { return true; }
d642 1
a642 1
    void writeAccessors(raw_ostream &OS) const override {
d647 1
a647 1
    void writeCloneArgs(raw_ostream &OS) const override {
d650 1
a650 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d653 1
a653 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d656 1
a656 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d659 1
a659 1
    void writeCtorParameters(raw_ostream &OS) const override {
d662 1
a662 1
    void writeDeclarations(raw_ostream &OS) const override {
d677 1
a677 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d682 1
a682 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d685 1
a685 1
    void writePCHWrite(raw_ostream &OS) const override {
d688 1
a688 1
    void writeValue(raw_ostream &OS) const override {
d691 1
a691 1
    void writeDump(raw_ostream &OS) const override {
d693 4
a696 3
      for (const auto &I : uniques) {
        OS << "    case " << getAttrName() << "Attr::" << I << ":\n";
        OS << "      OS << \" " << I << "\";\n";
d706 1
a706 1
      OS << type << ">>(Val)\n";
d723 1
a723 1
    VariadicEnumArgument(const Record &Arg, StringRef Attr)
d736 1
a736 1
    bool isVariadicEnumArg() const override { return true; }
d738 1
a738 1
    void writeDeclarations(raw_ostream &OS) const override {
d754 1
a754 1
    void writeDump(raw_ostream &OS) const override {
d759 4
a762 3
      for (const auto &UI : uniques) {
        OS << "    case " << getAttrName() << "Attr::" << UI << ":\n";
        OS << "      OS << \" " << UI << "\";\n";
d768 1
a768 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d778 1
a778 1
    void writePCHWrite(raw_ostream &OS) const override {
d789 1
a789 1
      OS << type << ">>(Val)\n";
d804 1
a804 1
    VersionArgument(const Record &Arg, StringRef Attr)
d808 1
a808 1
    void writeAccessors(raw_ostream &OS) const override {
d817 1
a817 1
    void writeCloneArgs(raw_ostream &OS) const override {
d820 1
a820 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d823 3
a825 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d828 1
a828 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d831 1
a831 1
    void writeCtorParameters(raw_ostream &OS) const override {
d834 1
a834 1
    void writeDeclarations(raw_ostream &OS) const override {
d837 1
a837 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d841 1
a841 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d844 1
a844 1
    void writePCHWrite(raw_ostream &OS) const override {
d847 1
a847 1
    void writeValue(raw_ostream &OS) const override {
d850 1
a850 1
    void writeDump(raw_ostream &OS) const override {
d857 1
a857 1
    ExprArgument(const Record &Arg, StringRef Attr)
d861 1
a861 1
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
d867 1
a867 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d871 1
a871 1
    void writeTemplateInstantiation(raw_ostream &OS) const override {
d879 1
a879 1
         << "Result.getAs<Expr>();\n";
d883 2
a884 1
    void writeDump(raw_ostream &OS) const override {}
d886 1
a886 1
    void writeDumpChildren(raw_ostream &OS) const override {
d890 1
a890 1
    void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
d895 1
a895 1
    VariadicExprArgument(const Record &Arg, StringRef Attr)
d899 1
a899 1
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
d912 1
a912 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d917 1
a917 1
    void writeTemplateInstantiation(raw_ostream &OS) const override {
d932 1
a932 1
      OS << "          *TI = Result.getAs<Expr>();\n";
d937 2
a938 1
    void writeDump(raw_ostream &OS) const override {}
d940 1
a940 1
    void writeDumpChildren(raw_ostream &OS) const override {
d950 1
a950 1
    void writeHasChildren(raw_ostream &OS) const override {
d958 1
a958 1
    TypeArgument(const Record &Arg, StringRef Attr)
d962 1
a962 1
    void writeAccessors(raw_ostream &OS) const override {
d970 1
a970 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d973 1
a973 1
    void writePCHWrite(raw_ostream &OS) const override {
d980 2
a981 3
static std::unique_ptr<Argument>
createArgument(const Record &Arg, StringRef Attr,
               const Record *Search = nullptr) {
d985 1
a985 1
  Argument *Ptr = nullptr;
d1020 3
a1022 2
    for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
      Ptr = createArgument(Arg, Attr, Base).release();
d1031 1
a1031 1
  return std::unique_ptr<Argument>(Ptr);
d1066 2
a1067 4
static void
writePrettyPrintFunction(Record &R,
                         const std::vector<std::unique_ptr<Argument>> &Args,
                         raw_ostream &OS) {
d1120 1
a1120 2
    if (!Args.empty())
      OS << "(";
d1124 2
a1125 1
      for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
d1131 1
a1131 2
    if (!Args.empty())
      OS << ")";
d1166 1
a1166 1
static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
d1168 3
a1170 1
  for (const auto *Accessor : Accessors) {
d1194 3
a1196 3
  for (const auto &Spelling :
       llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
    std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
d1214 2
a1215 1
  for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
d1253 3
a1255 2
  for (const auto &I : Map)
    OS << "    case " << I.first << ": return " << I.second << ";\n";
d1264 5
a1268 2
  for (const auto *Attr : Attrs) {
    bool LateParsed = Attr->getValueAsBit("LateParsed");
d1271 1
a1271 1
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
d1274 3
a1276 2
      for (const auto &I : Spellings) {
        if (I.variety() != "GNU")
d1278 1
a1278 1
        OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
d1290 4
a1293 1
  for (const auto *Attr : Attrs) {
d1295 1
a1295 1
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
d1303 1
a1303 1
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
d1305 4
a1308 3
    for (const auto &S : Spellings) {
      if (Emitted.insert(S.name()).second)
        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
d1319 3
a1321 2
  for (const auto &I : Attrs) {
    const Record &Attr = *I.second;
d1329 4
a1332 3
    for (const auto &S : Spellings) {
      if (Emitted.insert(S.name()).second)
        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
d1351 4
a1354 1
  for (const auto *Attr : Attrs) {
d1356 1
a1356 1
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
d1361 1
a1361 1
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
d1363 4
a1366 3
    for (const auto &S : Spellings) {
      if (Emitted.insert(S.name()).second)
        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
d1383 3
a1385 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1404 3
a1406 2
    for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
      const Record &R = *Super;
d1414 2
a1415 1
    std::vector<std::unique_ptr<Argument>> Args;
d1418 9
a1426 3
    for (const auto *ArgRecord : ArgRecords) {
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));
      Args.back()->writeDeclarations(OS);
d1430 2
d1452 1
a1452 1
    for (auto const &ai : Args) {
d1454 1
a1454 1
      ai->writeCtorParameters(OS);
d1460 2
a1461 2
    for (auto const &ai : Args) {
      ai->writeImplicitCtorArgs(OS);
d1471 1
a1471 1
    for (auto const &ai : Args) {
d1473 1
a1473 1
      ai->writeCtorParameters(OS);
d1475 1
a1475 1
      if (ai->isOptional())
d1485 1
a1485 1
    for (auto const &ai : Args) {
d1487 1
a1487 1
      ai->writeCtorInitializers(OS);
d1493 2
a1494 2
    for (auto const &ai : Args) {
      ai->writeCtorBody(OS);
d1503 2
a1504 2
      for (auto const &ai : Args) {
        if (!ai->isOptional()) {
d1506 1
a1506 1
          ai->writeCtorParameters(OS);
d1517 1
a1517 1
      for (auto const &ai : Args) {
d1519 1
a1519 1
        ai->writeCtorDefaultInitializers(OS);
d1525 3
a1527 3
      for (auto const &ai : Args) {
        if (!ai->isOptional()) {
          ai->writeCtorBody(OS);
d1534 4
a1537 4
    OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const override;\n";
    OS << "  void printPretty(raw_ostream &OS,\n"
       << "                   const PrintingPolicy &Policy) const override;\n";
    OS << "  const char *getSpelling() const override;\n";
d1549 2
a1550 2
    for (auto const &ai : Args) {
      ai->writeAccessors(OS);
d1553 7
a1559 5
      if (ai->isEnumArg())
        static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
      else if (ai->isVariadicEnumArg())
        static_cast<const VariadicEnumArgument *>(ai.get())
            ->writeConversion(OS);
d1569 1
a1569 1
    OS << "  bool isLateParsed() const override { return "
d1573 1
a1573 1
      OS << "  bool duplicatesAllowed() const override { return true; }\n\n";
d1586 2
d1589 2
a1590 2
  for (auto *Attr : Attrs) {
    Record &R = *Attr;
d1594 1
a1594 1

d1596 3
a1598 3
    std::vector<std::unique_ptr<Argument>> Args;
    for (const auto *Arg : ArgRecords)
      Args.emplace_back(createArgument(*Arg, R.getName()));
d1600 2
a1601 2
    for (auto const &ai : Args)
      ai->writeAccessorDefinitions(OS);
d1606 1
a1606 1
    for (auto const &ai : Args) {
d1608 1
a1608 1
      ai->writeCloneArgs(OS);
d1667 3
a1669 2
  for (auto *Attr : Attrs) {
    if (!Attr->getValueAsBit("ASTNode"))
d1672 4
a1675 4
    if (Attr->isSubClassOf(InhParamClass))
      InhParamAttrs.push_back(Attr);
    else if (Attr->isSubClassOf(InhClass))
      InhAttrs.push_back(Attr);
d1677 1
a1677 1
      NonInhAttrs.push_back(Attr);
d1698 3
a1700 1
  std::vector<std::unique_ptr<Argument>> Args;
d1706 2
a1707 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1718 4
a1721 3
    for (const auto *Arg : ArgRecords) {
      Args.emplace_back(createArgument(*Arg, R.getName()));
      Args.back()->writePCHReadDecls(OS);
d1724 1
a1724 1
    for (auto const &ri : Args) {
d1726 1
a1726 1
      ri->writePCHReadArgs(OS);
d1744 1
d1750 2
a1751 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1764 2
a1765 2
    for (const auto *Arg : Args)
      createArgument(*Arg, R.getName())->writePCHWrite(OS);
d1772 11
a1782 4
static void GenerateHasAttrSpellingStringSwitch(
    const std::vector<Record *> &Attrs, raw_ostream &OS,
    const std::string &Variety = "", const std::string &Scope = "") {
  for (const auto *Attr : Attrs) {
d1787 2
a1788 2
    if (Attr->isSubClassOf("TargetSpecificAttr")) {
      const Record *R = Attr->getValueAsDef("Target");
d1792 2
a1793 1
      for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) {
d1805 2
a1806 1
        for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) {
d1815 1
a1815 9
      
      // If this is the C++11 variety, also add in the LangOpts test.
      if (Variety == "CXX11")
        Test += " && LangOpts.CPlusPlus11";
    } else if (Variety == "CXX11")
      // C++11 mode should be checked against LangOpts, which is presumed to be
      // present in the caller.
      Test = "LangOpts.CPlusPlus11";
    else
d1818 4
a1821 33
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
    for (const auto &S : Spellings)
      if (Variety.empty() || (Variety == S.variety() &&
                              (Scope.empty() || Scope == S.nameSpace())))
        OS << "    .Case(\"" << S.name() << "\", " << Test << ")\n";
  }
  OS << "    .Default(false);\n";
}

// Emits the list of spellings for attributes.
void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Code to implement the __has_attribute logic", OS);

  // Separate all of the attributes out into four group: generic, C++11, GNU,
  // and declspecs. Then generate a big switch statement for each of them.
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<Record *> Declspec, GNU;
  std::map<std::string, std::vector<Record *>> CXX;

  // Walk over the list of all attributes, and split them out based on the
  // spelling variety.
  for (auto *R : Attrs) {
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
    for (const auto &SI : Spellings) {
      std::string Variety = SI.variety();
      if (Variety == "GNU")
        GNU.push_back(R);
      else if (Variety == "Declspec")
        Declspec.push_back(R);
      else if (Variety == "CXX11") {
        CXX[SI.nameSpace()].push_back(R);
      }
    }
a1823 27
  OS << "switch (Syntax) {\n";
  OS << "case AttrSyntax::Generic:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Attrs, OS);
  OS << "case AttrSyntax::GNU:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
  OS << "case AttrSyntax::Declspec:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
  OS << "case AttrSyntax::CXX: {\n";
  // C++11-style attributes are further split out based on the Scope.
  for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(),
                                                              E = CXX.end();
       I != E; ++I) {
    if (I != CXX.begin())
      OS << " else ";
    if (I->first.empty())
      OS << "if (!Scope || Scope->getName() == \"\") {\n";
    else
      OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
    OS << "  return llvm::StringSwitch<bool>(Name)\n";
    GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
    OS << "}";
  }
  OS << "\n}\n";
  OS << "}\n";
d1837 3
a1839 2
  for (const auto &I : Attrs) {
    const Record &R = *I.second;
d1841 1
a1841 1
    OS << "  case AT_" << I.first << ": {\n";
d1874 3
a1876 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1889 3
a1891 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1904 8
a1911 2
    for (const auto *Arg : ArgRecords)
      createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
d1927 3
a1929 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1957 3
a1959 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1983 2
a1984 1
    std::vector<std::unique_ptr<Argument>> Args;
d1987 9
a1995 5
    for (const auto *ArgRecord : ArgRecords)
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));

    for (auto const &ai : Args)
      ai->writeTemplateInstantiation(OS);
d1997 3
d2001 1
a2001 1
    for (auto const &ai : Args) {
d2003 1
a2003 1
      ai->writeTemplateInstantiationArgs(OS);
d2024 3
a2026 2
  for (const auto &I : Names) {
    OS << "PARSED_ATTR(" << I.first << ")\n";
d2036 4
a2039 2
  for (const auto *Arg : Args) {
    Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
d2072 4
a2075 3
    Field = 1U << 12,
    CXXMethod = 1U << 13,
    ObjCProtocol = 1U << 14
d2080 3
a2082 2
  for (const auto *Subject : Subjects) {
    const Record &R = *Subject;
d2108 1
d2115 2
a2116 1
      PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
d2148 1
d2229 2
a2230 1
  for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
d2281 2
a2282 1
  for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
d2311 1
a2311 1
  OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n";
d2341 5
a2345 4
    for (const auto &I : Dupes) {
      if (I.first == APK) {
        std::vector<std::string> DA = I.second->getValueAsDef("Target")
                                          ->getValueAsListOfStrings("Arches");
d2352 2
a2353 1
  for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
d2371 2
a2372 1
    for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
d2390 1
a2390 1
  OS << "static bool " << FnName << "(const llvm::Triple &T) {\n";
d2439 3
a2441 2
  for (const auto &I : Spellings) {
    if (I.knownToGCC())
d2468 2
a2469 1
  for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
d2508 3
a2510 2
  for (const auto *A : Attrs) {
    const Record &Attr = *A;
d2536 5
a2540 4
      for (const auto &S : Spellings) {
        std::string RawSpelling = S.name();
        std::vector<StringMatcher::StringPair> *Matches = nullptr;
        std::string Spelling, Variety = S.variety();
d2543 1
a2543 1
          Spelling += S.nameSpace();
d2590 3
a2592 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d2608 3
a2610 2
      for (const auto *Arg : Args)
        createArgument(*Arg, R.getName())->writeDump(OS);
d2614 1
a2614 1
      OS << "    bool MoreChildren;\n";
d2616 2
a2617 1
      for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI) {
d2620 1
a2620 1
        for (auto Next = AI + 1; Next != AE; ++Next) {
d2627 1
a2627 1
        createArgument(**AI, R.getName())->writeDumpChildren(OS);
d2703 2
a2704 2
      for (auto I = Spellings.begin(), E = Spellings.end();
           I != E && Uniques.size() <= 1; ++I) {
d2726 3
a2728 2
  for (const auto &I : Spellings) {
    SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
d2738 3
a2740 3
    if (Kind == CXX11 && !I.nameSpace().empty())
      Name = I.nameSpace() + "::";
    Name += I.name();
d2751 2
a2752 1
    for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
d2817 4
d2824 3
a2826 3
  std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
  for (const auto *A : Attrs) {
    const Record &Attr = *A;
d2828 3
a2830 2
    for (const auto *D : Docs) {
      const Record &Doc = *D;
d2849 3
a2851 2
  for (const auto &I : SplitDocs) {
    WriteCategoryHeader(I.first, OS);
d2855 3
a2857 2
    for (const auto &Doc : I.second)
      WriteDocumentation(Doc, OS);
@


1.1.1.6
log
@Import Clang 3.5svn r209886.
@
text
@a14 1
#include "llvm/ADT/STLExtras.h"
d17 1
a23 1
#include <memory>
d59 5
a63 2
  for (const auto &Spelling : Spellings) {
    if (Spelling->getValueAsString("Variety") == "GCC") {
d65 1
a65 1
      Ret.push_back(FlattenedSpelling("GNU", Spelling->getValueAsString("Name"),
d67 3
a69 2
      Ret.push_back(FlattenedSpelling(
          "CXX11", Spelling->getValueAsString("Name"), "gnu", true));
d71 1
a71 1
      Ret.push_back(FlattenedSpelling(*Spelling));
d135 1
a135 1
typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
d138 2
a139 2
                                       ParsedAttrMap *Dupes = nullptr) {
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
d142 4
a145 2
  for (const auto *Attr : Attrs) {
    if (Attr->getValueAsBit("SemaHandler")) {
d147 3
a149 3
      if (Attr->isSubClassOf("TargetSpecificAttr") &&
          !Attr->isValueUnset("ParseKind")) {
        AN = Attr->getValueAsString("ParseKind");
d155 1
a155 1
            Dupes->push_back(std::make_pair(AN, Attr));
d160 1
a160 1
        AN = NormalizeAttrName(Attr->getName()).str();
d162 1
a162 1
      R.push_back(std::make_pair(AN, Attr));
d175 1
a175 1
    Argument(const Record &Arg, StringRef Attr)
d224 1
a224 1
    SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
d230 1
a230 1
    void writeAccessors(raw_ostream &OS) const override {
d235 1
a235 1
    void writeCloneArgs(raw_ostream &OS) const override {
d238 1
a238 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d241 1
a241 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d244 1
a244 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d247 1
a247 1
    void writeCtorParameters(raw_ostream &OS) const override {
d250 1
a250 1
    void writeDeclarations(raw_ostream &OS) const override {
d253 1
a253 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d257 1
a257 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d260 1
a260 1
    void writePCHWrite(raw_ostream &OS) const override {
d264 1
a264 1
    void writeValue(raw_ostream &OS) const override {
d276 1
a276 1
    void writeDump(raw_ostream &OS) const override {
d301 1
a301 1
    DefaultSimpleArgument(const Record &Arg, StringRef Attr,
d305 1
a305 1
    void writeAccessors(raw_ostream &OS) const override {
d315 1
a315 1
    StringArgument(const Record &Arg, StringRef Attr)
d319 1
a319 1
    void writeAccessors(raw_ostream &OS) const override {
d336 1
a336 1
    void writeCloneArgs(raw_ostream &OS) const override {
d339 1
a339 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d342 1
a342 1
    void writeCtorBody(raw_ostream &OS) const override {
d346 1
a346 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d351 1
a351 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d354 1
a354 1
    void writeCtorParameters(raw_ostream &OS) const override {
d357 1
a357 1
    void writeDeclarations(raw_ostream &OS) const override {
d361 1
a361 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d365 1
a365 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d368 1
a368 1
    void writePCHWrite(raw_ostream &OS) const override {
d371 1
a371 1
    void writeValue(raw_ostream &OS) const override {
d374 1
a374 1
    void writeDump(raw_ostream &OS) const override {
d382 1
a382 1
    AlignedArgument(const Record &Arg, StringRef Attr)
d386 1
a386 1
    void writeAccessors(raw_ostream &OS) const override {
d405 1
a405 1
    void writeAccessorDefinitions(raw_ostream &OS) const override {
d433 1
a433 1
    void writeCloneArgs(raw_ostream &OS) const override {
d439 1
a439 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d443 1
a443 1
    void writeCtorBody(raw_ostream &OS) const override {
d452 1
a452 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d455 1
a455 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d458 1
a458 1
    void writeCtorParameters(raw_ostream &OS) const override {
d461 1
a461 1
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
d464 1
a464 1
    void writeDeclarations(raw_ostream &OS) const override {
d471 1
a471 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d474 1
a474 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d483 1
a483 1
    void writePCHWrite(raw_ostream &OS) const override {
d491 1
a491 1
    void writeValue(raw_ostream &OS) const override {
d496 1
a496 1
    void writeDump(raw_ostream &OS) const override {
d498 1
a498 1
    void writeDumpChildren(raw_ostream &OS) const override {
d506 1
a506 1
    void writeHasChildren(raw_ostream &OS) const override {
d512 1
a512 1
    std::string Type, ArgName, ArgSizeName, RangeName;
d515 20
a534 21
    VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
        : Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
          ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}

    std::string getType() const { return Type; }

    void writeAccessors(raw_ostream &OS) const override {
      std::string IteratorType = getLowerName().str() + "_iterator";
      std::string BeginFn = getLowerName().str() + "_begin()";
      std::string EndFn = getLowerName().str() + "_end()";
      
      OS << "  typedef " << Type << "* " << IteratorType << ";\n";
      OS << "  " << IteratorType << " " << BeginFn << " const {"
         << " return " << ArgName << "; }\n";
      OS << "  " << IteratorType << " " << EndFn << " const {"
         << " return " << ArgName << " + " << ArgSizeName << "; }\n";
      OS << "  unsigned " << getLowerName() << "_size() const {"
         << " return " << ArgSizeName << "; }\n";
      OS << "  llvm::iterator_range<" << IteratorType << "> " << RangeName
         << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
         << "); }\n";
d536 2
a537 2
    void writeCloneArgs(raw_ostream &OS) const override {
      OS << ArgName << ", " << ArgSizeName;
d539 1
a539 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d544 9
a552 8
    void writeCtorBody(raw_ostream &OS) const override {
      OS << "    std::copy(" << getUpperName() << ", " << getUpperName()
         << " + " << ArgSizeName << ", " << ArgName << ");";
    }
    void writeCtorInitializers(raw_ostream &OS) const override {
      OS << ArgSizeName << "(" << getUpperName() << "Size), "
         << ArgName << "(new (Ctx, 16) " << getType() << "["
         << ArgSizeName << "])";
d554 2
a555 2
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
      OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
d557 1
a557 1
    void writeCtorParameters(raw_ostream &OS) const override {
d561 1
a561 1
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
d564 3
a566 3
    void writeDeclarations(raw_ostream &OS) const override {
      OS << "  unsigned " << ArgSizeName << ";\n";
      OS << "  " << getType() << " *" << ArgName << ";";
d568 1
a568 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d570 1
a570 1
      OS << "  SmallVector<" << Type << ", 4> " << getLowerName()
d576 1
a576 1
      std::string read = ReadPCHRecord(Type);
d579 1
a579 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d582 1
a582 1
    void writePCHWrite(raw_ostream &OS) const override {
d584 4
a587 2
      OS << "    for (auto &Val : SA->" << RangeName << "())\n";
      OS << "      " << WritePCHRecord(Type, "Val");
d589 1
a589 1
    void writeValue(raw_ostream &OS) const override {
d592 3
a594 1
         << "  for (const auto &Val : " << RangeName << "()) {\n"
d597 1
a597 1
         << "    OS << Val;\n"
d601 5
a605 3
    void writeDump(raw_ostream &OS) const override {
      OS << "    for (const auto &Val : SA->" << RangeName << "())\n";
      OS << "      OS << \" \" << Val;\n";
d614 4
a617 2
    for (const auto &i : enums) {
      std::set<std::string>::iterator set_i = unique_set.find(i);
d619 1
a619 1
        uniques.push_back(i);
d630 1
a630 1
    EnumArgument(const Record &Arg, StringRef Attr)
d640 1
a640 1
    bool isEnumArg() const override { return true; }
d642 1
a642 1
    void writeAccessors(raw_ostream &OS) const override {
d647 1
a647 1
    void writeCloneArgs(raw_ostream &OS) const override {
d650 1
a650 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d653 1
a653 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d656 1
a656 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d659 1
a659 1
    void writeCtorParameters(raw_ostream &OS) const override {
d662 1
a662 1
    void writeDeclarations(raw_ostream &OS) const override {
d677 1
a677 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d682 1
a682 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d685 1
a685 1
    void writePCHWrite(raw_ostream &OS) const override {
d688 1
a688 1
    void writeValue(raw_ostream &OS) const override {
d691 1
a691 1
    void writeDump(raw_ostream &OS) const override {
d693 4
a696 3
      for (const auto &I : uniques) {
        OS << "    case " << getAttrName() << "Attr::" << I << ":\n";
        OS << "      OS << \" " << I << "\";\n";
d706 1
a706 1
      OS << type << ">>(Val)\n";
d723 1
a723 1
    VariadicEnumArgument(const Record &Arg, StringRef Attr)
d736 1
a736 1
    bool isVariadicEnumArg() const override { return true; }
d738 1
a738 1
    void writeDeclarations(raw_ostream &OS) const override {
d754 1
a754 1
    void writeDump(raw_ostream &OS) const override {
d759 4
a762 3
      for (const auto &UI : uniques) {
        OS << "    case " << getAttrName() << "Attr::" << UI << ":\n";
        OS << "      OS << \" " << UI << "\";\n";
d768 1
a768 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d778 1
a778 1
    void writePCHWrite(raw_ostream &OS) const override {
d789 1
a789 1
      OS << type << ">>(Val)\n";
d804 1
a804 1
    VersionArgument(const Record &Arg, StringRef Attr)
d808 1
a808 1
    void writeAccessors(raw_ostream &OS) const override {
d817 1
a817 1
    void writeCloneArgs(raw_ostream &OS) const override {
d820 1
a820 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d823 3
a825 1
    void writeCtorInitializers(raw_ostream &OS) const override {
d828 1
a828 1
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
d831 1
a831 1
    void writeCtorParameters(raw_ostream &OS) const override {
d834 1
a834 1
    void writeDeclarations(raw_ostream &OS) const override {
d837 1
a837 1
    void writePCHReadDecls(raw_ostream &OS) const override {
d841 1
a841 1
    void writePCHReadArgs(raw_ostream &OS) const override {
d844 1
a844 1
    void writePCHWrite(raw_ostream &OS) const override {
d847 1
a847 1
    void writeValue(raw_ostream &OS) const override {
d850 1
a850 1
    void writeDump(raw_ostream &OS) const override {
d857 1
a857 1
    ExprArgument(const Record &Arg, StringRef Attr)
d861 1
a861 1
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
d867 1
a867 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d871 1
a871 1
    void writeTemplateInstantiation(raw_ostream &OS) const override {
d879 1
a879 1
         << "Result.getAs<Expr>();\n";
d883 2
a884 1
    void writeDump(raw_ostream &OS) const override {}
d886 1
a886 1
    void writeDumpChildren(raw_ostream &OS) const override {
d890 1
a890 1
    void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
d895 1
a895 1
    VariadicExprArgument(const Record &Arg, StringRef Attr)
d899 1
a899 1
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
d912 1
a912 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d917 1
a917 1
    void writeTemplateInstantiation(raw_ostream &OS) const override {
d932 1
a932 1
      OS << "          *TI = Result.getAs<Expr>();\n";
d937 2
a938 1
    void writeDump(raw_ostream &OS) const override {}
d940 1
a940 1
    void writeDumpChildren(raw_ostream &OS) const override {
d950 1
a950 1
    void writeHasChildren(raw_ostream &OS) const override {
d958 1
a958 1
    TypeArgument(const Record &Arg, StringRef Attr)
d962 1
a962 1
    void writeAccessors(raw_ostream &OS) const override {
d970 1
a970 1
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
d973 1
a973 1
    void writePCHWrite(raw_ostream &OS) const override {
d980 2
a981 3
static std::unique_ptr<Argument>
createArgument(const Record &Arg, StringRef Attr,
               const Record *Search = nullptr) {
d985 1
a985 1
  Argument *Ptr = nullptr;
d1020 3
a1022 2
    for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
      Ptr = createArgument(Arg, Attr, Base).release();
d1031 1
a1031 1
  return std::unique_ptr<Argument>(Ptr);
d1066 2
a1067 4
static void
writePrettyPrintFunction(Record &R,
                         const std::vector<std::unique_ptr<Argument>> &Args,
                         raw_ostream &OS) {
d1120 1
a1120 2
    if (!Args.empty())
      OS << "(";
d1124 2
a1125 1
      for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
d1131 1
a1131 2
    if (!Args.empty())
      OS << ")";
d1166 1
a1166 1
static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
d1168 3
a1170 1
  for (const auto *Accessor : Accessors) {
d1194 3
a1196 3
  for (const auto &Spelling :
       llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
    std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
d1214 2
a1215 1
  for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
d1253 3
a1255 2
  for (const auto &I : Map)
    OS << "    case " << I.first << ": return " << I.second << ";\n";
d1264 5
a1268 2
  for (const auto *Attr : Attrs) {
    bool LateParsed = Attr->getValueAsBit("LateParsed");
d1271 1
a1271 1
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
d1274 3
a1276 2
      for (const auto &I : Spellings) {
        if (I.variety() != "GNU")
d1278 1
a1278 1
        OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
d1290 4
a1293 1
  for (const auto *Attr : Attrs) {
d1295 1
a1295 1
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
d1303 1
a1303 1
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
d1305 4
a1308 3
    for (const auto &S : Spellings) {
      if (Emitted.insert(S.name()).second)
        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
d1319 3
a1321 2
  for (const auto &I : Attrs) {
    const Record &Attr = *I.second;
d1329 4
a1332 3
    for (const auto &S : Spellings) {
      if (Emitted.insert(S.name()).second)
        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
d1351 4
a1354 1
  for (const auto *Attr : Attrs) {
d1356 1
a1356 1
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
d1361 1
a1361 1
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
d1363 4
a1366 3
    for (const auto &S : Spellings) {
      if (Emitted.insert(S.name()).second)
        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
d1383 3
a1385 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1404 3
a1406 2
    for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
      const Record &R = *Super;
d1414 2
a1415 1
    std::vector<std::unique_ptr<Argument>> Args;
d1418 9
a1426 3
    for (const auto *ArgRecord : ArgRecords) {
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));
      Args.back()->writeDeclarations(OS);
d1430 2
d1452 1
a1452 1
    for (auto const &ai : Args) {
d1454 1
a1454 1
      ai->writeCtorParameters(OS);
d1460 2
a1461 2
    for (auto const &ai : Args) {
      ai->writeImplicitCtorArgs(OS);
d1471 1
a1471 1
    for (auto const &ai : Args) {
d1473 1
a1473 1
      ai->writeCtorParameters(OS);
d1475 1
a1475 1
      if (ai->isOptional())
d1485 1
a1485 1
    for (auto const &ai : Args) {
d1487 1
a1487 1
      ai->writeCtorInitializers(OS);
d1493 2
a1494 2
    for (auto const &ai : Args) {
      ai->writeCtorBody(OS);
d1503 2
a1504 2
      for (auto const &ai : Args) {
        if (!ai->isOptional()) {
d1506 1
a1506 1
          ai->writeCtorParameters(OS);
d1517 1
a1517 1
      for (auto const &ai : Args) {
d1519 1
a1519 1
        ai->writeCtorDefaultInitializers(OS);
d1525 3
a1527 3
      for (auto const &ai : Args) {
        if (!ai->isOptional()) {
          ai->writeCtorBody(OS);
d1534 4
a1537 4
    OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const override;\n";
    OS << "  void printPretty(raw_ostream &OS,\n"
       << "                   const PrintingPolicy &Policy) const override;\n";
    OS << "  const char *getSpelling() const override;\n";
d1549 2
a1550 2
    for (auto const &ai : Args) {
      ai->writeAccessors(OS);
d1553 7
a1559 5
      if (ai->isEnumArg())
        static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
      else if (ai->isVariadicEnumArg())
        static_cast<const VariadicEnumArgument *>(ai.get())
            ->writeConversion(OS);
d1569 1
a1569 1
    OS << "  bool isLateParsed() const override { return "
d1573 1
a1573 1
      OS << "  bool duplicatesAllowed() const override { return true; }\n\n";
d1586 2
d1589 2
a1590 2
  for (auto *Attr : Attrs) {
    Record &R = *Attr;
d1594 1
a1594 1

d1596 3
a1598 3
    std::vector<std::unique_ptr<Argument>> Args;
    for (const auto *Arg : ArgRecords)
      Args.emplace_back(createArgument(*Arg, R.getName()));
d1600 2
a1601 2
    for (auto const &ai : Args)
      ai->writeAccessorDefinitions(OS);
d1606 1
a1606 1
    for (auto const &ai : Args) {
d1608 1
a1608 1
      ai->writeCloneArgs(OS);
d1667 3
a1669 2
  for (auto *Attr : Attrs) {
    if (!Attr->getValueAsBit("ASTNode"))
d1672 4
a1675 4
    if (Attr->isSubClassOf(InhParamClass))
      InhParamAttrs.push_back(Attr);
    else if (Attr->isSubClassOf(InhClass))
      InhAttrs.push_back(Attr);
d1677 1
a1677 1
      NonInhAttrs.push_back(Attr);
d1698 3
a1700 1
  std::vector<std::unique_ptr<Argument>> Args;
d1706 2
a1707 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1718 4
a1721 3
    for (const auto *Arg : ArgRecords) {
      Args.emplace_back(createArgument(*Arg, R.getName()));
      Args.back()->writePCHReadDecls(OS);
d1724 1
a1724 1
    for (auto const &ri : Args) {
d1726 1
a1726 1
      ri->writePCHReadArgs(OS);
d1744 1
d1750 2
a1751 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1764 2
a1765 2
    for (const auto *Arg : Args)
      createArgument(*Arg, R.getName())->writePCHWrite(OS);
d1772 11
a1782 4
static void GenerateHasAttrSpellingStringSwitch(
    const std::vector<Record *> &Attrs, raw_ostream &OS,
    const std::string &Variety = "", const std::string &Scope = "") {
  for (const auto *Attr : Attrs) {
d1787 2
a1788 2
    if (Attr->isSubClassOf("TargetSpecificAttr")) {
      const Record *R = Attr->getValueAsDef("Target");
d1792 2
a1793 1
      for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) {
d1805 2
a1806 1
        for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) {
d1815 1
a1815 9
      
      // If this is the C++11 variety, also add in the LangOpts test.
      if (Variety == "CXX11")
        Test += " && LangOpts.CPlusPlus11";
    } else if (Variety == "CXX11")
      // C++11 mode should be checked against LangOpts, which is presumed to be
      // present in the caller.
      Test = "LangOpts.CPlusPlus11";
    else
d1818 4
a1821 33
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
    for (const auto &S : Spellings)
      if (Variety.empty() || (Variety == S.variety() &&
                              (Scope.empty() || Scope == S.nameSpace())))
        OS << "    .Case(\"" << S.name() << "\", " << Test << ")\n";
  }
  OS << "    .Default(false);\n";
}

// Emits the list of spellings for attributes.
void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Code to implement the __has_attribute logic", OS);

  // Separate all of the attributes out into four group: generic, C++11, GNU,
  // and declspecs. Then generate a big switch statement for each of them.
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<Record *> Declspec, GNU;
  std::map<std::string, std::vector<Record *>> CXX;

  // Walk over the list of all attributes, and split them out based on the
  // spelling variety.
  for (auto *R : Attrs) {
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
    for (const auto &SI : Spellings) {
      std::string Variety = SI.variety();
      if (Variety == "GNU")
        GNU.push_back(R);
      else if (Variety == "Declspec")
        Declspec.push_back(R);
      else if (Variety == "CXX11") {
        CXX[SI.nameSpace()].push_back(R);
      }
    }
a1823 27
  OS << "switch (Syntax) {\n";
  OS << "case AttrSyntax::Generic:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Attrs, OS);
  OS << "case AttrSyntax::GNU:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
  OS << "case AttrSyntax::Declspec:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
  OS << "case AttrSyntax::CXX: {\n";
  // C++11-style attributes are further split out based on the Scope.
  for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(),
                                                              E = CXX.end();
       I != E; ++I) {
    if (I != CXX.begin())
      OS << " else ";
    if (I->first.empty())
      OS << "if (!Scope || Scope->getName() == \"\") {\n";
    else
      OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
    OS << "  return llvm::StringSwitch<bool>(Name)\n";
    GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
    OS << "}";
  }
  OS << "\n}\n";
  OS << "}\n";
d1837 3
a1839 2
  for (const auto &I : Attrs) {
    const Record &R = *I.second;
d1841 1
a1841 1
    OS << "  case AT_" << I.first << ": {\n";
d1874 3
a1876 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1889 3
a1891 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1904 8
a1911 2
    for (const auto *Arg : ArgRecords)
      createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
d1927 3
a1929 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1957 3
a1959 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d1983 2
a1984 1
    std::vector<std::unique_ptr<Argument>> Args;
d1987 9
a1995 5
    for (const auto *ArgRecord : ArgRecords)
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));

    for (auto const &ai : Args)
      ai->writeTemplateInstantiation(OS);
d1997 3
d2001 1
a2001 1
    for (auto const &ai : Args) {
d2003 1
a2003 1
      ai->writeTemplateInstantiationArgs(OS);
d2024 3
a2026 2
  for (const auto &I : Names) {
    OS << "PARSED_ATTR(" << I.first << ")\n";
d2036 4
a2039 2
  for (const auto *Arg : Args) {
    Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
d2072 4
a2075 3
    Field = 1U << 12,
    CXXMethod = 1U << 13,
    ObjCProtocol = 1U << 14
d2080 3
a2082 2
  for (const auto *Subject : Subjects) {
    const Record &R = *Subject;
d2108 1
d2115 2
a2116 1
      PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
d2148 1
d2229 2
a2230 1
  for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
d2281 2
a2282 1
  for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
d2311 1
a2311 1
  OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n";
d2341 5
a2345 4
    for (const auto &I : Dupes) {
      if (I.first == APK) {
        std::vector<std::string> DA = I.second->getValueAsDef("Target")
                                          ->getValueAsListOfStrings("Arches");
d2352 2
a2353 1
  for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
d2371 2
a2372 1
    for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
d2390 1
a2390 1
  OS << "static bool " << FnName << "(const llvm::Triple &T) {\n";
d2439 3
a2441 2
  for (const auto &I : Spellings) {
    if (I.knownToGCC())
d2468 2
a2469 1
  for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
d2508 3
a2510 2
  for (const auto *A : Attrs) {
    const Record &Attr = *A;
d2536 5
a2540 4
      for (const auto &S : Spellings) {
        std::string RawSpelling = S.name();
        std::vector<StringMatcher::StringPair> *Matches = nullptr;
        std::string Spelling, Variety = S.variety();
d2543 1
a2543 1
          Spelling += S.nameSpace();
d2590 3
a2592 2
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
d2608 3
a2610 2
      for (const auto *Arg : Args)
        createArgument(*Arg, R.getName())->writeDump(OS);
d2614 1
a2614 1
      OS << "    bool MoreChildren;\n";
d2616 2
a2617 1
      for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI) {
d2620 1
a2620 1
        for (auto Next = AI + 1; Next != AE; ++Next) {
d2627 1
a2627 1
        createArgument(**AI, R.getName())->writeDumpChildren(OS);
d2703 2
a2704 2
      for (auto I = Spellings.begin(), E = Spellings.end();
           I != E && Uniques.size() <= 1; ++I) {
d2726 3
a2728 2
  for (const auto &I : Spellings) {
    SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
d2738 3
a2740 3
    if (Kind == CXX11 && !I.nameSpace().empty())
      Name = I.nameSpace() + "::";
    Name += I.name();
d2751 2
a2752 1
    for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
d2817 4
d2824 3
a2826 3
  std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
  for (const auto *A : Attrs) {
    const Record &Attr = *A;
d2828 3
a2830 2
    for (const auto *D : Docs) {
      const Record &Doc = *D;
d2849 3
a2851 2
  for (const auto &I : SplitDocs) {
    WriteCategoryHeader(I.first, OS);
d2855 3
a2857 2
    for (const auto &Doc : I.second)
      WriteDocumentation(Doc, OS);
@


1.1.1.7
log
@Import clang 3.6svn r215315.
@
text
@d44 1
a44 1
    if (V == "CXX11" || V == "Pragma")
a208 1
    virtual bool isVariadic() const { return false; }
d487 3
a489 6
      OS << "\";\n";
      // The aligned attribute argument expression is optional.
      OS << "    if (is" << getLowerName() << "Expr && "
         << getLowerName() << "Expr)\n";
      OS << "      " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n";
      OS << "    OS << \"";
a514 1
    bool isVariadic() const override { return true; }
d967 1
a967 1
  std::unique_ptr<Argument> Ptr;
d970 3
a972 6
  if (ArgName == "AlignedArgument")
    Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
  else if (ArgName == "EnumArgument")
    Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
  else if (ArgName == "ExprArgument")
    Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
d974 1
a974 1
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
d976 1
a976 1
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
d978 4
a981 4
    Ptr = llvm::make_unique<DefaultSimpleArgument>(
        Arg, Attr, "bool", Arg.getValueAsBit("Default"));
  else if (ArgName == "BoolArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
d983 5
a987 8
    Ptr = llvm::make_unique<DefaultSimpleArgument>(
        Arg, Attr, "int", Arg.getValueAsInt("Default"));
  else if (ArgName == "IntArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
  else if (ArgName == "StringArgument")
    Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
  else if (ArgName == "TypeArgument")
    Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
d989 1
a989 1
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
d991 1
a991 1
    Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
d993 1
a993 1
    Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
d995 1
a995 1
    Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
d997 1
a997 1
    Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
d1003 2
a1004 1
      if ((Ptr = createArgument(Arg, Attr, Base)))
d1012 1
a1012 1
  return Ptr;
d1056 1
a1056 1
  if (Spellings.empty()) {
d1083 1
a1083 1
      if (!Namespace.empty()) {
a1092 8
    } else if (Variety == "Pragma") {
      Prefix = "#pragma ";
      Suffix = "\n";
      std::string Namespace = Spellings[I].nameSpace();
      if (!Namespace.empty()) {
        Spelling += Namespace;
        Spelling += " ";
      }
a1102 13
    if (Variety == "Pragma") {
      OS << " \";\n";
      OS << "    printPrettyPragma(OS, Policy);\n";
      OS << "    break;\n";
      OS << "  }\n";
      continue;
    }

    // FIXME: always printing the parenthesis isn't the correct behavior for
    // attributes which have optional arguments that were not provided. For
    // instance: __attribute__((aligned)) will be pretty printed as
    // __attribute__((aligned())). The logic should check whether there is only
    // a single argument, and if it is optional, whether it has been provided.
d1556 1
a1556 1
    OS << "  auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
d1561 1
a1561 5
    OS << ", getSpellingListIndex());\n";
    OS << "  A->Inherited = Inherited;\n";
    OS << "  A->IsPackExpansion = IsPackExpansion;\n";
    OS << "  A->Implicit = Implicit;\n";
    OS << "  return A;\n}\n\n";
d1652 2
a1653 1
  OS << "    llvm_unreachable(\"Unknown attribute!\");\n";
d1779 1
a1779 1
  std::vector<Record *> Declspec, GNU, Pragma;
d1792 1
a1792 1
      else if (Variety == "CXX11")
d1794 1
a1794 2
      else if (Variety == "Pragma")
        Pragma.push_back(R);
a1807 3
  OS << "case AttrSyntax::Pragma:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
d1843 11
a1853 11
      OS << "    if (Name == \"" << Spellings[I].name() << "\" && "
         << "SyntaxUsed == "
         << StringSwitch<unsigned>(Spellings[I].variety())
                .Case("GNU", 0)
                .Case("CXX11", 1)
                .Case("Declspec", 2)
                .Case("Keyword", 3)
                .Case("Pragma", 4)
                .Default(0)
         << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
         << "        return " << I << ";\n";
a2010 4
static bool isArgVariadic(const Record &R, StringRef AttrName) {
  return createArgument(R, AttrName)->isVariadic();
}

a2016 1
  bool HasVariadic = false;
a2018 2
    if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
      HasVariadic = true;
d2020 1
a2020 4

  // If there is a variadic argument, we will set the optional argument count
  // to its largest value. Since it's currently a 4-bit number, we set it to 15.
  OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
a2131 2
    case ObjCProtocol | ObjCInterface:
      return "ExpectedObjectiveCInterfaceOrProtocol";
d2473 1
a2473 1
  std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma;
a2515 2
        else if (Variety == "Pragma")
          Matches = &Pragma;
a2539 2
  OS << "  } else if (AttributeList::AS_Pragma == Syntax) {\n";
  StringMatcher("Name", Pragma, OS).Emit();
d2645 1
a2645 2
  Keyword = 1 << 3,
  Pragma = 1 << 4
d2690 4
a2693 5
                            .Case("GNU", GNU)
                            .Case("CXX11", CXX11)
                            .Case("Declspec", Declspec)
                            .Case("Keyword", Keyword)
                            .Case("Pragma", Pragma);
d2728 1
a2728 2
  OS << "   :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
  OS << " \"Pragma\"\n\n";
a2736 2
  OS << "\", \"";
  if (SupportedSpellings & Pragma) OS << "X";
@


1.1.1.7.2.1
log
@Update LLVM to 3.6.1, requested by joerg in ticket 824.
@
text
@a16 1
#include "llvm/ADT/StringExtras.h"
d498 2
a499 1
      OS << "    if (SA->is" << getUpperName() << "Expr())\n";
d501 1
a501 1
      OS << "    else\n";
a512 6
  protected:
    // Assumed to receive a parameter: raw_ostream OS.
    virtual void writeValueImpl(raw_ostream &OS) const {
      OS << "    OS << Val;\n";
    }

d592 3
a594 3
         << "    else OS << \", \";\n";
      writeValueImpl(OS);
      OS << "  }\n";
d681 1
a681 5
      // FIXME: this isn't 100% correct -- some enum arguments require printing
      // as a string literal, while others require printing as an identifier.
      // Tablegen currently does not distinguish between the two forms.
      OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
         << getUpperName() << "()) << \"\\\"";
d706 1
a706 18
      OS << "  }\n\n";

      // Mapping from enumeration values back to enumeration strings isn't
      // trivial because some enumeration values have multiple named
      // enumerators, such as type_visibility(internal) and
      // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
      OS << "  static const char *Convert" << type << "ToStr("
         << type << " Val) {\n"
         << "    switch(Val) {\n";
      std::set<std::string> Uniques;
      for (size_t I = 0; I < enums.size(); ++I) {
        if (Uniques.insert(enums[I]).second)
          OS << "    case " << getAttrName() << "Attr::" << enums[I]
             << ": return \"" << values[I] << "\";\n";       
      }
      OS << "    }\n"
         << "    llvm_unreachable(\"No enumerator with that value\");\n"
         << "  }\n";
a712 10

  protected:
    void writeValueImpl(raw_ostream &OS) const override {
      // FIXME: this isn't 100% correct -- some enum arguments require printing
      // as a string literal, while others require printing as an identifier.
      // Tablegen currently does not distinguish between the two forms.
      OS << "    OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
         << "ToStr(Val)" << "<< \"\\\"\";\n";
    }

d788 1
a788 14
      OS << "  }\n\n";

      OS << "  static const char *Convert" << type << "ToStr("
        << type << " Val) {\n"
        << "    switch(Val) {\n";
      std::set<std::string> Uniques;
      for (size_t I = 0; I < enums.size(); ++I) {
        if (Uniques.insert(enums[I]).second)
          OS << "    case " << getAttrName() << "Attr::" << enums[I]
          << ": return \"" << values[I] << "\";\n";
      }
      OS << "    }\n"
        << "    llvm_unreachable(\"No enumerator with that value\");\n"
        << "  }\n";
d874 1
d929 3
a931 1
         << getLowerName() << "_end(); I != E; ++I)\n";
d933 1
a1343 1
    .Case("VariadicEnumArgument", true)
d1622 1
a1622 8
// Determines if an attribute has a Pragma spelling.
static bool AttrHasPragmaSpelling(const Record *R) {
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
  return std::find_if(Spellings.begin(), Spellings.end(),
                      [](const FlattenedSpelling &S) {
           return S.variety() == "Pragma";
         }) != Spellings.end();
}
a1623 1
namespace clang {
a1648 8
  OS << "#ifndef PRAGMA_SPELLING_ATTR\n";
  OS << "#define PRAGMA_SPELLING_ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef LAST_PRAGMA_SPELLING_ATTR\n";
  OS << "#define LAST_PRAGMA_SPELLING_ATTR(NAME) PRAGMA_SPELLING_ATTR(NAME)\n";
  OS << "#endif\n\n";

d1651 2
a1652 2
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"),
                        NonInhAttrs, InhAttrs, InhParamAttrs, PragmaAttrs;
d1656 1
a1656 4

    if (AttrHasPragmaSpelling(Attr))
      PragmaAttrs.push_back(Attr);

a1664 1
  EmitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
a1672 2
  OS << "#undef LAST_PRAGMA_ATTR\n";
  OS << "#undef PRAGMA_SPELLING_ATTR\n";
a1755 21
    // C++11-style attributes have specific version information associated with
    // them. If the attribute has no scope, the version information must not
    // have the default value (1), as that's incorrect. Instead, the unscoped
    // attribute version information should be taken from the SD-6 standing
    // document, which can be found at: 
    // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
    int Version = 1;

    if (Variety == "CXX11") {
        std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
        for (const auto &Spelling : Spellings) {
          if (Spelling->getValueAsString("Variety") == "CXX11") {
            Version = static_cast<int>(Spelling->getValueAsInt("Version"));
            if (Scope.empty() && Version == 1)
              PrintError(Spelling->getLoc(), "C++ standard attributes must "
              "have valid version information.");
            break;
          }
      }
    }

d1794 2
a1796 2
    std::string TestStr =
        !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
d1801 1
a1801 1
        OS << "    .Case(\"" << S.name() << "\", " << TestStr << ")\n";
d1803 1
a1803 1
  OS << "    .Default(0);\n";
d1834 3
d1838 1
a1838 1
  OS << "  return llvm::StringSwitch<int>(Name)\n";
d1841 1
a1841 1
  OS << "  return llvm::StringSwitch<int>(Name)\n";
d1844 1
a1844 1
  OS << "  return llvm::StringSwitch<int>(Name)\n";
d1857 1
a1857 1
    OS << "  return llvm::StringSwitch<int>(Name)\n";
d2629 14
a2642 1
      for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI)
d2644 4
@


1.1.1.8
log
@Import Clang 3.6RC1 r227398.
@
text
@a16 1
#include "llvm/ADT/StringExtras.h"
d498 2
a499 1
      OS << "    if (SA->is" << getUpperName() << "Expr())\n";
d501 1
a501 1
      OS << "    else\n";
a512 6
  protected:
    // Assumed to receive a parameter: raw_ostream OS.
    virtual void writeValueImpl(raw_ostream &OS) const {
      OS << "    OS << Val;\n";
    }

d592 3
a594 3
         << "    else OS << \", \";\n";
      writeValueImpl(OS);
      OS << "  }\n";
d681 1
a681 5
      // FIXME: this isn't 100% correct -- some enum arguments require printing
      // as a string literal, while others require printing as an identifier.
      // Tablegen currently does not distinguish between the two forms.
      OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
         << getUpperName() << "()) << \"\\\"";
d706 1
a706 18
      OS << "  }\n\n";

      // Mapping from enumeration values back to enumeration strings isn't
      // trivial because some enumeration values have multiple named
      // enumerators, such as type_visibility(internal) and
      // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
      OS << "  static const char *Convert" << type << "ToStr("
         << type << " Val) {\n"
         << "    switch(Val) {\n";
      std::set<std::string> Uniques;
      for (size_t I = 0; I < enums.size(); ++I) {
        if (Uniques.insert(enums[I]).second)
          OS << "    case " << getAttrName() << "Attr::" << enums[I]
             << ": return \"" << values[I] << "\";\n";       
      }
      OS << "    }\n"
         << "    llvm_unreachable(\"No enumerator with that value\");\n"
         << "  }\n";
a712 10

  protected:
    void writeValueImpl(raw_ostream &OS) const override {
      // FIXME: this isn't 100% correct -- some enum arguments require printing
      // as a string literal, while others require printing as an identifier.
      // Tablegen currently does not distinguish between the two forms.
      OS << "    OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
         << "ToStr(Val)" << "<< \"\\\"\";\n";
    }

d788 1
a788 14
      OS << "  }\n\n";

      OS << "  static const char *Convert" << type << "ToStr("
        << type << " Val) {\n"
        << "    switch(Val) {\n";
      std::set<std::string> Uniques;
      for (size_t I = 0; I < enums.size(); ++I) {
        if (Uniques.insert(enums[I]).second)
          OS << "    case " << getAttrName() << "Attr::" << enums[I]
          << ": return \"" << values[I] << "\";\n";
      }
      OS << "    }\n"
        << "    llvm_unreachable(\"No enumerator with that value\");\n"
        << "  }\n";
d874 1
d929 3
a931 1
         << getLowerName() << "_end(); I != E; ++I)\n";
d933 1
a1343 1
    .Case("VariadicEnumArgument", true)
d1622 1
a1622 8
// Determines if an attribute has a Pragma spelling.
static bool AttrHasPragmaSpelling(const Record *R) {
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
  return std::find_if(Spellings.begin(), Spellings.end(),
                      [](const FlattenedSpelling &S) {
           return S.variety() == "Pragma";
         }) != Spellings.end();
}
a1623 1
namespace clang {
a1648 8
  OS << "#ifndef PRAGMA_SPELLING_ATTR\n";
  OS << "#define PRAGMA_SPELLING_ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef LAST_PRAGMA_SPELLING_ATTR\n";
  OS << "#define LAST_PRAGMA_SPELLING_ATTR(NAME) PRAGMA_SPELLING_ATTR(NAME)\n";
  OS << "#endif\n\n";

d1651 2
a1652 2
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"),
                        NonInhAttrs, InhAttrs, InhParamAttrs, PragmaAttrs;
d1656 1
a1656 4

    if (AttrHasPragmaSpelling(Attr))
      PragmaAttrs.push_back(Attr);

a1664 1
  EmitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
a1672 2
  OS << "#undef LAST_PRAGMA_ATTR\n";
  OS << "#undef PRAGMA_SPELLING_ATTR\n";
a1755 21
    // C++11-style attributes have specific version information associated with
    // them. If the attribute has no scope, the version information must not
    // have the default value (1), as that's incorrect. Instead, the unscoped
    // attribute version information should be taken from the SD-6 standing
    // document, which can be found at: 
    // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
    int Version = 1;

    if (Variety == "CXX11") {
        std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
        for (const auto &Spelling : Spellings) {
          if (Spelling->getValueAsString("Variety") == "CXX11") {
            Version = static_cast<int>(Spelling->getValueAsInt("Version"));
            if (Scope.empty() && Version == 1)
              PrintError(Spelling->getLoc(), "C++ standard attributes must "
              "have valid version information.");
            break;
          }
      }
    }

d1794 2
a1796 2
    std::string TestStr =
        !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
d1801 1
a1801 1
        OS << "    .Case(\"" << S.name() << "\", " << TestStr << ")\n";
d1803 1
a1803 1
  OS << "    .Default(0);\n";
d1834 3
d1838 1
a1838 1
  OS << "  return llvm::StringSwitch<int>(Name)\n";
d1841 1
a1841 1
  OS << "  return llvm::StringSwitch<int>(Name)\n";
d1844 1
a1844 1
  OS << "  return llvm::StringSwitch<int>(Name)\n";
d1857 1
a1857 1
    OS << "  return llvm::StringSwitch<int>(Name)\n";
d2629 14
a2642 1
      for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI)
d2644 4
@


1.1.1.9
log
@Import Clang 3.8.0rc3 r261930.
@
text
@a30 1
namespace {
a55 1
} // end anonymous namespace
d57 1
a57 2
static std::vector<FlattenedSpelling>
GetFlattenedSpellings(const Record &Attr) {
d64 4
a67 3
      Ret.emplace_back("GNU", Spelling->getValueAsString("Name"), "", true);
      Ret.emplace_back("CXX11", Spelling->getValueAsString("Name"), "gnu",
                       true);
a81 1
    .Case("std::string", "ReadString(Record, Idx)")
a94 1
    .Case("std::string", "AddString(" + std::string(name) + ", Record);\n")
d115 5
a119 1
  return Name.trim("_");
a168 1
    bool Fake;
d173 1
a173 1
        attrName(Attr), isOpt(false), Fake(false) {
d179 1
a179 1
    virtual ~Argument() = default;
a187 3
    bool isFake() const { return Fake; }
    void setFake(bool fake) { Fake = fake; }

a277 2
        if (isOptional())
          OS << "    if (SA->get" << getUpperName() << "())\n  ";
d329 1
a329 2
      OS << "    if (!S.empty())\n";
      OS << "      std::memcpy(this->" << getLowerName() << ", S.data(), "
d340 1
a340 2
      OS << "      if (!" << getUpperName() << ".empty())\n";
      OS << "        std::memcpy(" << getLowerName() << ", " << getUpperName()
d349 1
a349 1
      OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
d417 2
d423 3
a425 4
      OS << "    return " << getLowerName() << "Expr ? " << getLowerName()
         << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
         << " * Ctx.getCharWidth() : "
         << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
d493 1
a493 1
      OS << "      " << getLowerName() << "Expr->printPretty(OS, nullptr, Policy);\n";
d615 1
a615 1
      auto set_i = unique_set.find(i);
d661 2
a662 1
      auto i = uniques.cbegin(), e = uniques.cend();
d767 2
a768 1
      auto i = uniques.cbegin(), e = uniques.cend();
d954 1
a954 1
      OS << "      auto *tempInst" << getUpperName()
a987 10
  class VariadicStringArgument : public VariadicArgument {
  public:
    VariadicStringArgument(const Record &Arg, StringRef Attr)
      : VariadicArgument(Arg, Attr, "std::string")
    {}
    void writeValueImpl(raw_ostream &OS) const override {
      OS << "    OS << \"\\\"\" << Val << \"\\\"\";\n";
    }
  };

d1010 1
a1010 1
} // end anonymous namespace
a1048 2
  else if (ArgName == "VariadicStringArgument")
    Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
d1058 1
a1058 1
    ArrayRef<Record*> Bases = Search->getSuperClasses();
a1067 3
  if (Ptr && Arg.getValueAsBit("Fake"))
    Ptr->setFake(true);

d1165 1
a1165 1
      "    OS << \"" << Prefix << Spelling;
a1169 1
      OS << "    OS << \"\\n\";";
a1174 8
    // Fake arguments aren't part of the parsed form and should not be
    // pretty-printed.
    bool hasNonFakeArgs = false;
    for (const auto &arg : Args) {
      if (arg->isFake()) continue;
      hasNonFakeArgs = true;
    }

d1180 1
a1180 1
    if (hasNonFakeArgs)
d1185 3
a1187 5
      unsigned index = 0;
      for (const auto &arg : Args) {
        if (arg->isFake()) continue;
        if (index++) OS << ", ";
        arg->writeValue(OS);
d1191 1
a1191 1
    if (hasNonFakeArgs)
d1193 1
a1193 1
    OS << Suffix + "\";\n";
d1210 1
a1210 1
  assert(!SpellingList.empty() && "Spelling list is empty!");
d1234 1
a1234 1
    assert(!SpellingList.empty() &&
d1300 1
a1300 5
    // Duplicate spellings are not considered part of the semantic spelling
    // enumeration, but the spelling index and semantic spelling values are
    // meant to be equivalent, so we must specify a concrete value for each
    // enumerator.
    Ret += "    " + EnumName + " = " + llvm::utostr(Idx);
d1444 1
a1444 1
    ArrayRef<Record *> Supers = R.getSuperClasses();
a1458 2
    bool HasOptArg = false;
    bool HasFakeArg = false;
a1462 7

      // For these purposes, fake takes priority over optional.
      if (Args.back()->isFake()) {
        HasFakeArg = true;
      } else if (Args.back()->isOptional()) {
        HasOptArg = true;
      }
d1481 50
a1530 40
    // Emit CreateImplicit factory methods.
    auto emitCreateImplicit = [&](bool emitFake) {
      OS << "  static " << R.getName() << "Attr *CreateImplicit(";
      OS << "ASTContext &Ctx";
      if (!ElideSpelling)
        OS << ", Spelling S";
      for (auto const &ai : Args) {
        if (ai->isFake() && !emitFake) continue;
        OS << ", ";
        ai->writeCtorParameters(OS);
      }
      OS << ", SourceRange Loc = SourceRange()";
      OS << ") {\n";
      OS << "    auto *A = new (Ctx) " << R.getName();
      OS << "Attr(Loc, Ctx, ";
      for (auto const &ai : Args) {
        if (ai->isFake() && !emitFake) continue;
        ai->writeImplicitCtorArgs(OS);
        OS << ", ";
      }
      OS << (ElideSpelling ? "0" : "S") << ");\n";
      OS << "    A->setImplicit(true);\n";
      OS << "    return A;\n  }\n\n";
    };

    // Emit a CreateImplicit that takes all the arguments.
    emitCreateImplicit(true);

    // Emit a CreateImplicit that takes all the non-fake arguments.
    if (HasFakeArg) {
      emitCreateImplicit(false);
    }

    // Emit constructors.
    auto emitCtor = [&](bool emitOpt, bool emitFake) {
      auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
        if (arg->isFake()) return emitFake;
        if (arg->isOptional()) return emitOpt;
        return true;
      };
d1532 3
d1537 5
a1541 4
        if (!shouldEmitArg(ai)) continue;
        OS << "              , ";
        ai->writeCtorParameters(OS);
        OS << "\n";
d1548 1
a1548 3
      OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
         << R.getValueAsBit("LateParsed") << ", "
         << R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n";
d1552 1
a1552 5
        if (!shouldEmitArg(ai)) {
          ai->writeCtorDefaultInitializers(OS);
        } else {
          ai->writeCtorInitializers(OS);
        }
d1559 4
a1562 3
        if (!shouldEmitArg(ai)) continue;
        ai->writeCtorBody(OS);
        OS << "\n";
a1564 15

    };

    // Emit a constructor that includes all the arguments.
    // This is necessary for cloning.
    emitCtor(true, true);

    // Emit a constructor that takes all the non-fake arguments.
    if (HasFakeArg) {
      emitCtor(true, false);
    }
 
    // Emit a constructor that takes all the non-fake, non-optional arguments.
    if (HasOptArg) {
      emitCtor(false, false);
d1567 1
a1567 1
    OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
d1569 2
a1570 2
       << "                   const PrintingPolicy &Policy) const;\n";
    OS << "  const char *getSpelling() const;\n";
a1585 3
      // Don't write conversion routines for fake arguments.
      if (ai->isFake()) continue;

d1599 7
d1609 1
a1609 1
  OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
a1647 30

  // Instead of relying on virtual dispatch we just create a huge dispatch
  // switch. This is both smaller and faster than virtual functions.
  auto EmitFunc = [&](const char *Method) {
    OS << "  switch (getKind()) {\n";
    for (const auto *Attr : Attrs) {
      const Record &R = *Attr;
      if (!R.getValueAsBit("ASTNode"))
        continue;

      OS << "  case attr::" << R.getName() << ":\n";
      OS << "    return cast<" << R.getName() << "Attr>(this)->" << Method
         << ";\n";
    }
    OS << "  case attr::NUM_ATTRS:\n";
    OS << "    break;\n";
    OS << "  }\n";
    OS << "  llvm_unreachable(\"Unexpected attribute kind!\");\n";
    OS << "}\n\n";
  };

  OS << "const char *Attr::getSpelling() const {\n";
  EmitFunc("getSpelling()");

  OS << "Attr *Attr::clone(ASTContext &C) const {\n";
  EmitFunc("clone(C)");

  OS << "void Attr::printPretty(raw_ostream &OS, "
        "const PrintingPolicy &Policy) const {\n";
  EmitFunc("printPretty(OS, Policy)");
d1654 1
a1654 1
  auto i = AttrList.cbegin(), e = AttrList.cend();
d1806 1
a1806 1
      OS << "    const auto *SA = cast<" << R.getName()
a1820 59
// Generate a conditional expression to check if the current target satisfies
// the conditions for a TargetSpecificAttr record, and append the code for
// those checks to the Test string. If the FnName string pointer is non-null,
// append a unique suffix to distinguish this set of target checks from other
// TargetSpecificAttr records.
static void GenerateTargetSpecificAttrChecks(const Record *R,
                                             std::vector<std::string> &Arches,
                                             std::string &Test,
                                             std::string *FnName) {
  // It is assumed that there will be an llvm::Triple object
  // named "T" and a TargetInfo object named "Target" within
  // scope that can be used to determine whether the attribute exists in
  // a given target.
  Test += "(";

  for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
    std::string Part = *I;
    Test += "T.getArch() == llvm::Triple::" + Part;
    if (I + 1 != E)
      Test += " || ";
    if (FnName)
      *FnName += Part;
  }
  Test += ")";

  // If the attribute is specific to particular OSes, check those.
  if (!R->isValueUnset("OSes")) {
    // We know that there was at least one arch test, so we need to and in the
    // OS tests.
    Test += " && (";
    std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
    for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
      std::string Part = *I;

      Test += "T.getOS() == llvm::Triple::" + Part;
      if (I + 1 != E)
        Test += " || ";
      if (FnName)
        *FnName += Part;
    }
    Test += ")";
  }

  // If one or more CXX ABIs are specified, check those as well.
  if (!R->isValueUnset("CXXABIs")) {
    Test += " && (";
    std::vector<std::string> CXXABIs = R->getValueAsListOfStrings("CXXABIs");
    for (auto I = CXXABIs.begin(), E = CXXABIs.end(); I != E; ++I) {
      std::string Part = *I;
      Test += "Target.getCXXABI().getKind() == TargetCXXABI::" + Part;
      if (I + 1 != E)
        Test += " || ";
      if (FnName)
        *FnName += Part;
    }
    Test += ")";
  }
}

d1846 3
a1852 1
      GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
d1854 23
a1922 1
  OS << "const llvm::Triple &T = Target.getTriple();\n";
d1935 3
a1937 1
  for (auto I = CXX.cbegin(), E = CXX.cend(); I != E; ++I) {
d2008 1
a2008 1
       << "  }\n";
d2082 1
a2082 1
      OS << "      return nullptr;\n";
d2087 1
a2087 1
    OS << "      const auto *A = cast<"
d2116 1
a2116 1
     << "  return nullptr;\n"
d2188 1
a2188 2
    ObjCProtocol = 1U << 14,
    Enum = 1U << 15
a2221 1
                   .Case("Enum", Enum)
a2239 1
    case Enum:  return "ExpectedEnum";
a2283 1

d2291 1
a2291 1
  auto I = CustomSubjectSet.find(FnName);
d2305 1
a2305 1
  OS << "  if (const auto *S = dyn_cast<";
a2392 2
    if ((*I)->getValueAsBit("Negated"))
      Test += "!";
d2403 1
a2403 1
  auto I = CustomLangOptsSet.find(FnName);
d2420 1
a2420 1
  OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
d2459 29
a2487 3
  std::string FnName = "isTarget";
  std::string Test;
  GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
d2492 1
a2492 1
  auto I = CustomTargetSet.find(FnName);
d2496 4
a2499 2
  OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
  OS << "  const llvm::Triple &T = Target.getTriple();\n";
d2677 1
a2677 2
  OS << "  } else if (AttributeList::AS_Keyword == Syntax || ";
  OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n";
d2711 1
a2711 1
      OS << "    const auto *SA = cast<" << R.getName()
d2716 2
a2717 2
      for (const auto *AI : Args)
        createArgument(*AI, R.getName())->writeDumpChildren(OS);
d2751 11
a2761 3
  // Trim leading and trailing newlines and spaces.
  OS << StringRef(ContentStr).trim();

d2883 8
a2890 1
  OS << StringRef(ContentStr).trim();
@


1.1.1.9.2.1
log
@Sync with HEAD
@
text
@a13 3
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/iterator_range.h"
d16 1
a17 1
#include "llvm/ADT/StringRef.h"
a18 2
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
a23 1
#include <cassert>
a24 3
#include <cstddef>
#include <cstdint>
#include <map>
a27 3
#include <string>
#include <utility>
#include <vector>
a31 1

a56 1

d84 1
a84 1
    .Case("StringRef", "ReadString(Record, Idx)")
a87 7
// Get a type that is suitable for storing an object of the specified type.
static StringRef getStorageType(StringRef type) {
  return StringSwitch<StringRef>(type)
    .Case("StringRef", "std::string")
    .Default(type);
}

d90 5
a94 3
  return "Record." + StringSwitch<std::string>(type)
    .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
    .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
d96 4
a99 3
    .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
    .Case("StringRef", "AddString(" + std::string(name) + ");\n")
    .Default("push_back(" + std::string(name) + ");\n");
d106 6
a111 2
  AttrName.consume_front("__");
  AttrName.consume_back("__");
d122 4
a125 3
// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
// removing "__" if it appears at the beginning and end of the attribute's name.
static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
a164 1

a178 5
      // Work around MinGW's macro definition of 'interface' to 'struct'. We
      // have an attribute argument called 'Interface', so only the lower case
      // name conflicts with the macro definition.
      if (lowerName == "interface")
        lowerName = "interface_";
d226 2
a227 1
        : Argument(Arg, Attr), type(std::move(T)) {}
a235 1

a238 1

a241 1

a244 1

a247 1

a250 1

a253 1

a257 1

a260 1

a264 1

d270 1
a270 7
        OS << "\";\n";
        if (isOptional())
          OS << "    if (get" << getUpperName() << "()) ";
        else
          OS << "    ";
        OS << "OS << get" << getUpperName() << "()->getName();\n";
        OS << "    OS << \"";
a276 1

d312 1
a312 6
         << " = ";
      if (getType() == "bool")
        OS << (Default != 0 ? "true" : "false");
      else
        OS << Default;
      OS << ";";
a339 1

a342 1

a345 1

d349 1
a349 1
         << ".data(), " << getLowerName() << "Length);\n";
a350 1

a355 1

a358 1

a361 1

a365 1

a369 1

a372 1

d374 1
a374 1
      OS << "    Record.AddString(SA->get" << getUpperName() << "());\n";
a375 1

a378 1

a409 1

a436 1

a442 1

a446 1

d454 1
a454 1
         << ");\n";
a455 1

a458 1

a461 1

a464 1

a467 1

a474 1

a477 1

a486 1

d490 1
a490 1
      OS << "      Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
d492 2
a493 2
      OS << "      Record.AddTypeSourceInfo(SA->get" << getUpperName()
         << "Type());\n";
a494 1

d503 2
a504 3

    void writeDump(raw_ostream &OS) const override {}

a511 1

d528 4
a531 7
        : Argument(Arg, Attr), Type(std::move(T)),
          ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
          RangeName(getLowerName()) {}

    const std::string &getType() const { return Type; }
    const std::string &getArgName() const { return ArgName; }
    const std::string &getArgSizeName() const { return ArgSizeName; }
a549 1

a552 1

a557 1

d560 1
a560 1
         << " + " << ArgSizeName << ", " << ArgName << ");\n";
a561 1

a566 1

a569 1

a573 1

a576 1

a580 1

d582 4
a585 4
      OS << "    unsigned " << getLowerName() << "Size = Record[Idx++];\n";
      OS << "    SmallVector<" << getType() << ", 4> "
         << getLowerName() << ";\n";
      OS << "    " << getLowerName() << ".reserve(" << getLowerName()
d587 2
a588 15

      // If we can't store the values in the current type (if it's something
      // like StringRef), store them in a different type and convert the
      // container afterwards.
      std::string StorageType = getStorageType(getType());
      std::string StorageName = getLowerName();
      if (StorageType != getType()) {
        StorageName += "Storage";
        OS << "    SmallVector<" << StorageType << ", 4> "
           << StorageName << ";\n";
        OS << "    " << StorageName << ".reserve(" << getLowerName()
           << "Size);\n";
      }

      OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
d590 1
a590 7
      OS << "      " << StorageName << ".push_back(" << read << ");\n";

      if (StorageType != getType()) {
        OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
        OS << "      " << getLowerName() << ".push_back("
           << StorageName << "[i]);\n";
      }
a591 1

a594 1

a599 1

a609 1

d620 1
a620 1
    SmallDenseSet<StringRef, 8> unique_set;
d622 2
a623 1
      if (unique_set.insert(i).second)
d625 2
a651 1

a654 1

a680 1

a685 1

a688 1

a691 1

a698 1

d731 1
a731 1
      SmallDenseSet<StringRef, 8> Uniques;
a786 1

a799 1

a809 1

a816 1

d835 1
a835 1
      SmallDenseSet<StringRef, 8> Uniques;
a861 1

a864 1

a867 1

a870 1

a873 1

a876 1

a879 1

a883 1

a886 1

d888 1
a888 1
      OS << "    Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
a889 1

a892 1

a930 1

d996 1
a996 1
      : VariadicArgument(Arg, Attr, "StringRef")
a997 13

    void writeCtorBody(raw_ostream &OS) const override {
      OS << "    for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
            "         ++I) {\n"
            "      StringRef Ref = " << getUpperName() << "[I];\n"
            "      if (!Ref.empty()) {\n"
            "        char *Mem = new (Ctx, 1) char[Ref.size()];\n"
            "        std::memcpy(Mem, Ref.data(), Ref.size());\n"
            "        " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
            "      }\n"
            "    }\n";
    }

a1016 1

a1019 1

a1024 1

d1075 3
a1077 3
    ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
    for (const auto &Base : llvm::reverse(Bases)) {
      if ((Ptr = createArgument(Arg, Attr, Base.first)))
a1092 1
     << "  if (getStrict()) OS << \", strict\";\n"
a1099 9
static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
  OS << "\\\"\" << getMessage() << \"\\\"\";\n";
  // Only GNU deprecated has an optional fixit argument at the second position.
  if (Variety == "GNU")
     OS << "    if (!getReplacement().empty()) OS << \", \\\"\""
           " << getReplacement() << \"\\\"\";\n";
  OS << "    OS << \"";
}

a1165 3
    } else if (Variety == "Microsoft") {
      Prefix = "[";
      Suffix = "]";
d1198 5
a1202 2
    bool hasNonFakeArgs = llvm::any_of(
        Args, [](const std::unique_ptr<Argument> &A) { return !A->isFake(); });
a1212 2
    } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
        writeDeprecatedAttrValue(OS, Variety);
a1259 6
  if (Accessors.empty())
    return;

  const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
  assert(!SpellingList.empty() &&
         "Attribute with empty spelling list can't have accessors!");
d1262 5
a1266 1
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
d1271 1
a1271 1
      if (Index != Spellings.size() - 1)
d1306 4
a1309 4
    const std::string &Variety = S.variety();
    const std::string &Spelling = S.name();
    const std::string &Namespace = S.nameSpace();
    std::string EnumName;
a1372 10
template <typename Fn>
static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  SmallDenseSet<StringRef, 8> Seen;
  for (const FlattenedSpelling &S : Spellings) {
    if (Seen.insert(S.name()).second)
      F(S);
  }
}

d1384 1
a1384 1
    if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
d1388 6
a1393 3
    forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
    });
d1410 6
a1415 3
    forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
    });
d1422 1
a1422 1
    llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
d1441 6
a1446 3
    forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
    });
d1479 1
a1479 1
    ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
d1482 4
a1485 4
    for (const auto &Super : llvm::reverse(Supers)) {
      const Record *R = Super.first;
      if (R->getName() != "TargetSpecificAttr" && SuperName.empty())
        SuperName = R->getName();
d1509 1
a1509 1
    OS << "public:\n";
d1579 2
a1580 2
         << ( R.getValueAsBit("LateParsed") ? "true" : "false" ) << ", "
         << ( R.getValueAsBit("DuplicatesAllowedWhileMerging") ? "true" : "false" ) << ")\n";
d1597 1
d1600 1
d1708 2
d1728 1
a1728 1
static void emitAttrList(raw_ostream &OS, StringRef Class,
d1730 12
a1741 2
  for (auto Cur : AttrList) {
    OS << Class << "(" << Cur->getName() << ")\n";
d1748 2
a1749 1
  return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
d1754 4
a1757 1
namespace {
d1759 3
a1761 4
  struct AttrClassDescriptor {
    const char * const MacroName;
    const char * const TableGenName;
  };
d1763 3
a1765 1
} // end anonymous namespace
d1767 3
a1769 7
static const AttrClassDescriptor AttrClassDescriptors[] = {
  { "ATTR", "Attr" },
  { "STMT_ATTR", "StmtAttr" },
  { "INHERITABLE_ATTR", "InheritableAttr" },
  { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
  { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
};
d1771 3
a1773 7
static void emitDefaultDefine(raw_ostream &OS, StringRef name,
                              const char *superName) {
  OS << "#ifndef " << name << "\n";
  OS << "#define " << name << "(NAME) ";
  if (superName) OS << superName << "(NAME)";
  OS << "\n#endif\n\n";
}
d1775 4
a1778 1
namespace {
d1780 3
a1782 7
  /// A class of attributes.
  struct AttrClass {
    const AttrClassDescriptor &Descriptor;
    Record *TheRecord;
    AttrClass *SuperClass = nullptr;
    std::vector<AttrClass*> SubClasses;
    std::vector<Record*> Attrs;
d1784 3
a1786 2
    AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
      : Descriptor(Descriptor), TheRecord(R) {}
d1788 4
a1791 154
    void emitDefaultDefines(raw_ostream &OS) const {
      // Default the macro unless this is a root class (i.e. Attr).
      if (SuperClass) {
        emitDefaultDefine(OS, Descriptor.MacroName,
                          SuperClass->Descriptor.MacroName);
      }
    }

    void emitUndefs(raw_ostream &OS) const {
      OS << "#undef " << Descriptor.MacroName << "\n";
    }

    void emitAttrList(raw_ostream &OS) const {
      for (auto SubClass : SubClasses) {
        SubClass->emitAttrList(OS);
      }

      ::emitAttrList(OS, Descriptor.MacroName, Attrs);
    }

    void classifyAttrOnRoot(Record *Attr) {
      bool result = classifyAttr(Attr);
      assert(result && "failed to classify on root"); (void) result;
    }

    void emitAttrRange(raw_ostream &OS) const {
      OS << "ATTR_RANGE(" << Descriptor.TableGenName
         << ", " << getFirstAttr()->getName()
         << ", " << getLastAttr()->getName() << ")\n";
    }

  private:
    bool classifyAttr(Record *Attr) {
      // Check all the subclasses.
      for (auto SubClass : SubClasses) {
        if (SubClass->classifyAttr(Attr))
          return true;
      }

      // It's not more specific than this class, but it might still belong here.
      if (Attr->isSubClassOf(TheRecord)) {
        Attrs.push_back(Attr);
        return true;
      }

      return false;
    }

    Record *getFirstAttr() const {
      if (!SubClasses.empty())
        return SubClasses.front()->getFirstAttr();
      return Attrs.front();
    }

    Record *getLastAttr() const {
      if (!Attrs.empty())
        return Attrs.back();
      return SubClasses.back()->getLastAttr();
    }
  };

  /// The entire hierarchy of attribute classes.
  class AttrClassHierarchy {
    std::vector<std::unique_ptr<AttrClass>> Classes;

  public:
    AttrClassHierarchy(RecordKeeper &Records) {
      // Find records for all the classes.
      for (auto &Descriptor : AttrClassDescriptors) {
        Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
        AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
        Classes.emplace_back(Class);
      }

      // Link up the hierarchy.
      for (auto &Class : Classes) {
        if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
          Class->SuperClass = SuperClass;
          SuperClass->SubClasses.push_back(Class.get());
        }
      }

#ifndef NDEBUG
      for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
        assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
               "only the first class should be a root class!");
      }
#endif
    }

    void emitDefaultDefines(raw_ostream &OS) const {
      for (auto &Class : Classes) {
        Class->emitDefaultDefines(OS);
      }
    }

    void emitUndefs(raw_ostream &OS) const {
      for (auto &Class : Classes) {
        Class->emitUndefs(OS);
      }
    }

    void emitAttrLists(raw_ostream &OS) const {
      // Just start from the root class.
      Classes[0]->emitAttrList(OS);
    }

    void emitAttrRanges(raw_ostream &OS) const {
      for (auto &Class : Classes)
        Class->emitAttrRange(OS);
    }

    void classifyAttr(Record *Attr) {
      // Add the attribute to the root class.
      Classes[0]->classifyAttrOnRoot(Attr);
    }

  private:
    AttrClass *findClassByRecord(Record *R) const {
      for (auto &Class : Classes) {
        if (Class->TheRecord == R)
          return Class.get();
      }
      return nullptr;
    }

    AttrClass *findSuperClass(Record *R) const {
      // TableGen flattens the superclass list, so we just need to walk it
      // in reverse.
      auto SuperClasses = R->getSuperClasses();
      for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
        auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
        if (SuperClass) return SuperClass;
      }
      return nullptr;
    }
  };

} // end anonymous namespace

namespace clang {

// Emits the enumeration list for attributes.
void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);

  AttrClassHierarchy Hierarchy(Records);

  // Add defaulting macro definitions.
  Hierarchy.emitDefaultDefines(OS);
  emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);

  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<Record *> PragmaAttrs;
a1795 1
    // Add the attribute to the ad-hoc groups.
d1799 6
a1804 2
    // Place it in the hierarchy.
    Hierarchy.classifyAttr(Attr);
d1807 10
a1816 13
  // Emit the main attribute list.
  Hierarchy.emitAttrLists(OS);

  // Emit the ad hoc groups.
  emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);

  // Emit the attribute ranges.
  OS << "#ifdef ATTR_RANGE\n";
  Hierarchy.emitAttrRanges(OS);
  OS << "#undef ATTR_RANGE\n";
  OS << "#endif\n";

  Hierarchy.emitUndefs(OS);
d1818 1
d1831 2
d1872 3
d2013 1
a2013 1
  std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
d2021 1
a2021 1
      const std::string &Variety = SI.variety();
a2025 2
      else if (Variety == "Microsoft")
        Microsoft.push_back(R);
a2040 3
  OS << "case AttrSyntax::Microsoft:\n";
  OS << "  return llvm::StringSwitch<int>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
d2065 5
a2069 1
  OS << "  switch (AttrKind) {\n";
d2083 2
a2084 3
                .Case("Microsoft", 3)
                .Case("Keyword", 4)
                .Case("Pragma", 5)
d2149 3
a2151 1
     << "  switch (A->getKind()) {\n";
d2162 1
a2162 2
  OS << "  }\n";  // end switch
  OS << "  llvm_unreachable(\"bad attribute kind\");\n";
d2178 3
a2180 1
     << "  switch (At->getKind()) {\n";
a2256 4
    // If the arg is fake, it's the user's job to supply it: general parsing
    // logic shouldn't need to know anything about it.
    if (Arg->getValueAsBit("Fake"))
      continue;
a2377 9
    case Func | Var | Class | ObjCInterface:
      return "(S.getLangOpts().CPlusPlus"
             "     ? ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2)"
             "            ? ExpectedFunctionVariableClassOrObjCInterface"
             "            : ExpectedFunctionVariableOrClass)"
             "     : ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2)"
             "            ? ExpectedFunctionVariableOrObjCInterface"
             "            : ExpectedVariableOrFunction))";

d2391 1
a2391 1
  const std::string &B = R->getName();
d2399 1
a2399 1
  std::string FnName = "is" + Subject.getName().str();
d2448 1
a2448 1
  std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
d2506 1
a2506 2
    if ((*I)->getValueAsBit("Negated")) {
      FnName += "Not";
a2507 1
    }
d2569 1
a2569 1
        std::move(DA.begin(), DA.end(), std::back_inserter(Arches));
d2617 1
a2617 1
  std::string Name = Attr.getName().str() + "AttrSpellingMap";
d2631 6
a2636 3
  return llvm::any_of(
      GetFlattenedSpellings(Attr),
      [](const FlattenedSpelling &S) { return S.knownToGCC(); });
a2673 1
    SS << ", " << I->second->isSubClassOf("StmtAttr");
d2697 1
a2697 2
  std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
      Keywords, Pragma;
d2727 1
a2727 1
        const std::string &RawSpelling = S.name();
d2729 1
a2729 2
        std::string Spelling;
        const std::string &Variety = S.variety();
a2737 2
        else if (Variety == "Microsoft")
          Matches = &Microsoft;
d2745 1
a2745 5
        if (Variety == "GNU")
          Spelling += NormalizeGNUAttrSpelling(RawSpelling);
        else
          Spelling += RawSpelling;

a2761 2
  OS << "  } else if (AttributeList::AS_Microsoft == Syntax) {\n";
  StringMatcher("Name", Microsoft, OS).Emit();
d2778 5
a2782 1
  OS << "  switch (A->getKind()) {\n";
d2849 2
a2850 3
  Microsoft = 1 << 3,
  Keyword = 1 << 4,
  Pragma = 1 << 5
a2897 1
                            .Case("Microsoft", Microsoft)
@


1.1.1.10
log
@Import Clang pre-4.0.0 r291444.
@
text
@a13 3
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/iterator_range.h"
d16 1
a17 1
#include "llvm/ADT/StringRef.h"
a18 2
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
a23 1
#include <cassert>
a24 3
#include <cstddef>
#include <cstdint>
#include <map>
a27 3
#include <string>
#include <utility>
#include <vector>
a31 1

a56 1

d84 1
a84 1
    .Case("StringRef", "ReadString(Record, Idx)")
a87 7
// Get a type that is suitable for storing an object of the specified type.
static StringRef getStorageType(StringRef type) {
  return StringSwitch<StringRef>(type)
    .Case("StringRef", "std::string")
    .Default(type);
}

d90 5
a94 3
  return "Record." + StringSwitch<std::string>(type)
    .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
    .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
d96 4
a99 3
    .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
    .Case("StringRef", "AddString(" + std::string(name) + ");\n")
    .Default("push_back(" + std::string(name) + ");\n");
d106 6
a111 2
  AttrName.consume_front("__");
  AttrName.consume_back("__");
d122 4
a125 3
// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
// removing "__" if it appears at the beginning and end of the attribute's name.
static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
a164 1

a178 5
      // Work around MinGW's macro definition of 'interface' to 'struct'. We
      // have an attribute argument called 'Interface', so only the lower case
      // name conflicts with the macro definition.
      if (lowerName == "interface")
        lowerName = "interface_";
d226 2
a227 1
        : Argument(Arg, Attr), type(std::move(T)) {}
a235 1

a238 1

a241 1

a244 1

a247 1

a250 1

a253 1

a257 1

a260 1

a264 1

d270 1
a270 7
        OS << "\";\n";
        if (isOptional())
          OS << "    if (get" << getUpperName() << "()) ";
        else
          OS << "    ";
        OS << "OS << get" << getUpperName() << "()->getName();\n";
        OS << "    OS << \"";
a276 1

d312 1
a312 6
         << " = ";
      if (getType() == "bool")
        OS << (Default != 0 ? "true" : "false");
      else
        OS << Default;
      OS << ";";
a339 1

a342 1

a345 1

d349 1
a349 1
         << ".data(), " << getLowerName() << "Length);\n";
a350 1

a355 1

a358 1

a361 1

a365 1

a369 1

a372 1

d374 1
a374 1
      OS << "    Record.AddString(SA->get" << getUpperName() << "());\n";
a375 1

a378 1

a409 1

a436 1

a442 1

a446 1

d454 1
a454 1
         << ");\n";
a455 1

a458 1

a461 1

a464 1

a467 1

a474 1

a477 1

a486 1

d490 1
a490 1
      OS << "      Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
d492 2
a493 2
      OS << "      Record.AddTypeSourceInfo(SA->get" << getUpperName()
         << "Type());\n";
a494 1

d503 2
a504 3

    void writeDump(raw_ostream &OS) const override {}

a511 1

d528 4
a531 7
        : Argument(Arg, Attr), Type(std::move(T)),
          ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
          RangeName(getLowerName()) {}

    const std::string &getType() const { return Type; }
    const std::string &getArgName() const { return ArgName; }
    const std::string &getArgSizeName() const { return ArgSizeName; }
a549 1

a552 1

a557 1

d560 1
a560 1
         << " + " << ArgSizeName << ", " << ArgName << ");\n";
a561 1

a566 1

a569 1

a573 1

a576 1

a580 1

d582 4
a585 4
      OS << "    unsigned " << getLowerName() << "Size = Record[Idx++];\n";
      OS << "    SmallVector<" << getType() << ", 4> "
         << getLowerName() << ";\n";
      OS << "    " << getLowerName() << ".reserve(" << getLowerName()
d587 2
a588 15

      // If we can't store the values in the current type (if it's something
      // like StringRef), store them in a different type and convert the
      // container afterwards.
      std::string StorageType = getStorageType(getType());
      std::string StorageName = getLowerName();
      if (StorageType != getType()) {
        StorageName += "Storage";
        OS << "    SmallVector<" << StorageType << ", 4> "
           << StorageName << ";\n";
        OS << "    " << StorageName << ".reserve(" << getLowerName()
           << "Size);\n";
      }

      OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
d590 1
a590 7
      OS << "      " << StorageName << ".push_back(" << read << ");\n";

      if (StorageType != getType()) {
        OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
        OS << "      " << getLowerName() << ".push_back("
           << StorageName << "[i]);\n";
      }
a591 1

a594 1

a599 1

a609 1

d620 1
a620 1
    SmallDenseSet<StringRef, 8> unique_set;
d622 2
a623 1
      if (unique_set.insert(i).second)
d625 2
a651 1

a654 1

a680 1

a685 1

a688 1

a691 1

a698 1

d731 1
a731 1
      SmallDenseSet<StringRef, 8> Uniques;
a786 1

a799 1

a809 1

a816 1

d835 1
a835 1
      SmallDenseSet<StringRef, 8> Uniques;
a861 1

a864 1

a867 1

a870 1

a873 1

a876 1

a879 1

a883 1

a886 1

d888 1
a888 1
      OS << "    Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
a889 1

a892 1

a930 1

d996 1
a996 1
      : VariadicArgument(Arg, Attr, "StringRef")
a997 13

    void writeCtorBody(raw_ostream &OS) const override {
      OS << "    for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
            "         ++I) {\n"
            "      StringRef Ref = " << getUpperName() << "[I];\n"
            "      if (!Ref.empty()) {\n"
            "        char *Mem = new (Ctx, 1) char[Ref.size()];\n"
            "        std::memcpy(Mem, Ref.data(), Ref.size());\n"
            "        " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
            "      }\n"
            "    }\n";
    }

a1016 1

a1019 1

a1024 1

d1075 3
a1077 3
    ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
    for (const auto &Base : llvm::reverse(Bases)) {
      if ((Ptr = createArgument(Arg, Attr, Base.first)))
a1092 1
     << "  if (getStrict()) OS << \", strict\";\n"
a1099 9
static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
  OS << "\\\"\" << getMessage() << \"\\\"\";\n";
  // Only GNU deprecated has an optional fixit argument at the second position.
  if (Variety == "GNU")
     OS << "    if (!getReplacement().empty()) OS << \", \\\"\""
           " << getReplacement() << \"\\\"\";\n";
  OS << "    OS << \"";
}

a1165 3
    } else if (Variety == "Microsoft") {
      Prefix = "[";
      Suffix = "]";
d1198 5
a1202 2
    bool hasNonFakeArgs = llvm::any_of(
        Args, [](const std::unique_ptr<Argument> &A) { return !A->isFake(); });
a1212 2
    } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
        writeDeprecatedAttrValue(OS, Variety);
a1259 6
  if (Accessors.empty())
    return;

  const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
  assert(!SpellingList.empty() &&
         "Attribute with empty spelling list can't have accessors!");
d1262 5
a1266 1
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
d1271 1
a1271 1
      if (Index != Spellings.size() - 1)
d1306 4
a1309 4
    const std::string &Variety = S.variety();
    const std::string &Spelling = S.name();
    const std::string &Namespace = S.nameSpace();
    std::string EnumName;
a1372 10
template <typename Fn>
static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  SmallDenseSet<StringRef, 8> Seen;
  for (const FlattenedSpelling &S : Spellings) {
    if (Seen.insert(S.name()).second)
      F(S);
  }
}

d1384 1
a1384 1
    if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
d1388 6
a1393 3
    forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
    });
d1410 6
a1415 3
    forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
    });
d1422 1
a1422 1
    llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
d1441 6
a1446 3
    forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
    });
d1479 1
a1479 1
    ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
d1482 4
a1485 4
    for (const auto &Super : llvm::reverse(Supers)) {
      const Record *R = Super.first;
      if (R->getName() != "TargetSpecificAttr" && SuperName.empty())
        SuperName = R->getName();
d1509 1
a1509 1
    OS << "public:\n";
d1579 2
a1580 2
         << ( R.getValueAsBit("LateParsed") ? "true" : "false" ) << ", "
         << ( R.getValueAsBit("DuplicatesAllowedWhileMerging") ? "true" : "false" ) << ")\n";
d1597 1
d1600 1
d1708 2
d1728 1
a1728 1
static void emitAttrList(raw_ostream &OS, StringRef Class,
d1730 12
a1741 2
  for (auto Cur : AttrList) {
    OS << Class << "(" << Cur->getName() << ")\n";
d1748 2
a1749 1
  return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
d1754 4
a1757 1
namespace {
d1759 3
a1761 4
  struct AttrClassDescriptor {
    const char * const MacroName;
    const char * const TableGenName;
  };
d1763 3
a1765 1
} // end anonymous namespace
d1767 3
a1769 7
static const AttrClassDescriptor AttrClassDescriptors[] = {
  { "ATTR", "Attr" },
  { "STMT_ATTR", "StmtAttr" },
  { "INHERITABLE_ATTR", "InheritableAttr" },
  { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
  { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
};
d1771 3
a1773 7
static void emitDefaultDefine(raw_ostream &OS, StringRef name,
                              const char *superName) {
  OS << "#ifndef " << name << "\n";
  OS << "#define " << name << "(NAME) ";
  if (superName) OS << superName << "(NAME)";
  OS << "\n#endif\n\n";
}
d1775 4
a1778 1
namespace {
d1780 3
a1782 7
  /// A class of attributes.
  struct AttrClass {
    const AttrClassDescriptor &Descriptor;
    Record *TheRecord;
    AttrClass *SuperClass = nullptr;
    std::vector<AttrClass*> SubClasses;
    std::vector<Record*> Attrs;
d1784 3
a1786 2
    AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
      : Descriptor(Descriptor), TheRecord(R) {}
d1788 4
a1791 154
    void emitDefaultDefines(raw_ostream &OS) const {
      // Default the macro unless this is a root class (i.e. Attr).
      if (SuperClass) {
        emitDefaultDefine(OS, Descriptor.MacroName,
                          SuperClass->Descriptor.MacroName);
      }
    }

    void emitUndefs(raw_ostream &OS) const {
      OS << "#undef " << Descriptor.MacroName << "\n";
    }

    void emitAttrList(raw_ostream &OS) const {
      for (auto SubClass : SubClasses) {
        SubClass->emitAttrList(OS);
      }

      ::emitAttrList(OS, Descriptor.MacroName, Attrs);
    }

    void classifyAttrOnRoot(Record *Attr) {
      bool result = classifyAttr(Attr);
      assert(result && "failed to classify on root"); (void) result;
    }

    void emitAttrRange(raw_ostream &OS) const {
      OS << "ATTR_RANGE(" << Descriptor.TableGenName
         << ", " << getFirstAttr()->getName()
         << ", " << getLastAttr()->getName() << ")\n";
    }

  private:
    bool classifyAttr(Record *Attr) {
      // Check all the subclasses.
      for (auto SubClass : SubClasses) {
        if (SubClass->classifyAttr(Attr))
          return true;
      }

      // It's not more specific than this class, but it might still belong here.
      if (Attr->isSubClassOf(TheRecord)) {
        Attrs.push_back(Attr);
        return true;
      }

      return false;
    }

    Record *getFirstAttr() const {
      if (!SubClasses.empty())
        return SubClasses.front()->getFirstAttr();
      return Attrs.front();
    }

    Record *getLastAttr() const {
      if (!Attrs.empty())
        return Attrs.back();
      return SubClasses.back()->getLastAttr();
    }
  };

  /// The entire hierarchy of attribute classes.
  class AttrClassHierarchy {
    std::vector<std::unique_ptr<AttrClass>> Classes;

  public:
    AttrClassHierarchy(RecordKeeper &Records) {
      // Find records for all the classes.
      for (auto &Descriptor : AttrClassDescriptors) {
        Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
        AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
        Classes.emplace_back(Class);
      }

      // Link up the hierarchy.
      for (auto &Class : Classes) {
        if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
          Class->SuperClass = SuperClass;
          SuperClass->SubClasses.push_back(Class.get());
        }
      }

#ifndef NDEBUG
      for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
        assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
               "only the first class should be a root class!");
      }
#endif
    }

    void emitDefaultDefines(raw_ostream &OS) const {
      for (auto &Class : Classes) {
        Class->emitDefaultDefines(OS);
      }
    }

    void emitUndefs(raw_ostream &OS) const {
      for (auto &Class : Classes) {
        Class->emitUndefs(OS);
      }
    }

    void emitAttrLists(raw_ostream &OS) const {
      // Just start from the root class.
      Classes[0]->emitAttrList(OS);
    }

    void emitAttrRanges(raw_ostream &OS) const {
      for (auto &Class : Classes)
        Class->emitAttrRange(OS);
    }

    void classifyAttr(Record *Attr) {
      // Add the attribute to the root class.
      Classes[0]->classifyAttrOnRoot(Attr);
    }

  private:
    AttrClass *findClassByRecord(Record *R) const {
      for (auto &Class : Classes) {
        if (Class->TheRecord == R)
          return Class.get();
      }
      return nullptr;
    }

    AttrClass *findSuperClass(Record *R) const {
      // TableGen flattens the superclass list, so we just need to walk it
      // in reverse.
      auto SuperClasses = R->getSuperClasses();
      for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
        auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
        if (SuperClass) return SuperClass;
      }
      return nullptr;
    }
  };

} // end anonymous namespace

namespace clang {

// Emits the enumeration list for attributes.
void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);

  AttrClassHierarchy Hierarchy(Records);

  // Add defaulting macro definitions.
  Hierarchy.emitDefaultDefines(OS);
  emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);

  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<Record *> PragmaAttrs;
a1795 1
    // Add the attribute to the ad-hoc groups.
d1799 6
a1804 2
    // Place it in the hierarchy.
    Hierarchy.classifyAttr(Attr);
d1807 10
a1816 13
  // Emit the main attribute list.
  Hierarchy.emitAttrLists(OS);

  // Emit the ad hoc groups.
  emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);

  // Emit the attribute ranges.
  OS << "#ifdef ATTR_RANGE\n";
  Hierarchy.emitAttrRanges(OS);
  OS << "#undef ATTR_RANGE\n";
  OS << "#endif\n";

  Hierarchy.emitUndefs(OS);
d1818 1
d1831 2
d1872 3
d2013 1
a2013 1
  std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
d2021 1
a2021 1
      const std::string &Variety = SI.variety();
a2025 2
      else if (Variety == "Microsoft")
        Microsoft.push_back(R);
a2040 3
  OS << "case AttrSyntax::Microsoft:\n";
  OS << "  return llvm::StringSwitch<int>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
d2065 5
a2069 1
  OS << "  switch (AttrKind) {\n";
d2083 2
a2084 3
                .Case("Microsoft", 3)
                .Case("Keyword", 4)
                .Case("Pragma", 5)
d2149 3
a2151 1
     << "  switch (A->getKind()) {\n";
d2162 1
a2162 2
  OS << "  }\n";  // end switch
  OS << "  llvm_unreachable(\"bad attribute kind\");\n";
d2178 3
a2180 1
     << "  switch (At->getKind()) {\n";
a2256 4
    // If the arg is fake, it's the user's job to supply it: general parsing
    // logic shouldn't need to know anything about it.
    if (Arg->getValueAsBit("Fake"))
      continue;
a2377 9
    case Func | Var | Class | ObjCInterface:
      return "(S.getLangOpts().CPlusPlus"
             "     ? ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2)"
             "            ? ExpectedFunctionVariableClassOrObjCInterface"
             "            : ExpectedFunctionVariableOrClass)"
             "     : ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2)"
             "            ? ExpectedFunctionVariableOrObjCInterface"
             "            : ExpectedVariableOrFunction))";

d2391 1
a2391 1
  const std::string &B = R->getName();
d2399 1
a2399 1
  std::string FnName = "is" + Subject.getName().str();
d2448 1
a2448 1
  std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
d2506 1
a2506 2
    if ((*I)->getValueAsBit("Negated")) {
      FnName += "Not";
a2507 1
    }
d2569 1
a2569 1
        std::move(DA.begin(), DA.end(), std::back_inserter(Arches));
d2617 1
a2617 1
  std::string Name = Attr.getName().str() + "AttrSpellingMap";
d2631 6
a2636 3
  return llvm::any_of(
      GetFlattenedSpellings(Attr),
      [](const FlattenedSpelling &S) { return S.knownToGCC(); });
a2673 1
    SS << ", " << I->second->isSubClassOf("StmtAttr");
d2697 1
a2697 2
  std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
      Keywords, Pragma;
d2727 1
a2727 1
        const std::string &RawSpelling = S.name();
d2729 1
a2729 2
        std::string Spelling;
        const std::string &Variety = S.variety();
a2737 2
        else if (Variety == "Microsoft")
          Matches = &Microsoft;
d2745 1
a2745 5
        if (Variety == "GNU")
          Spelling += NormalizeGNUAttrSpelling(RawSpelling);
        else
          Spelling += RawSpelling;

a2761 2
  OS << "  } else if (AttributeList::AS_Microsoft == Syntax) {\n";
  StringMatcher("Name", Microsoft, OS).Emit();
d2778 5
a2782 1
  OS << "  switch (A->getKind()) {\n";
d2849 2
a2850 3
  Microsoft = 1 << 3,
  Keyword = 1 << 4,
  Pragma = 1 << 5
a2897 1
                            .Case("Microsoft", Microsoft)
@


1.1.1.11
log
@Import clang r309604 from branches/release_50
@
text
@a14 1
#include "llvm/ADT/DenseMap.h"
d16 2
a18 1
#include "llvm/ADT/SmallString.h"
a20 1
#include "llvm/ADT/StringSet.h"
a21 1
#include "llvm/ADT/iterator_range.h"
d93 7
a99 7
    .EndsWith("Decl *", "Record.GetLocalDeclAs<" 
              + std::string(type, 0, type.size()-1) + ">(Record.readInt())")
    .Case("TypeSourceInfo *", "Record.getTypeSourceInfo()")
    .Case("Expr *", "Record.readExpr()")
    .Case("IdentifierInfo *", "Record.getIdentifierInfo()")
    .Case("StringRef", "Record.readString()")
    .Default("Record.readInt()");
d313 1
a313 1
      if (type == "FunctionDecl *" || type == "NamedDecl *") {
d416 1
a416 1
         << "= Record.readString();\n";
d542 1
a542 1
      OS << "    bool is" << getLowerName() << "Expr = Record.readInt();\n";
d545 1
a545 1
      OS << "      " << getLowerName() << "Ptr = Record.readExpr();\n";
d548 1
a548 1
         << "Ptr = Record.getTypeSourceInfo();\n";
d661 1
a661 1
      OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
d719 3
a721 3
  std::vector<StringRef>
  uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
    std::vector<StringRef> uniques;
d732 1
a732 2
    std::vector<StringRef> values, enums, uniques;

d786 1
a786 1
         << ">(Record.readInt()));\n";
d851 1
a851 1
    std::vector<StringRef> values, enums, uniques;
d909 1
a909 1
      OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
d916 1
a916 1
         << QualifiedTypeName << ">(Record.readInt()));\n";
d999 1
a999 1
         << "= Record.readVersionTuple();\n";
d1039 1
a1039 1
         << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
d1086 1
a1086 1
         << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
a1181 2
  else if (ArgName == "NamedArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "NamedDecl *");
a1524 403
static bool hasGNUorCXX11Spelling(const Record &Attribute) {
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
  for (const auto &I : Spellings) {
    if (I.variety() == "GNU" || I.variety() == "CXX11")
      return true;
  }
  return false;
}

namespace {

struct AttributeSubjectMatchRule {
  const Record *MetaSubject;
  const Record *Constraint;

  AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
      : MetaSubject(MetaSubject), Constraint(Constraint) {
    assert(MetaSubject && "Missing subject");
  }

  bool isSubRule() const { return Constraint != nullptr; }

  std::vector<Record *> getSubjects() const {
    return (Constraint ? Constraint : MetaSubject)
        ->getValueAsListOfDefs("Subjects");
  }

  std::vector<Record *> getLangOpts() const {
    if (Constraint) {
      // Lookup the options in the sub-rule first, in case the sub-rule
      // overrides the rules options.
      std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
      if (!Opts.empty())
        return Opts;
    }
    return MetaSubject->getValueAsListOfDefs("LangOpts");
  }

  // Abstract rules are used only for sub-rules
  bool isAbstractRule() const { return getSubjects().empty(); }

  std::string getName() const {
    return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
  }

  bool isNegatedSubRule() const {
    assert(isSubRule() && "Not a sub-rule");
    return Constraint->getValueAsBit("Negated");
  }

  std::string getSpelling() const {
    std::string Result = MetaSubject->getValueAsString("Name");
    if (isSubRule()) {
      Result += '(';
      if (isNegatedSubRule())
        Result += "unless(";
      Result += getName();
      if (isNegatedSubRule())
        Result += ')';
      Result += ')';
    }
    return Result;
  }

  std::string getEnumValueName() const {
    SmallString<128> Result;
    Result += "SubjectMatchRule_";
    Result += MetaSubject->getValueAsString("Name");
    if (isSubRule()) {
      Result += "_";
      if (isNegatedSubRule())
        Result += "not_";
      Result += Constraint->getValueAsString("Name");
    }
    if (isAbstractRule())
      Result += "_abstract";
    return Result.str();
  }

  std::string getEnumValue() const { return "attr::" + getEnumValueName(); }

  static const char *EnumName;
};

const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";

struct PragmaClangAttributeSupport {
  std::vector<AttributeSubjectMatchRule> Rules;

  class RuleOrAggregateRuleSet {
    std::vector<AttributeSubjectMatchRule> Rules;
    bool IsRule;
    RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
                           bool IsRule)
        : Rules(Rules), IsRule(IsRule) {}

  public:
    bool isRule() const { return IsRule; }

    const AttributeSubjectMatchRule &getRule() const {
      assert(IsRule && "not a rule!");
      return Rules[0];
    }

    ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
      return Rules;
    }

    static RuleOrAggregateRuleSet
    getRule(const AttributeSubjectMatchRule &Rule) {
      return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
    }
    static RuleOrAggregateRuleSet
    getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
      return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
    }
  };
  llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;

  PragmaClangAttributeSupport(RecordKeeper &Records);

  bool isAttributedSupported(const Record &Attribute);

  void emitMatchRuleList(raw_ostream &OS);

  std::string generateStrictConformsTo(const Record &Attr, raw_ostream &OS);

  void generateParsingHelpers(raw_ostream &OS);
};

} // end anonymous namespace

static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
  const Record *CurrentBase = D->getValueAsDef("Base");
  if (!CurrentBase)
    return false;
  if (CurrentBase == Base)
    return true;
  return doesDeclDeriveFrom(CurrentBase, Base);
}

PragmaClangAttributeSupport::PragmaClangAttributeSupport(
    RecordKeeper &Records) {
  std::vector<Record *> MetaSubjects =
      Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
  auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
                                       const Record *MetaSubject,
                                       const Record *Constraint) {
    Rules.emplace_back(MetaSubject, Constraint);
    std::vector<Record *> ApplicableSubjects =
        SubjectContainer->getValueAsListOfDefs("Subjects");
    for (const auto *Subject : ApplicableSubjects) {
      bool Inserted =
          SubjectsToRules
              .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
                                        AttributeSubjectMatchRule(MetaSubject,
                                                                  Constraint)))
              .second;
      if (!Inserted) {
        PrintFatalError("Attribute subject match rules should not represent"
                        "same attribute subjects.");
      }
    }
  };
  for (const auto *MetaSubject : MetaSubjects) {
    MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
    std::vector<Record *> Constraints =
        MetaSubject->getValueAsListOfDefs("Constraints");
    for (const auto *Constraint : Constraints)
      MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
  }

  std::vector<Record *> Aggregates =
      Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
  std::vector<Record *> DeclNodes = Records.getAllDerivedDefinitions("DDecl");
  for (const auto *Aggregate : Aggregates) {
    Record *SubjectDecl = Aggregate->getValueAsDef("Subject");

    // Gather sub-classes of the aggregate subject that act as attribute
    // subject rules.
    std::vector<AttributeSubjectMatchRule> Rules;
    for (const auto *D : DeclNodes) {
      if (doesDeclDeriveFrom(D, SubjectDecl)) {
        auto It = SubjectsToRules.find(D);
        if (It == SubjectsToRules.end())
          continue;
        if (!It->second.isRule() || It->second.getRule().isSubRule())
          continue; // Assume that the rule will be included as well.
        Rules.push_back(It->second.getRule());
      }
    }

    bool Inserted =
        SubjectsToRules
            .try_emplace(SubjectDecl,
                         RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
            .second;
    if (!Inserted) {
      PrintFatalError("Attribute subject match rules should not represent"
                      "same attribute subjects.");
    }
  }
}

static PragmaClangAttributeSupport &
getPragmaAttributeSupport(RecordKeeper &Records) {
  static PragmaClangAttributeSupport Instance(Records);
  return Instance;
}

void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
  OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
  OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
        "IsNegated) "
     << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
  OS << "#endif\n";
  for (const auto &Rule : Rules) {
    OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
    OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
       << Rule.isAbstractRule();
    if (Rule.isSubRule())
      OS << ", "
         << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
         << ", " << Rule.isNegatedSubRule();
    OS << ")\n";
  }
  OS << "#undef ATTR_MATCH_SUB_RULE\n";
}

bool PragmaClangAttributeSupport::isAttributedSupported(
    const Record &Attribute) {
  if (Attribute.getValueAsBit("ForcePragmaAttributeSupport"))
    return true;
  // Opt-out rules:
  // FIXME: The documentation check should be moved before
  // the ForcePragmaAttributeSupport check after annotate is documented.
  // No documentation present.
  if (Attribute.isValueUnset("Documentation"))
    return false;
  std::vector<Record *> Docs = Attribute.getValueAsListOfDefs("Documentation");
  if (Docs.empty())
    return false;
  if (Docs.size() == 1 && Docs[0]->getName() == "Undocumented")
    return false;
  // An attribute requires delayed parsing (LateParsed is on)
  if (Attribute.getValueAsBit("LateParsed"))
    return false;
  // An attribute has no GNU/CXX11 spelling
  if (!hasGNUorCXX11Spelling(Attribute))
    return false;
  // An attribute subject list has a subject that isn't covered by one of the
  // subject match rules or has no subjects at all.
  if (Attribute.isValueUnset("Subjects"))
    return false;
  const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
  std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
  if (Subjects.empty())
    return false;
  for (const auto *Subject : Subjects) {
    if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
      return false;
  }
  return true;
}

std::string
PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
                                                      raw_ostream &OS) {
  if (!isAttributedSupported(Attr))
    return "nullptr";
  // Generate a function that constructs a set of matching rules that describe
  // to which declarations the attribute should apply to.
  std::string FnName = "matchRulesFor" + Attr.getName().str();
  std::stringstream SS;
  SS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
     << AttributeSubjectMatchRule::EnumName
     << ", bool>> &MatchRules, const LangOptions &LangOpts) {\n";
  if (Attr.isValueUnset("Subjects")) {
    SS << "}\n\n";
    OS << SS.str();
    return FnName;
  }
  const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
  for (const auto *Subject : Subjects) {
    auto It = SubjectsToRules.find(Subject);
    assert(It != SubjectsToRules.end() &&
           "This attribute is unsupported by #pragma clang attribute");
    for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
      // The rule might be language specific, so only subtract it from the given
      // rules if the specific language options are specified.
      std::vector<Record *> LangOpts = Rule.getLangOpts();
      SS << "  MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
         << ", /*IsSupported=*/";
      if (!LangOpts.empty()) {
        for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
          std::string Part = (*I)->getValueAsString("Name");
          if ((*I)->getValueAsBit("Negated"))
            SS << "!";
          SS << "LangOpts." + Part;
          if (I + 1 != E)
            SS << " || ";
        }
      } else
        SS << "true";
      SS << "));\n";
    }
  }
  SS << "}\n\n";
  OS << SS.str();
  return FnName;
}

void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
  // Generate routines that check the names of sub-rules.
  OS << "Optional<attr::SubjectMatchRule> "
        "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
  OS << "  return None;\n";
  OS << "}\n\n";

  std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
      SubMatchRules;
  for (const auto &Rule : Rules) {
    if (!Rule.isSubRule())
      continue;
    SubMatchRules[Rule.MetaSubject].push_back(Rule);
  }

  for (const auto &SubMatchRule : SubMatchRules) {
    OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
       << SubMatchRule.first->getValueAsString("Name")
       << "(StringRef Name, bool IsUnless) {\n";
    OS << "  if (IsUnless)\n";
    OS << "    return "
          "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
    for (const auto &Rule : SubMatchRule.second) {
      if (Rule.isNegatedSubRule())
        OS << "    Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
           << ").\n";
    }
    OS << "    Default(None);\n";
    OS << "  return "
          "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
    for (const auto &Rule : SubMatchRule.second) {
      if (!Rule.isNegatedSubRule())
        OS << "  Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
           << ").\n";
    }
    OS << "  Default(None);\n";
    OS << "}\n\n";
  }

  // Generate the function that checks for the top-level rules.
  OS << "std::pair<Optional<attr::SubjectMatchRule>, "
        "Optional<attr::SubjectMatchRule> (*)(StringRef, "
        "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
  OS << "  return "
        "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
        "Optional<attr::SubjectMatchRule> (*) (StringRef, "
        "bool)>>(Name).\n";
  for (const auto &Rule : Rules) {
    if (Rule.isSubRule())
      continue;
    std::string SubRuleFunction;
    if (SubMatchRules.count(Rule.MetaSubject))
      SubRuleFunction = "isAttributeSubjectMatchSubRuleFor_" + Rule.getName();
    else
      SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
    OS << "  Case(\"" << Rule.getName() << "\", std::make_pair("
       << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
  }
  OS << "  Default(std::make_pair(None, "
        "defaultIsAttributeSubjectMatchSubRuleFor));\n";
  OS << "}\n\n";

  // Generate the function that checks for the submatch rules.
  OS << "const char *validAttributeSubjectMatchSubRules("
     << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
  OS << "  switch (Rule) {\n";
  for (const auto &SubMatchRule : SubMatchRules) {
    OS << "  case "
       << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
       << ":\n";
    OS << "  return \"'";
    bool IsFirst = true;
    for (const auto &Rule : SubMatchRule.second) {
      if (!IsFirst)
        OS << ", '";
      IsFirst = false;
      if (Rule.isNegatedSubRule())
        OS << "unless(";
      OS << Rule.getName();
      if (Rule.isNegatedSubRule())
        OS << ')';
      OS << "'";
    }
    OS << "\";\n";
  }
  OS << "  default: return nullptr;\n";
  OS << "  }\n";
  OS << "}\n\n";
}

a2111 11
// Emits the enumeration list for attributes.
void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader(
      "List of all attribute subject matching rules that Clang recognizes", OS);
  PragmaClangAttributeSupport &PragmaAttributeSupport =
      getPragmaAttributeSupport(Records);
  emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
  PragmaAttributeSupport.emitMatchRuleList(OS);
  OS << "#undef ATTR_MATCH_RULE\n";
}

d2129 3
a2131 3
      OS << "    bool isInherited = Record.readInt();\n";
    OS << "    bool isImplicit = Record.readInt();\n";
    OS << "    unsigned Spelling = Record.readInt();\n";
d2189 1
a2189 1
                                             std::vector<StringRef> &Arches,
d2199 2
a2200 3
    StringRef Part = *I;
    Test += "T.getArch() == llvm::Triple::";
    Test += Part;
d2213 1
a2213 1
    std::vector<StringRef> OSes = R->getValueAsListOfStrings("OSes");
d2215 1
a2215 1
      StringRef Part = *I;
d2217 1
a2217 2
      Test += "T.getOS() == llvm::Triple::";
      Test += Part;
d2229 1
a2229 1
    std::vector<StringRef> CXXABIs = R->getValueAsListOfStrings("CXXABIs");
d2231 2
a2232 3
      StringRef Part = *I;
      Test += "Target.getCXXABI().getKind() == TargetCXXABI::";
      Test += Part;
d2270 1
a2270 1
      std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
d2454 12
a2465 3
void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
                                            raw_ostream &OS,
                                            bool AppliesToDecl) {
a2466 1
  OS << "  switch (At->getKind()) {\n";
d2471 1
d2473 1
a2473 3
    bool ShouldClone = R.getValueAsBit("Clone") &&
                       (!AppliesToDecl ||
                        R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
d2510 2
a2511 21
     << "  return nullptr;\n";
}

// Emits code to instantiate dependent attributes on templates.
void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Template instantiation code for attributes", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  OS << "namespace clang {\n"
     << "namespace sema {\n\n"
     << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
     << "Sema &S,\n"
     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
  EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
  OS << "}\n\n"
     << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
     << " ASTContext &C, Sema &S,\n"
     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
  EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
  OS << "}\n\n"
d2587 1
a2587 2
    Enum = 1U << 15,
    Named = 1U << 16,
a2621 1
                   .Case("Named", Named)
a2676 2
    case Func | ObjCMethod | ObjCProp:
      return "ExpectedFunctionOrMethodOrProperty";
a2679 3

    case Named:
      return "ExpectedNamedDecl";
a2694 4
static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
  return "is" + Subject.getName().str();
}

d2697 1
a2697 1
  std::string FnName = functionNameForCustomAppertainsTo(Subject);
a2781 36
static void
emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
                        raw_ostream &OS) {
  OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
     << AttributeSubjectMatchRule::EnumName << " rule) {\n";
  OS << "  switch (rule) {\n";
  for (const auto &Rule : PragmaAttributeSupport.Rules) {
    if (Rule.isAbstractRule()) {
      OS << "  case " << Rule.getEnumValue() << ":\n";
      OS << "    assert(false && \"Abstract matcher rule isn't allowed\");\n";
      OS << "    return false;\n";
      continue;
    }
    std::vector<Record *> Subjects = Rule.getSubjects();
    assert(!Subjects.empty() && "Missing subjects");
    OS << "  case " << Rule.getEnumValue() << ":\n";
    OS << "    return ";
    for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
      // If the subject has custom code associated with it, use the function
      // that was generated for GenerateAppertainsTo to check if the declaration
      // is valid.
      if ((*I)->isSubClassOf("SubsetSubject"))
        OS << functionNameForCustomAppertainsTo(**I) << "(D)";
      else
        OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";

      if (I + 1 != E)
        OS << " || ";
    }
    OS << ";\n";
  }
  OS << "  }\n";
  OS << "  llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
  OS << "}\n\n";
}

d2850 1
a2850 1
  std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
d2867 3
a2869 4
        std::vector<StringRef> DA =
            I.second->getValueAsDef("Target")->getValueAsListOfStrings(
                "Arches");
        Arches.insert(Arches.end(), DA.begin(), DA.end());
a2939 3
  PragmaClangAttributeSupport &PragmaAttributeSupport =
      getPragmaAttributeSupport(Records);

a2972 1
    SS << ", " << PragmaAttributeSupport.isAttributedSupported(*I->second);
a2976 2
    SS << ", "
       << PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
a2987 3

  // Generate the attribute match rules.
  emitAttributeMatchRules(PragmaAttributeSupport, OS);
a3126 5
void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
                                                        raw_ostream &OS) {
  getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
}

d3158 2
a3159 2
static void WriteDocumentation(RecordKeeper &Records,
                               const DocumentationData &Doc, raw_ostream &OS) {
d3241 1
a3241 1
  OS << " \"Pragma\", \"Pragma clang attribute\"\n\n";
a3251 3
  OS << "\", \"";
  if (getPragmaAttributeSupport(Records).isAttributedSupported(*Doc.Attribute))
    OS << "X";
d3318 1
a3318 44
      WriteDocumentation(Records, Doc, OS);
  }
}

void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
                                                raw_ostream &OS) {
  PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
  ParsedAttrMap Attrs = getParsedAttrList(Records);
  unsigned NumAttrs = 0;
  for (const auto &I : Attrs) {
    if (Support.isAttributedSupported(*I.second))
      ++NumAttrs;
  }
  OS << "#pragma clang attribute supports " << NumAttrs << " attributes:\n";
  for (const auto &I : Attrs) {
    if (!Support.isAttributedSupported(*I.second))
      continue;
    OS << I.first;
    if (I.second->isValueUnset("Subjects")) {
      OS << " ()\n";
      continue;
    }
    const Record *SubjectObj = I.second->getValueAsDef("Subjects");
    std::vector<Record *> Subjects =
        SubjectObj->getValueAsListOfDefs("Subjects");
    OS << " (";
    for (const auto &Subject : llvm::enumerate(Subjects)) {
      if (Subject.index())
        OS << ", ";
      PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
          Support.SubjectsToRules.find(Subject.value())->getSecond();
      if (RuleSet.isRule()) {
        OS << RuleSet.getRule().getEnumValueName();
        continue;
      }
      OS << "(";
      for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
        if (Rule.index())
          OS << ", ";
        OS << Rule.value().getEnumValueName();
      }
      OS << ")";
    }
    OS << ")\n";
@


1.1.1.11.4.1
log
@Sync with HEAD
@
text
@d59 3
a61 3
    assert(V != "GCC" && V != "Clang" &&
           "Given a GCC spelling, which means this hasn't been flattened!");
    if (V == "CXX11" || V == "C2x" || V == "Pragma")
d81 1
a81 3
    StringRef Variety = Spelling->getValueAsString("Variety");
    StringRef Name = Spelling->getValueAsString("Name");
    if (Variety == "GCC") {
d83 3
a85 7
      Ret.emplace_back("GNU", Name, "", true);
      Ret.emplace_back("CXX11", Name, "gnu", true);
    } else if (Variety == "Clang") {
      Ret.emplace_back("GNU", Name, "", false);
      Ret.emplace_back("CXX11", Name, "clang", false);
      if (Spelling->getValueAsBit("AllowInC"))
        Ret.emplace_back("C2x", Name, "clang", false);
a100 1
    .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
a118 1
    .Case("ParamIdx", "push_back(" + std::string(name) + ".serialize());\n")
a227 1
    virtual std::string getIsOmitted() const { return "false"; }
a294 8
    std::string getIsOmitted() const override {
      if (type == "IdentifierInfo *")
        return "!get" + getUpperName().str() + "()";
      if (type == "ParamIdx")
        return "!get" + getUpperName().str() + "().isValid()";
      return "false";
    }

d296 1
a296 1
      if (type == "FunctionDecl *")
d299 9
a307 6
      else if (type == "IdentifierInfo *")
        // Some non-optional (comma required) identifier arguments can be the
        // empty string but are then recorded as a nullptr.
        OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
           << "()->getName() : \"\") << \"";
      else if (type == "TypeSourceInfo *")
d309 1
a309 3
      else if (type == "ParamIdx")
        OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
      else
d311 1
d319 3
a321 4
        // Some non-optional (comma required) identifier arguments can be the
        // empty string but are then recorded as a nullptr.
        OS << "    if (SA->get" << getUpperName() << "())\n"
           << "      OS << \" \" << SA->get" << getUpperName()
a330 5
      } else if (type == "ParamIdx") {
        if (isOptional())
          OS << "    if (SA->get" << getUpperName() << "().isValid())\n  ";
        OS << "    OS << \" \" << SA->get" << getUpperName()
           << "().getSourceIndex();\n";
a492 11
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      StringRef Name = getUpperName();
      OS << "  if (A->is" << Name << "Expr()) {\n"
         << "    if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n" 
         << "      return false;\n" 
         << "  } else if (auto *TSI = A->get" << Name << "Type()) {\n"
         << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
         << "      return false;\n" 
         << "  }\n";
    }

a561 5
    std::string getIsOmitted() const override {
      return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
             + "Expr";
    }

d564 4
a567 2
      OS << "    " << getLowerName()
         << "Expr->printPretty(OS, nullptr, Policy);\n";
a593 4
    // Assumed to receive a parameter: raw_ostream OS.
    virtual void writeDumpImpl(raw_ostream &OS) const {
      OS << "      OS << \" \" << Val;\n";
    }
a632 4
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      // FIXME: Traverse the elements.
    }

d716 1
a716 16
      writeDumpImpl(OS);
    }
  };

  class VariadicParamIdxArgument : public VariadicArgument {
  public:
    VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
        : VariadicArgument(Arg, Attr, "ParamIdx") {}

  public:
    void writeValueImpl(raw_ostream &OS) const override {
      OS << "    OS << Val.getSourceIndex();\n";
    }

    void writeDumpImpl(raw_ostream &OS) const override {
      OS << "      OS << \" \" << Val.getSourceIndex();\n";
a1155 6
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      OS << "  if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
      OS << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
      OS << "      return false;\n";
    }

a1212 4
  else if (ArgName == "VariadicParamIdxArgument")
    Ptr = llvm::make_unique<VariadicParamIdxArgument>(Arg, Attr);
  else if (ArgName == "ParamIdxArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
d1308 1
a1308 1
    } else if (Variety == "CXX11" || Variety == "C2x") {
d1344 1
a1344 1
      OS << "\";\n";
d1352 12
a1364 1
      OS << "(";
a1365 1
      OS << ")";
d1367 1
a1367 3
      OS << "(";
      writeDeprecatedAttrValue(OS, Variety);
      OS << ")";
d1369 1
a1369 34
      // To avoid printing parentheses around an empty argument list or
      // printing spurious commas at the end of an argument list, we need to
      // determine where the last provided non-fake argument is.
      unsigned NonFakeArgs = 0;
      unsigned TrailingOptArgs = 0;
      bool FoundNonOptArg = false;
      for (const auto &arg : llvm::reverse(Args)) {
        if (arg->isFake())
          continue;
        ++NonFakeArgs;
        if (FoundNonOptArg)
          continue;
        // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
        // any way to detect whether the argument was omitted.
        if (!arg->isOptional() || arg->getIsOmitted() == "false") {
          FoundNonOptArg = true;
          continue;
        }
        if (!TrailingOptArgs++)
          OS << "\";\n"
             << "    unsigned TrailingOmittedArgs = 0;\n";
        OS << "    if (" << arg->getIsOmitted() << ")\n"
           << "      ++TrailingOmittedArgs;\n";
      }
      if (TrailingOptArgs)
        OS << "    OS << \"";
      if (TrailingOptArgs < NonFakeArgs)
        OS << "(";
      else if (TrailingOptArgs)
        OS << "\";\n"
           << "    if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
           << "       OS << \"(\";\n"
           << "    OS << \"";
      unsigned ArgIndex = 0;
d1371 2
a1372 17
        if (arg->isFake())
          continue;
        if (ArgIndex) {
          if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
            OS << "\";\n"
               << "    if (" << ArgIndex << " < " << NonFakeArgs
               << " - TrailingOmittedArgs)\n"
               << "      OS << \", \";\n"
               << "    OS << \"";
          else
            OS << ", ";
        }
        std::string IsOmitted = arg->getIsOmitted();
        if (arg->isOptional() && IsOmitted != "false")
          OS << "\";\n"
             << "    if (!(" << IsOmitted << ")) {\n"
             << "      OS << \"";
d1374 1
a1374 13
        if (arg->isOptional() && IsOmitted != "false")
          OS << "\";\n"
             << "    }\n"
             << "    OS << \"";
        ++ArgIndex;
      }
      if (TrailingOptArgs < NonFakeArgs)
        OS << ")";
      else if (TrailingOptArgs)
        OS << "\";\n"
           << "    if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
           << "       OS << \")\";\n"
           << "    OS << \"";
d1377 2
d1392 1
a1392 1
/// Return the index of a spelling in a spelling list.
d1422 1
a1422 1
    const StringRef Name = Accessor->getValueAsString("Name");
d1571 1
a1571 1
  StringRef getName() const {
d1803 2
a1804 1
  OS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
d1808 2
a1809 1
    OS << "}\n\n";
d1822 1
a1822 1
      OS << "  MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
d1826 1
a1826 1
          const StringRef Part = (*I)->getValueAsString("Name");
d1828 2
a1829 2
            OS << "!";
          OS << "LangOpts." << Part;
d1831 1
a1831 1
            OS << " || ";
d1834 2
a1835 2
        OS << "true";
      OS << "));\n";
d1838 2
a1839 1
  OS << "}\n\n";
d1895 1
a1895 2
      SubRuleFunction =
          ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
d1943 1
a1943 1
/// Emits the first-argument-is-type property for attributes.
d1965 1
a1965 1
/// Emits the parse-arguments-in-unevaluated-context property for
a2042 1
    bool Inheritable = false;
d2045 1
a2045 2
      if (R->getName() != "TargetSpecificAttr" &&
          R->getName() != "DeclOrTypeAttr" && SuperName.empty())
a2046 2
      if (R->getName() == "InheritableAttr")
        Inheritable = true;
d2140 2
a2141 7
         << ( R.getValueAsBit("LateParsed") ? "true" : "false" );
      if (Inheritable) {
        OS << ", "
           << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
                                                              : "false");
      }
      OS << ")\n";
a2601 25
// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
// parameter with only a single check type, if applicable.
static void GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
                                            std::string *FnName,
                                            StringRef ListName,
                                            StringRef CheckAgainst,
                                            StringRef Scope) {
  if (!R->isValueUnset(ListName)) {
    Test += " && (";
    std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
    for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
      StringRef Part = *I;
      Test += CheckAgainst;
      Test += " == ";
      Test += Scope;
      Test += Part;
      if (I + 1 != E)
        Test += " || ";
      if (FnName)
        *FnName += Part;
    }
    Test += ")";
  }
}

d2615 17
a2631 5
  Test += "true";
  // If one or more architectures is specified, check those.  Arches are handled
  // differently because GenerateTargetRequirements needs to combine the list
  // with ParseKind.
  if (!Arches.empty()) {
d2633 2
a2634 1
    for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
d2636 2
a2637 1
      Test += "T.getArch() == llvm::Triple::";
a2646 4
  // If the attribute is specific to particular OSes, check those.
  GenerateTargetSpecificAttrCheck(R, Test, FnName, "OSes", "T.getOS()",
                                  "llvm::Triple::");

d2648 14
a2661 6
  GenerateTargetSpecificAttrCheck(R, Test, FnName, "CXXABIs",
                                  "Target.getCXXABI().getKind()",
                                  "TargetCXXABI::");
  // If one or more object formats is specified, check those.
  GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
                                  "T.getObjectFormat()", "llvm::Triple::");
a2697 2
      else if (Variety == "C2x")
        Test += " && LangOpts.DoubleSquareBracketAttributes";
a2701 2
    else if (Variety == "C2x")
      Test = "LangOpts.DoubleSquareBracketAttributes";
d2722 1
a2722 1
  std::map<std::string, std::vector<Record *>> CXX, C2x;
a2737 2
      else if (Variety == "C2x")
        C2x[SI.nameSpace()].push_back(R);
d2757 14
a2770 19
  auto fn = [&OS](const char *Spelling, const char *Variety,
                  const std::map<std::string, std::vector<Record *>> &List) {
    OS << "case AttrSyntax::" << Variety << ": {\n";
    // C++11-style attributes are further split out based on the Scope.
    for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
      if (I != List.cbegin())
        OS << " else ";
      if (I->first.empty())
        OS << "if (!Scope || Scope->getName() == \"\") {\n";
      else
        OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
      OS << "  return llvm::StringSwitch<int>(Name)\n";
      GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
      OS << "}";
    }
    OS << "\n} break;\n";
  };
  fn("CXX11", "CXX", CXX);
  fn("C2x", "C", C2x);
d2791 4
a2794 5
                .Case("C2x", 2)
                .Case("Declspec", 3)
                .Case("Microsoft", 4)
                .Case("Keyword", 5)
                .Case("Pragma", 6)
d2968 1
a2968 1
static void emitArgInfo(const Record &R, raw_ostream &OS) {
d2991 1
a2991 1
  OS << "static bool defaultAppertainsTo(Sema &, const ParsedAttr &,";
a2996 15
static std::string GetDiagnosticSpelling(const Record &R) {
  std::string Ret = R.getValueAsString("DiagSpelling");
  if (!Ret.empty())
    return Ret;

  // If we couldn't find the DiagSpelling in this object, we can check to see
  // if the object is one that has a base, and if it is, loop up to the Base
  // member recursively.
  std::string Super = R.getSuperClasses().back().first->getName();
  if (Super == "DDecl" || Super == "DStmt")
    return GetDiagnosticSpelling(*R.getValueAsDef("Base"));

  return "";
}

d3000 1
a3000 1
  const StringRef CustomDiag = S.getValueAsString("CustomDiag");
d3002 23
a3024 1
    return ("\"" + Twine(CustomDiag) + "\"").str();
a3025 1
  std::vector<std::string> DiagList;
d3029 92
a3120 15
    // Get the diagnostic text from the Decl or Stmt node given.
    std::string V = GetDiagnosticSpelling(R);
    if (V.empty()) {
      PrintError(R.getLoc(),
                 "Could not determine diagnostic spelling for the node: " +
                     R.getName() + "; please add one to DeclNodes.td");
    } else {
      // The node may contain a list of elements itself, so split the elements
      // by a comma, and trim any whitespace.
      SmallVector<StringRef, 2> Frags;
      llvm::SplitString(V, Frags, ",");
      for (auto Str : Frags) {
        DiagList.push_back(Str.trim());
      }
    }
d3123 2
a3124 5
  if (DiagList.empty()) {
    PrintFatalError(S.getLoc(),
                    "Could not deduce diagnostic argument for Attr subjects");
    return "";
  }
d3126 1
a3126 17
  // FIXME: this is not particularly good for localization purposes and ideally
  // should be part of the diagnostics engine itself with some sort of list
  // specifier.

  // A single member of the list can be returned directly.
  if (DiagList.size() == 1)
    return '"' + DiagList.front() + '"';

  if (DiagList.size() == 2)
    return '"' + DiagList[0] + " and " + DiagList[1] + '"';

  // If there are more than two in the list, we serialize the first N - 1
  // elements with a comma. This leaves the string in the state: foo, bar,
  // baz (but misses quux). We can then add ", and " for the last element
  // manually.
  std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
  return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
d3193 1
a3193 1
  SS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr, ";
d3213 2
a3214 2
  SS << (Warn ? "warn_attribute_wrong_decl_type_str" :
               "err_attribute_wrong_decl_type_str");
d3265 1
a3265 1
  OS << "const ParsedAttr &) {\n";
d3284 1
a3284 1
    const StringRef Part = (*I)->getValueAsString("Name");
d3289 1
a3289 2
    Test += "S.LangOpts.";
    Test +=  Part;
d3303 1
a3303 1
  OS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr) {\n";
d3332 5
d3341 1
a3341 1
  // attribute has only one ParsedAttr::Kind enumeration value, but it
d3345 1
a3345 1
    const StringRef APK = Attr.getValueAsString("ParseKind");
d3378 1
a3378 1
     << "const ParsedAttr &Attr) {\n";
d3401 1
a3401 1
  OS << "static unsigned " << Name << "(const ParsedAttr &Attr) {\n";
d3441 1
a3441 2
  std::string Buffer;
  raw_string_ostream SS {Buffer};
d3450 1
a3450 1
    // ParsedAttr.cpp.
d3455 1
a3455 3
    SS << ", "
       << (I->second->isSubClassOf("TypeAttr") ||
           I->second->isSubClassOf("DeclOrTypeAttr"));
d3473 1
a3473 2
  OS << "static const ParsedAttrInfo AttrInfoMap[ParsedAttr::UnknownAttribute "
        "+ 1] = {\n";
d3487 1
a3487 1
      Keywords, Pragma, C2x;
d3501 1
a3501 1
      // these to a single ParsedAttr::Kind value, but the StringMatcher
a3524 4
        } else if (Variety == "C2x") {
          Matches = &C2x;
          Spelling += S.nameSpace();
          Spelling += "::";
d3544 2
a3545 2
          Matches->push_back(StringMatcher::StringPair(
              Spelling, "return ParsedAttr::AT_" + AttrName + ";"));
d3547 2
a3548 2
          Matches->push_back(StringMatcher::StringPair(
              Spelling, "return ParsedAttr::IgnoredAttribute;"));
d3552 4
a3555 4

  OS << "static ParsedAttr::Kind getAttrKind(StringRef Name, ";
  OS << "ParsedAttr::Syntax Syntax) {\n";
  OS << "  if (ParsedAttr::AS_GNU == Syntax) {\n";
d3557 1
a3557 1
  OS << "  } else if (ParsedAttr::AS_Declspec == Syntax) {\n";
d3559 1
a3559 1
  OS << "  } else if (ParsedAttr::AS_Microsoft == Syntax) {\n";
d3561 1
a3561 1
  OS << "  } else if (ParsedAttr::AS_CXX11 == Syntax) {\n";
d3563 2
a3564 4
  OS << "  } else if (ParsedAttr::AS_C2x == Syntax) {\n";
  StringMatcher("Name", C2x, OS).Emit();
  OS << "  } else if (ParsedAttr::AS_Keyword == Syntax || ";
  OS << "ParsedAttr::AS_ContextSensitiveKeyword == Syntax) {\n";
d3566 1
a3566 1
  OS << "  } else if (ParsedAttr::AS_Pragma == Syntax) {\n";
d3569 1
a3569 1
  OS << "  return ParsedAttr::UnknownAttribute;\n"
a3626 2
  std::string Heading;
  unsigned SupportedSpellings;
d3628 2
a3629 5
  DocumentationData(const Record &Documentation, const Record &Attribute,
                    const std::pair<std::string, unsigned> HeadingAndKinds)
      : Documentation(&Documentation), Attribute(&Attribute),
        Heading(std::move(HeadingAndKinds.first)),
        SupportedSpellings(HeadingAndKinds.second) {}
d3634 2
a3635 2
  const StringRef Name = DocCategory->getValueAsString("Name");
  OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
d3638 1
a3638 1
  const StringRef ContentStr = DocCategory->getValueAsString("Content");
d3640 1
a3640 1
  OS << ContentStr.trim();
d3648 4
a3651 5
  C2x = 1 << 2,
  Declspec = 1 << 3,
  Microsoft = 1 << 4,
  Keyword = 1 << 5,
  Pragma = 1 << 6
d3654 2
a3655 3
static std::pair<std::string, unsigned>
GetAttributeHeadingAndSpellingKinds(const Record &Documentation,
                                    const Record &Attribute) {
d3660 1
a3660 1
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
d3663 1
a3663 1
  std::string Heading = Documentation.getValueAsString("Heading");
d3685 1
a3685 1
    PrintFatalError(Attribute.getLoc(),
a3697 1
                            .Case("C2x", C2x)
d3707 1
a3707 1
    if ((Kind == CXX11 || Kind == C2x) && !I.nameSpace().empty())
d3727 2
d3730 1
a3730 1
    PrintFatalError(Attribute.getLoc(),
a3732 6
  return std::make_pair(std::move(Heading), SupportedSpellings);
}

static void WriteDocumentation(RecordKeeper &Records,
                               const DocumentationData &Doc, raw_ostream &OS) {
  OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
d3736 1
a3736 1
  OS << "   :header: \"GNU\", \"C++11\", \"C2x\", \"__declspec\", \"Keyword\",";
d3739 1
a3739 1
  if (Doc.SupportedSpellings & GNU) OS << "X";
d3741 1
a3741 1
  if (Doc.SupportedSpellings & CXX11) OS << "X";
d3743 1
a3743 1
  if (Doc.SupportedSpellings & C2x) OS << "X";
d3745 1
a3745 3
  if (Doc.SupportedSpellings & Declspec) OS << "X";
  OS << "\",\"";
  if (Doc.SupportedSpellings & Keyword) OS << "X";
d3747 1
a3747 1
  if (Doc.SupportedSpellings & Pragma) OS << "X";
d3759 1
a3759 1
    const StringRef Replacement = Deprecated.getValueAsString("Replacement");
d3761 2
a3762 2
      OS << "  This attribute has been superseded by ``" << Replacement
         << "``.";
d3766 1
a3766 1
  const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
d3768 1
a3768 1
  OS << ContentStr.trim();
d3797 1
a3797 1
      const StringRef Cat = Category->getValueAsString("Name");
d3802 1
a3802 1
                        "documentation categories");
d3805 1
a3805 2
        SplitDocs[Category].push_back(DocumentationData(
            Doc, Attr, GetAttributeHeadingAndSpellingKinds(Doc, Attr)));
d3811 1
a3811 1
  for (auto &I : SplitDocs) {
a3813 5
    llvm::sort(I.second.begin(), I.second.end(),
               [](const DocumentationData &D1, const DocumentationData &D2) {
                 return D1.Heading < D2.Heading;
              });

@


1.1.1.11.4.2
log
@Mostly merge changes from HEAD upto 20200411
@
text
@@


1.1.1.11.2.1
log
@Sync with HEAD
@
text
@d59 3
a61 3
    assert(V != "GCC" && V != "Clang" &&
           "Given a GCC spelling, which means this hasn't been flattened!");
    if (V == "CXX11" || V == "C2x" || V == "Pragma")
d81 1
a81 3
    StringRef Variety = Spelling->getValueAsString("Variety");
    StringRef Name = Spelling->getValueAsString("Name");
    if (Variety == "GCC") {
d83 3
a85 7
      Ret.emplace_back("GNU", Name, "", true);
      Ret.emplace_back("CXX11", Name, "gnu", true);
    } else if (Variety == "Clang") {
      Ret.emplace_back("GNU", Name, "", false);
      Ret.emplace_back("CXX11", Name, "clang", false);
      if (Spelling->getValueAsBit("AllowInC"))
        Ret.emplace_back("C2x", Name, "clang", false);
a100 1
    .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
a118 1
    .Case("ParamIdx", "push_back(" + std::string(name) + ".serialize());\n")
a227 1
    virtual std::string getIsOmitted() const { return "false"; }
a294 8
    std::string getIsOmitted() const override {
      if (type == "IdentifierInfo *")
        return "!get" + getUpperName().str() + "()";
      if (type == "ParamIdx")
        return "!get" + getUpperName().str() + "().isValid()";
      return "false";
    }

d296 1
a296 1
      if (type == "FunctionDecl *")
d299 9
a307 6
      else if (type == "IdentifierInfo *")
        // Some non-optional (comma required) identifier arguments can be the
        // empty string but are then recorded as a nullptr.
        OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
           << "()->getName() : \"\") << \"";
      else if (type == "TypeSourceInfo *")
d309 1
a309 3
      else if (type == "ParamIdx")
        OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
      else
d311 1
d319 3
a321 4
        // Some non-optional (comma required) identifier arguments can be the
        // empty string but are then recorded as a nullptr.
        OS << "    if (SA->get" << getUpperName() << "())\n"
           << "      OS << \" \" << SA->get" << getUpperName()
a330 5
      } else if (type == "ParamIdx") {
        if (isOptional())
          OS << "    if (SA->get" << getUpperName() << "().isValid())\n  ";
        OS << "    OS << \" \" << SA->get" << getUpperName()
           << "().getSourceIndex();\n";
a492 11
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      StringRef Name = getUpperName();
      OS << "  if (A->is" << Name << "Expr()) {\n"
         << "    if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n" 
         << "      return false;\n" 
         << "  } else if (auto *TSI = A->get" << Name << "Type()) {\n"
         << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
         << "      return false;\n" 
         << "  }\n";
    }

a561 5
    std::string getIsOmitted() const override {
      return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
             + "Expr";
    }

d564 4
a567 2
      OS << "    " << getLowerName()
         << "Expr->printPretty(OS, nullptr, Policy);\n";
a593 4
    // Assumed to receive a parameter: raw_ostream OS.
    virtual void writeDumpImpl(raw_ostream &OS) const {
      OS << "      OS << \" \" << Val;\n";
    }
a632 4
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      // FIXME: Traverse the elements.
    }

d716 1
a716 16
      writeDumpImpl(OS);
    }
  };

  class VariadicParamIdxArgument : public VariadicArgument {
  public:
    VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
        : VariadicArgument(Arg, Attr, "ParamIdx") {}

  public:
    void writeValueImpl(raw_ostream &OS) const override {
      OS << "    OS << Val.getSourceIndex();\n";
    }

    void writeDumpImpl(raw_ostream &OS) const override {
      OS << "      OS << \" \" << Val.getSourceIndex();\n";
a1155 6
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      OS << "  if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
      OS << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
      OS << "      return false;\n";
    }

a1212 4
  else if (ArgName == "VariadicParamIdxArgument")
    Ptr = llvm::make_unique<VariadicParamIdxArgument>(Arg, Attr);
  else if (ArgName == "ParamIdxArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
d1308 1
a1308 1
    } else if (Variety == "CXX11" || Variety == "C2x") {
d1344 1
a1344 1
      OS << "\";\n";
d1352 12
a1364 1
      OS << "(";
a1365 1
      OS << ")";
d1367 1
a1367 3
      OS << "(";
      writeDeprecatedAttrValue(OS, Variety);
      OS << ")";
d1369 1
a1369 34
      // To avoid printing parentheses around an empty argument list or
      // printing spurious commas at the end of an argument list, we need to
      // determine where the last provided non-fake argument is.
      unsigned NonFakeArgs = 0;
      unsigned TrailingOptArgs = 0;
      bool FoundNonOptArg = false;
      for (const auto &arg : llvm::reverse(Args)) {
        if (arg->isFake())
          continue;
        ++NonFakeArgs;
        if (FoundNonOptArg)
          continue;
        // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
        // any way to detect whether the argument was omitted.
        if (!arg->isOptional() || arg->getIsOmitted() == "false") {
          FoundNonOptArg = true;
          continue;
        }
        if (!TrailingOptArgs++)
          OS << "\";\n"
             << "    unsigned TrailingOmittedArgs = 0;\n";
        OS << "    if (" << arg->getIsOmitted() << ")\n"
           << "      ++TrailingOmittedArgs;\n";
      }
      if (TrailingOptArgs)
        OS << "    OS << \"";
      if (TrailingOptArgs < NonFakeArgs)
        OS << "(";
      else if (TrailingOptArgs)
        OS << "\";\n"
           << "    if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
           << "       OS << \"(\";\n"
           << "    OS << \"";
      unsigned ArgIndex = 0;
d1371 2
a1372 17
        if (arg->isFake())
          continue;
        if (ArgIndex) {
          if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
            OS << "\";\n"
               << "    if (" << ArgIndex << " < " << NonFakeArgs
               << " - TrailingOmittedArgs)\n"
               << "      OS << \", \";\n"
               << "    OS << \"";
          else
            OS << ", ";
        }
        std::string IsOmitted = arg->getIsOmitted();
        if (arg->isOptional() && IsOmitted != "false")
          OS << "\";\n"
             << "    if (!(" << IsOmitted << ")) {\n"
             << "      OS << \"";
d1374 1
a1374 13
        if (arg->isOptional() && IsOmitted != "false")
          OS << "\";\n"
             << "    }\n"
             << "    OS << \"";
        ++ArgIndex;
      }
      if (TrailingOptArgs < NonFakeArgs)
        OS << ")";
      else if (TrailingOptArgs)
        OS << "\";\n"
           << "    if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
           << "       OS << \")\";\n"
           << "    OS << \"";
d1377 2
d1392 1
a1392 1
/// Return the index of a spelling in a spelling list.
d1422 1
a1422 1
    const StringRef Name = Accessor->getValueAsString("Name");
d1571 1
a1571 1
  StringRef getName() const {
d1803 2
a1804 1
  OS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
d1808 2
a1809 1
    OS << "}\n\n";
d1822 1
a1822 1
      OS << "  MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
d1826 1
a1826 1
          const StringRef Part = (*I)->getValueAsString("Name");
d1828 2
a1829 2
            OS << "!";
          OS << "LangOpts." << Part;
d1831 1
a1831 1
            OS << " || ";
d1834 2
a1835 2
        OS << "true";
      OS << "));\n";
d1838 2
a1839 1
  OS << "}\n\n";
d1895 1
a1895 2
      SubRuleFunction =
          ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
d1943 1
a1943 1
/// Emits the first-argument-is-type property for attributes.
d1965 1
a1965 1
/// Emits the parse-arguments-in-unevaluated-context property for
a2042 1
    bool Inheritable = false;
d2045 1
a2045 2
      if (R->getName() != "TargetSpecificAttr" &&
          R->getName() != "DeclOrTypeAttr" && SuperName.empty())
a2046 2
      if (R->getName() == "InheritableAttr")
        Inheritable = true;
d2140 2
a2141 7
         << ( R.getValueAsBit("LateParsed") ? "true" : "false" );
      if (Inheritable) {
        OS << ", "
           << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
                                                              : "false");
      }
      OS << ")\n";
a2601 25
// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
// parameter with only a single check type, if applicable.
static void GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
                                            std::string *FnName,
                                            StringRef ListName,
                                            StringRef CheckAgainst,
                                            StringRef Scope) {
  if (!R->isValueUnset(ListName)) {
    Test += " && (";
    std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
    for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
      StringRef Part = *I;
      Test += CheckAgainst;
      Test += " == ";
      Test += Scope;
      Test += Part;
      if (I + 1 != E)
        Test += " || ";
      if (FnName)
        *FnName += Part;
    }
    Test += ")";
  }
}

d2615 17
a2631 5
  Test += "true";
  // If one or more architectures is specified, check those.  Arches are handled
  // differently because GenerateTargetRequirements needs to combine the list
  // with ParseKind.
  if (!Arches.empty()) {
d2633 2
a2634 1
    for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
d2636 2
a2637 1
      Test += "T.getArch() == llvm::Triple::";
a2646 4
  // If the attribute is specific to particular OSes, check those.
  GenerateTargetSpecificAttrCheck(R, Test, FnName, "OSes", "T.getOS()",
                                  "llvm::Triple::");

d2648 14
a2661 6
  GenerateTargetSpecificAttrCheck(R, Test, FnName, "CXXABIs",
                                  "Target.getCXXABI().getKind()",
                                  "TargetCXXABI::");
  // If one or more object formats is specified, check those.
  GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
                                  "T.getObjectFormat()", "llvm::Triple::");
a2697 2
      else if (Variety == "C2x")
        Test += " && LangOpts.DoubleSquareBracketAttributes";
a2701 2
    else if (Variety == "C2x")
      Test = "LangOpts.DoubleSquareBracketAttributes";
d2722 1
a2722 1
  std::map<std::string, std::vector<Record *>> CXX, C2x;
a2737 2
      else if (Variety == "C2x")
        C2x[SI.nameSpace()].push_back(R);
d2757 14
a2770 19
  auto fn = [&OS](const char *Spelling, const char *Variety,
                  const std::map<std::string, std::vector<Record *>> &List) {
    OS << "case AttrSyntax::" << Variety << ": {\n";
    // C++11-style attributes are further split out based on the Scope.
    for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
      if (I != List.cbegin())
        OS << " else ";
      if (I->first.empty())
        OS << "if (!Scope || Scope->getName() == \"\") {\n";
      else
        OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
      OS << "  return llvm::StringSwitch<int>(Name)\n";
      GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
      OS << "}";
    }
    OS << "\n} break;\n";
  };
  fn("CXX11", "CXX", CXX);
  fn("C2x", "C", C2x);
d2791 4
a2794 5
                .Case("C2x", 2)
                .Case("Declspec", 3)
                .Case("Microsoft", 4)
                .Case("Keyword", 5)
                .Case("Pragma", 6)
d2968 1
a2968 1
static void emitArgInfo(const Record &R, raw_ostream &OS) {
d2991 1
a2991 1
  OS << "static bool defaultAppertainsTo(Sema &, const ParsedAttr &,";
a2996 15
static std::string GetDiagnosticSpelling(const Record &R) {
  std::string Ret = R.getValueAsString("DiagSpelling");
  if (!Ret.empty())
    return Ret;

  // If we couldn't find the DiagSpelling in this object, we can check to see
  // if the object is one that has a base, and if it is, loop up to the Base
  // member recursively.
  std::string Super = R.getSuperClasses().back().first->getName();
  if (Super == "DDecl" || Super == "DStmt")
    return GetDiagnosticSpelling(*R.getValueAsDef("Base"));

  return "";
}

d3000 1
a3000 1
  const StringRef CustomDiag = S.getValueAsString("CustomDiag");
d3002 23
a3024 1
    return ("\"" + Twine(CustomDiag) + "\"").str();
a3025 1
  std::vector<std::string> DiagList;
d3029 92
a3120 15
    // Get the diagnostic text from the Decl or Stmt node given.
    std::string V = GetDiagnosticSpelling(R);
    if (V.empty()) {
      PrintError(R.getLoc(),
                 "Could not determine diagnostic spelling for the node: " +
                     R.getName() + "; please add one to DeclNodes.td");
    } else {
      // The node may contain a list of elements itself, so split the elements
      // by a comma, and trim any whitespace.
      SmallVector<StringRef, 2> Frags;
      llvm::SplitString(V, Frags, ",");
      for (auto Str : Frags) {
        DiagList.push_back(Str.trim());
      }
    }
d3123 2
a3124 5
  if (DiagList.empty()) {
    PrintFatalError(S.getLoc(),
                    "Could not deduce diagnostic argument for Attr subjects");
    return "";
  }
d3126 1
a3126 17
  // FIXME: this is not particularly good for localization purposes and ideally
  // should be part of the diagnostics engine itself with some sort of list
  // specifier.

  // A single member of the list can be returned directly.
  if (DiagList.size() == 1)
    return '"' + DiagList.front() + '"';

  if (DiagList.size() == 2)
    return '"' + DiagList[0] + " and " + DiagList[1] + '"';

  // If there are more than two in the list, we serialize the first N - 1
  // elements with a comma. This leaves the string in the state: foo, bar,
  // baz (but misses quux). We can then add ", and " for the last element
  // manually.
  std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
  return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
d3193 1
a3193 1
  SS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr, ";
d3213 2
a3214 2
  SS << (Warn ? "warn_attribute_wrong_decl_type_str" :
               "err_attribute_wrong_decl_type_str");
d3265 1
a3265 1
  OS << "const ParsedAttr &) {\n";
d3284 1
a3284 1
    const StringRef Part = (*I)->getValueAsString("Name");
d3289 1
a3289 2
    Test += "S.LangOpts.";
    Test +=  Part;
d3303 1
a3303 1
  OS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr) {\n";
d3332 5
d3341 1
a3341 1
  // attribute has only one ParsedAttr::Kind enumeration value, but it
d3345 1
a3345 1
    const StringRef APK = Attr.getValueAsString("ParseKind");
d3378 1
a3378 1
     << "const ParsedAttr &Attr) {\n";
d3401 1
a3401 1
  OS << "static unsigned " << Name << "(const ParsedAttr &Attr) {\n";
d3441 1
a3441 2
  std::string Buffer;
  raw_string_ostream SS {Buffer};
d3450 1
a3450 1
    // ParsedAttr.cpp.
d3455 1
a3455 3
    SS << ", "
       << (I->second->isSubClassOf("TypeAttr") ||
           I->second->isSubClassOf("DeclOrTypeAttr"));
d3473 1
a3473 2
  OS << "static const ParsedAttrInfo AttrInfoMap[ParsedAttr::UnknownAttribute "
        "+ 1] = {\n";
d3487 1
a3487 1
      Keywords, Pragma, C2x;
d3501 1
a3501 1
      // these to a single ParsedAttr::Kind value, but the StringMatcher
a3524 4
        } else if (Variety == "C2x") {
          Matches = &C2x;
          Spelling += S.nameSpace();
          Spelling += "::";
d3544 2
a3545 2
          Matches->push_back(StringMatcher::StringPair(
              Spelling, "return ParsedAttr::AT_" + AttrName + ";"));
d3547 2
a3548 2
          Matches->push_back(StringMatcher::StringPair(
              Spelling, "return ParsedAttr::IgnoredAttribute;"));
d3552 4
a3555 4

  OS << "static ParsedAttr::Kind getAttrKind(StringRef Name, ";
  OS << "ParsedAttr::Syntax Syntax) {\n";
  OS << "  if (ParsedAttr::AS_GNU == Syntax) {\n";
d3557 1
a3557 1
  OS << "  } else if (ParsedAttr::AS_Declspec == Syntax) {\n";
d3559 1
a3559 1
  OS << "  } else if (ParsedAttr::AS_Microsoft == Syntax) {\n";
d3561 1
a3561 1
  OS << "  } else if (ParsedAttr::AS_CXX11 == Syntax) {\n";
d3563 2
a3564 4
  OS << "  } else if (ParsedAttr::AS_C2x == Syntax) {\n";
  StringMatcher("Name", C2x, OS).Emit();
  OS << "  } else if (ParsedAttr::AS_Keyword == Syntax || ";
  OS << "ParsedAttr::AS_ContextSensitiveKeyword == Syntax) {\n";
d3566 1
a3566 1
  OS << "  } else if (ParsedAttr::AS_Pragma == Syntax) {\n";
d3569 1
a3569 1
  OS << "  return ParsedAttr::UnknownAttribute;\n"
a3626 2
  std::string Heading;
  unsigned SupportedSpellings;
d3628 2
a3629 5
  DocumentationData(const Record &Documentation, const Record &Attribute,
                    const std::pair<std::string, unsigned> HeadingAndKinds)
      : Documentation(&Documentation), Attribute(&Attribute),
        Heading(std::move(HeadingAndKinds.first)),
        SupportedSpellings(HeadingAndKinds.second) {}
d3634 2
a3635 2
  const StringRef Name = DocCategory->getValueAsString("Name");
  OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
d3638 1
a3638 1
  const StringRef ContentStr = DocCategory->getValueAsString("Content");
d3640 1
a3640 1
  OS << ContentStr.trim();
d3648 4
a3651 5
  C2x = 1 << 2,
  Declspec = 1 << 3,
  Microsoft = 1 << 4,
  Keyword = 1 << 5,
  Pragma = 1 << 6
d3654 2
a3655 3
static std::pair<std::string, unsigned>
GetAttributeHeadingAndSpellingKinds(const Record &Documentation,
                                    const Record &Attribute) {
d3660 1
a3660 1
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
d3663 1
a3663 1
  std::string Heading = Documentation.getValueAsString("Heading");
d3685 1
a3685 1
    PrintFatalError(Attribute.getLoc(),
a3697 1
                            .Case("C2x", C2x)
d3707 1
a3707 1
    if ((Kind == CXX11 || Kind == C2x) && !I.nameSpace().empty())
d3727 2
d3730 1
a3730 1
    PrintFatalError(Attribute.getLoc(),
a3732 6
  return std::make_pair(std::move(Heading), SupportedSpellings);
}

static void WriteDocumentation(RecordKeeper &Records,
                               const DocumentationData &Doc, raw_ostream &OS) {
  OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
d3736 1
a3736 1
  OS << "   :header: \"GNU\", \"C++11\", \"C2x\", \"__declspec\", \"Keyword\",";
d3739 1
a3739 1
  if (Doc.SupportedSpellings & GNU) OS << "X";
d3741 1
a3741 1
  if (Doc.SupportedSpellings & CXX11) OS << "X";
d3743 1
a3743 1
  if (Doc.SupportedSpellings & C2x) OS << "X";
d3745 1
a3745 3
  if (Doc.SupportedSpellings & Declspec) OS << "X";
  OS << "\",\"";
  if (Doc.SupportedSpellings & Keyword) OS << "X";
d3747 1
a3747 1
  if (Doc.SupportedSpellings & Pragma) OS << "X";
d3759 1
a3759 1
    const StringRef Replacement = Deprecated.getValueAsString("Replacement");
d3761 2
a3762 2
      OS << "  This attribute has been superseded by ``" << Replacement
         << "``.";
d3766 1
a3766 1
  const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
d3768 1
a3768 1
  OS << ContentStr.trim();
d3797 1
a3797 1
      const StringRef Cat = Category->getValueAsString("Name");
d3802 1
a3802 1
                        "documentation categories");
d3805 1
a3805 2
        SplitDocs[Category].push_back(DocumentationData(
            Doc, Attr, GetAttributeHeadingAndSpellingKinds(Doc, Attr)));
d3811 1
a3811 1
  for (auto &I : SplitDocs) {
a3813 5
    llvm::sort(I.second.begin(), I.second.end(),
               [](const DocumentationData &D1, const DocumentationData &D2) {
                 return D1.Heading < D2.Heading;
              });

@


1.1.1.12
log
@Import clang r337282 from trunk
@
text
@d59 3
a61 3
    assert(V != "GCC" && V != "Clang" &&
           "Given a GCC spelling, which means this hasn't been flattened!");
    if (V == "CXX11" || V == "C2x" || V == "Pragma")
d81 1
a81 3
    StringRef Variety = Spelling->getValueAsString("Variety");
    StringRef Name = Spelling->getValueAsString("Name");
    if (Variety == "GCC") {
d83 3
a85 7
      Ret.emplace_back("GNU", Name, "", true);
      Ret.emplace_back("CXX11", Name, "gnu", true);
    } else if (Variety == "Clang") {
      Ret.emplace_back("GNU", Name, "", false);
      Ret.emplace_back("CXX11", Name, "clang", false);
      if (Spelling->getValueAsBit("AllowInC"))
        Ret.emplace_back("C2x", Name, "clang", false);
a100 1
    .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
a118 1
    .Case("ParamIdx", "push_back(" + std::string(name) + ".serialize());\n")
a227 1
    virtual std::string getIsOmitted() const { return "false"; }
a294 8
    std::string getIsOmitted() const override {
      if (type == "IdentifierInfo *")
        return "!get" + getUpperName().str() + "()";
      if (type == "ParamIdx")
        return "!get" + getUpperName().str() + "().isValid()";
      return "false";
    }

d296 1
a296 1
      if (type == "FunctionDecl *")
d299 9
a307 6
      else if (type == "IdentifierInfo *")
        // Some non-optional (comma required) identifier arguments can be the
        // empty string but are then recorded as a nullptr.
        OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
           << "()->getName() : \"\") << \"";
      else if (type == "TypeSourceInfo *")
d309 1
a309 3
      else if (type == "ParamIdx")
        OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
      else
d311 1
d319 3
a321 4
        // Some non-optional (comma required) identifier arguments can be the
        // empty string but are then recorded as a nullptr.
        OS << "    if (SA->get" << getUpperName() << "())\n"
           << "      OS << \" \" << SA->get" << getUpperName()
a330 5
      } else if (type == "ParamIdx") {
        if (isOptional())
          OS << "    if (SA->get" << getUpperName() << "().isValid())\n  ";
        OS << "    OS << \" \" << SA->get" << getUpperName()
           << "().getSourceIndex();\n";
a492 11
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      StringRef Name = getUpperName();
      OS << "  if (A->is" << Name << "Expr()) {\n"
         << "    if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n" 
         << "      return false;\n" 
         << "  } else if (auto *TSI = A->get" << Name << "Type()) {\n"
         << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
         << "      return false;\n" 
         << "  }\n";
    }

a561 5
    std::string getIsOmitted() const override {
      return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
             + "Expr";
    }

d564 4
a567 2
      OS << "    " << getLowerName()
         << "Expr->printPretty(OS, nullptr, Policy);\n";
a593 4
    // Assumed to receive a parameter: raw_ostream OS.
    virtual void writeDumpImpl(raw_ostream &OS) const {
      OS << "      OS << \" \" << Val;\n";
    }
a632 4
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      // FIXME: Traverse the elements.
    }

d716 1
a716 16
      writeDumpImpl(OS);
    }
  };

  class VariadicParamIdxArgument : public VariadicArgument {
  public:
    VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
        : VariadicArgument(Arg, Attr, "ParamIdx") {}

  public:
    void writeValueImpl(raw_ostream &OS) const override {
      OS << "    OS << Val.getSourceIndex();\n";
    }

    void writeDumpImpl(raw_ostream &OS) const override {
      OS << "      OS << \" \" << Val.getSourceIndex();\n";
a1155 6
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      OS << "  if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
      OS << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
      OS << "      return false;\n";
    }

a1212 4
  else if (ArgName == "VariadicParamIdxArgument")
    Ptr = llvm::make_unique<VariadicParamIdxArgument>(Arg, Attr);
  else if (ArgName == "ParamIdxArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
d1308 1
a1308 1
    } else if (Variety == "CXX11" || Variety == "C2x") {
d1344 1
a1344 1
      OS << "\";\n";
d1352 12
a1364 1
      OS << "(";
a1365 1
      OS << ")";
d1367 1
a1367 3
      OS << "(";
      writeDeprecatedAttrValue(OS, Variety);
      OS << ")";
d1369 1
a1369 34
      // To avoid printing parentheses around an empty argument list or
      // printing spurious commas at the end of an argument list, we need to
      // determine where the last provided non-fake argument is.
      unsigned NonFakeArgs = 0;
      unsigned TrailingOptArgs = 0;
      bool FoundNonOptArg = false;
      for (const auto &arg : llvm::reverse(Args)) {
        if (arg->isFake())
          continue;
        ++NonFakeArgs;
        if (FoundNonOptArg)
          continue;
        // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
        // any way to detect whether the argument was omitted.
        if (!arg->isOptional() || arg->getIsOmitted() == "false") {
          FoundNonOptArg = true;
          continue;
        }
        if (!TrailingOptArgs++)
          OS << "\";\n"
             << "    unsigned TrailingOmittedArgs = 0;\n";
        OS << "    if (" << arg->getIsOmitted() << ")\n"
           << "      ++TrailingOmittedArgs;\n";
      }
      if (TrailingOptArgs)
        OS << "    OS << \"";
      if (TrailingOptArgs < NonFakeArgs)
        OS << "(";
      else if (TrailingOptArgs)
        OS << "\";\n"
           << "    if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
           << "       OS << \"(\";\n"
           << "    OS << \"";
      unsigned ArgIndex = 0;
d1371 2
a1372 17
        if (arg->isFake())
          continue;
        if (ArgIndex) {
          if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
            OS << "\";\n"
               << "    if (" << ArgIndex << " < " << NonFakeArgs
               << " - TrailingOmittedArgs)\n"
               << "      OS << \", \";\n"
               << "    OS << \"";
          else
            OS << ", ";
        }
        std::string IsOmitted = arg->getIsOmitted();
        if (arg->isOptional() && IsOmitted != "false")
          OS << "\";\n"
             << "    if (!(" << IsOmitted << ")) {\n"
             << "      OS << \"";
d1374 1
a1374 13
        if (arg->isOptional() && IsOmitted != "false")
          OS << "\";\n"
             << "    }\n"
             << "    OS << \"";
        ++ArgIndex;
      }
      if (TrailingOptArgs < NonFakeArgs)
        OS << ")";
      else if (TrailingOptArgs)
        OS << "\";\n"
           << "    if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
           << "       OS << \")\";\n"
           << "    OS << \"";
d1377 2
d1392 1
a1392 1
/// Return the index of a spelling in a spelling list.
d1422 1
a1422 1
    const StringRef Name = Accessor->getValueAsString("Name");
d1571 1
a1571 1
  StringRef getName() const {
d1803 2
a1804 1
  OS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
d1808 2
a1809 1
    OS << "}\n\n";
d1822 1
a1822 1
      OS << "  MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
d1826 1
a1826 1
          const StringRef Part = (*I)->getValueAsString("Name");
d1828 2
a1829 2
            OS << "!";
          OS << "LangOpts." << Part;
d1831 1
a1831 1
            OS << " || ";
d1834 2
a1835 2
        OS << "true";
      OS << "));\n";
d1838 2
a1839 1
  OS << "}\n\n";
d1895 1
a1895 2
      SubRuleFunction =
          ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
d1943 1
a1943 1
/// Emits the first-argument-is-type property for attributes.
d1965 1
a1965 1
/// Emits the parse-arguments-in-unevaluated-context property for
a2042 1
    bool Inheritable = false;
d2045 1
a2045 2
      if (R->getName() != "TargetSpecificAttr" &&
          R->getName() != "DeclOrTypeAttr" && SuperName.empty())
a2046 2
      if (R->getName() == "InheritableAttr")
        Inheritable = true;
d2140 2
a2141 7
         << ( R.getValueAsBit("LateParsed") ? "true" : "false" );
      if (Inheritable) {
        OS << ", "
           << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
                                                              : "false");
      }
      OS << ")\n";
a2601 25
// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
// parameter with only a single check type, if applicable.
static void GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
                                            std::string *FnName,
                                            StringRef ListName,
                                            StringRef CheckAgainst,
                                            StringRef Scope) {
  if (!R->isValueUnset(ListName)) {
    Test += " && (";
    std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
    for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
      StringRef Part = *I;
      Test += CheckAgainst;
      Test += " == ";
      Test += Scope;
      Test += Part;
      if (I + 1 != E)
        Test += " || ";
      if (FnName)
        *FnName += Part;
    }
    Test += ")";
  }
}

d2615 17
a2631 5
  Test += "true";
  // If one or more architectures is specified, check those.  Arches are handled
  // differently because GenerateTargetRequirements needs to combine the list
  // with ParseKind.
  if (!Arches.empty()) {
d2633 2
a2634 1
    for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
d2636 2
a2637 1
      Test += "T.getArch() == llvm::Triple::";
a2646 4
  // If the attribute is specific to particular OSes, check those.
  GenerateTargetSpecificAttrCheck(R, Test, FnName, "OSes", "T.getOS()",
                                  "llvm::Triple::");

d2648 14
a2661 6
  GenerateTargetSpecificAttrCheck(R, Test, FnName, "CXXABIs",
                                  "Target.getCXXABI().getKind()",
                                  "TargetCXXABI::");
  // If one or more object formats is specified, check those.
  GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
                                  "T.getObjectFormat()", "llvm::Triple::");
a2697 2
      else if (Variety == "C2x")
        Test += " && LangOpts.DoubleSquareBracketAttributes";
a2701 2
    else if (Variety == "C2x")
      Test = "LangOpts.DoubleSquareBracketAttributes";
d2722 1
a2722 1
  std::map<std::string, std::vector<Record *>> CXX, C2x;
a2737 2
      else if (Variety == "C2x")
        C2x[SI.nameSpace()].push_back(R);
d2757 14
a2770 19
  auto fn = [&OS](const char *Spelling, const char *Variety,
                  const std::map<std::string, std::vector<Record *>> &List) {
    OS << "case AttrSyntax::" << Variety << ": {\n";
    // C++11-style attributes are further split out based on the Scope.
    for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
      if (I != List.cbegin())
        OS << " else ";
      if (I->first.empty())
        OS << "if (!Scope || Scope->getName() == \"\") {\n";
      else
        OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
      OS << "  return llvm::StringSwitch<int>(Name)\n";
      GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
      OS << "}";
    }
    OS << "\n} break;\n";
  };
  fn("CXX11", "CXX", CXX);
  fn("C2x", "C", C2x);
d2791 4
a2794 5
                .Case("C2x", 2)
                .Case("Declspec", 3)
                .Case("Microsoft", 4)
                .Case("Keyword", 5)
                .Case("Pragma", 6)
d2968 1
a2968 1
static void emitArgInfo(const Record &R, raw_ostream &OS) {
d2991 1
a2991 1
  OS << "static bool defaultAppertainsTo(Sema &, const ParsedAttr &,";
a2996 15
static std::string GetDiagnosticSpelling(const Record &R) {
  std::string Ret = R.getValueAsString("DiagSpelling");
  if (!Ret.empty())
    return Ret;

  // If we couldn't find the DiagSpelling in this object, we can check to see
  // if the object is one that has a base, and if it is, loop up to the Base
  // member recursively.
  std::string Super = R.getSuperClasses().back().first->getName();
  if (Super == "DDecl" || Super == "DStmt")
    return GetDiagnosticSpelling(*R.getValueAsDef("Base"));

  return "";
}

d3000 1
a3000 1
  const StringRef CustomDiag = S.getValueAsString("CustomDiag");
d3002 23
a3024 1
    return ("\"" + Twine(CustomDiag) + "\"").str();
a3025 1
  std::vector<std::string> DiagList;
d3029 92
a3120 15
    // Get the diagnostic text from the Decl or Stmt node given.
    std::string V = GetDiagnosticSpelling(R);
    if (V.empty()) {
      PrintError(R.getLoc(),
                 "Could not determine diagnostic spelling for the node: " +
                     R.getName() + "; please add one to DeclNodes.td");
    } else {
      // The node may contain a list of elements itself, so split the elements
      // by a comma, and trim any whitespace.
      SmallVector<StringRef, 2> Frags;
      llvm::SplitString(V, Frags, ",");
      for (auto Str : Frags) {
        DiagList.push_back(Str.trim());
      }
    }
d3123 2
a3124 5
  if (DiagList.empty()) {
    PrintFatalError(S.getLoc(),
                    "Could not deduce diagnostic argument for Attr subjects");
    return "";
  }
d3126 1
a3126 17
  // FIXME: this is not particularly good for localization purposes and ideally
  // should be part of the diagnostics engine itself with some sort of list
  // specifier.

  // A single member of the list can be returned directly.
  if (DiagList.size() == 1)
    return '"' + DiagList.front() + '"';

  if (DiagList.size() == 2)
    return '"' + DiagList[0] + " and " + DiagList[1] + '"';

  // If there are more than two in the list, we serialize the first N - 1
  // elements with a comma. This leaves the string in the state: foo, bar,
  // baz (but misses quux). We can then add ", and " for the last element
  // manually.
  std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
  return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
d3193 1
a3193 1
  SS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr, ";
d3213 2
a3214 2
  SS << (Warn ? "warn_attribute_wrong_decl_type_str" :
               "err_attribute_wrong_decl_type_str");
d3265 1
a3265 1
  OS << "const ParsedAttr &) {\n";
d3284 1
a3284 1
    const StringRef Part = (*I)->getValueAsString("Name");
d3289 1
a3289 2
    Test += "S.LangOpts.";
    Test +=  Part;
d3303 1
a3303 1
  OS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr) {\n";
d3332 5
d3341 1
a3341 1
  // attribute has only one ParsedAttr::Kind enumeration value, but it
d3345 1
a3345 1
    const StringRef APK = Attr.getValueAsString("ParseKind");
d3378 1
a3378 1
     << "const ParsedAttr &Attr) {\n";
d3401 1
a3401 1
  OS << "static unsigned " << Name << "(const ParsedAttr &Attr) {\n";
d3441 1
a3441 2
  std::string Buffer;
  raw_string_ostream SS {Buffer};
d3450 1
a3450 1
    // ParsedAttr.cpp.
d3455 1
a3455 3
    SS << ", "
       << (I->second->isSubClassOf("TypeAttr") ||
           I->second->isSubClassOf("DeclOrTypeAttr"));
d3473 1
a3473 2
  OS << "static const ParsedAttrInfo AttrInfoMap[ParsedAttr::UnknownAttribute "
        "+ 1] = {\n";
d3487 1
a3487 1
      Keywords, Pragma, C2x;
d3501 1
a3501 1
      // these to a single ParsedAttr::Kind value, but the StringMatcher
a3524 4
        } else if (Variety == "C2x") {
          Matches = &C2x;
          Spelling += S.nameSpace();
          Spelling += "::";
d3544 2
a3545 2
          Matches->push_back(StringMatcher::StringPair(
              Spelling, "return ParsedAttr::AT_" + AttrName + ";"));
d3547 2
a3548 2
          Matches->push_back(StringMatcher::StringPair(
              Spelling, "return ParsedAttr::IgnoredAttribute;"));
d3552 4
a3555 4

  OS << "static ParsedAttr::Kind getAttrKind(StringRef Name, ";
  OS << "ParsedAttr::Syntax Syntax) {\n";
  OS << "  if (ParsedAttr::AS_GNU == Syntax) {\n";
d3557 1
a3557 1
  OS << "  } else if (ParsedAttr::AS_Declspec == Syntax) {\n";
d3559 1
a3559 1
  OS << "  } else if (ParsedAttr::AS_Microsoft == Syntax) {\n";
d3561 1
a3561 1
  OS << "  } else if (ParsedAttr::AS_CXX11 == Syntax) {\n";
d3563 2
a3564 4
  OS << "  } else if (ParsedAttr::AS_C2x == Syntax) {\n";
  StringMatcher("Name", C2x, OS).Emit();
  OS << "  } else if (ParsedAttr::AS_Keyword == Syntax || ";
  OS << "ParsedAttr::AS_ContextSensitiveKeyword == Syntax) {\n";
d3566 1
a3566 1
  OS << "  } else if (ParsedAttr::AS_Pragma == Syntax) {\n";
d3569 1
a3569 1
  OS << "  return ParsedAttr::UnknownAttribute;\n"
a3626 2
  std::string Heading;
  unsigned SupportedSpellings;
d3628 2
a3629 5
  DocumentationData(const Record &Documentation, const Record &Attribute,
                    const std::pair<std::string, unsigned> HeadingAndKinds)
      : Documentation(&Documentation), Attribute(&Attribute),
        Heading(std::move(HeadingAndKinds.first)),
        SupportedSpellings(HeadingAndKinds.second) {}
d3634 2
a3635 2
  const StringRef Name = DocCategory->getValueAsString("Name");
  OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
d3638 1
a3638 1
  const StringRef ContentStr = DocCategory->getValueAsString("Content");
d3640 1
a3640 1
  OS << ContentStr.trim();
d3648 4
a3651 5
  C2x = 1 << 2,
  Declspec = 1 << 3,
  Microsoft = 1 << 4,
  Keyword = 1 << 5,
  Pragma = 1 << 6
d3654 2
a3655 3
static std::pair<std::string, unsigned>
GetAttributeHeadingAndSpellingKinds(const Record &Documentation,
                                    const Record &Attribute) {
d3660 1
a3660 1
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
d3663 1
a3663 1
  std::string Heading = Documentation.getValueAsString("Heading");
d3685 1
a3685 1
    PrintFatalError(Attribute.getLoc(),
a3697 1
                            .Case("C2x", C2x)
d3707 1
a3707 1
    if ((Kind == CXX11 || Kind == C2x) && !I.nameSpace().empty())
d3727 2
d3730 1
a3730 1
    PrintFatalError(Attribute.getLoc(),
a3732 6
  return std::make_pair(std::move(Heading), SupportedSpellings);
}

static void WriteDocumentation(RecordKeeper &Records,
                               const DocumentationData &Doc, raw_ostream &OS) {
  OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
d3736 1
a3736 1
  OS << "   :header: \"GNU\", \"C++11\", \"C2x\", \"__declspec\", \"Keyword\",";
d3739 1
a3739 1
  if (Doc.SupportedSpellings & GNU) OS << "X";
d3741 1
a3741 1
  if (Doc.SupportedSpellings & CXX11) OS << "X";
d3743 1
a3743 1
  if (Doc.SupportedSpellings & C2x) OS << "X";
d3745 1
a3745 3
  if (Doc.SupportedSpellings & Declspec) OS << "X";
  OS << "\",\"";
  if (Doc.SupportedSpellings & Keyword) OS << "X";
d3747 1
a3747 1
  if (Doc.SupportedSpellings & Pragma) OS << "X";
d3759 1
a3759 1
    const StringRef Replacement = Deprecated.getValueAsString("Replacement");
d3761 2
a3762 2
      OS << "  This attribute has been superseded by ``" << Replacement
         << "``.";
d3766 1
a3766 1
  const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
d3768 1
a3768 1
  OS << ContentStr.trim();
d3797 1
a3797 1
      const StringRef Cat = Category->getValueAsString("Name");
d3802 1
a3802 1
                        "documentation categories");
d3805 1
a3805 2
        SplitDocs[Category].push_back(DocumentationData(
            Doc, Attr, GetAttributeHeadingAndSpellingKinds(Doc, Attr)));
d3811 1
a3811 1
  for (auto &I : SplitDocs) {
a3813 5
    llvm::sort(I.second.begin(), I.second.end(),
               [](const DocumentationData &D1, const DocumentationData &D2) {
                 return D1.Heading < D2.Heading;
              });

@


1.1.1.13
log
@Mark old LLVM instance as dead.
@
text
@@


1.1.1.7.4.1
log
@file ClangAttrEmitter.cpp was added on branch tls-maxphys on 2014-08-19 23:49:29 +0000
@
text
@d1 2873
@


1.1.1.7.4.2
log
@Rebase to HEAD as of a few days ago.
@
text
@a0 2873
//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang attribute processing code
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/StringMatcher.h"
#include "llvm/TableGen/TableGenBackend.h"
#include <algorithm>
#include <cctype>
#include <memory>
#include <set>
#include <sstream>

using namespace llvm;

class FlattenedSpelling {
  std::string V, N, NS;
  bool K;

public:
  FlattenedSpelling(const std::string &Variety, const std::string &Name,
                    const std::string &Namespace, bool KnownToGCC) :
    V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
  explicit FlattenedSpelling(const Record &Spelling) :
    V(Spelling.getValueAsString("Variety")),
    N(Spelling.getValueAsString("Name")) {

    assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
           "flattened!");
    if (V == "CXX11" || V == "Pragma")
      NS = Spelling.getValueAsString("Namespace");
    bool Unset;
    K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
  }

  const std::string &variety() const { return V; }
  const std::string &name() const { return N; }
  const std::string &nameSpace() const { return NS; }
  bool knownToGCC() const { return K; }
};

std::vector<FlattenedSpelling> GetFlattenedSpellings(const Record &Attr) {
  std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
  std::vector<FlattenedSpelling> Ret;

  for (const auto &Spelling : Spellings) {
    if (Spelling->getValueAsString("Variety") == "GCC") {
      // Gin up two new spelling objects to add into the list.
      Ret.push_back(FlattenedSpelling("GNU", Spelling->getValueAsString("Name"),
                                      "", true));
      Ret.push_back(FlattenedSpelling(
          "CXX11", Spelling->getValueAsString("Name"), "gnu", true));
    } else
      Ret.push_back(FlattenedSpelling(*Spelling));
  }

  return Ret;
}

static std::string ReadPCHRecord(StringRef type) {
  return StringSwitch<std::string>(type)
    .EndsWith("Decl *", "GetLocalDeclAs<" 
              + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
    .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
    .Case("Expr *", "ReadExpr(F)")
    .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
    .Default("Record[Idx++]");
}

// Assumes that the way to get the value is SA->getname()
static std::string WritePCHRecord(StringRef type, StringRef name) {
  return StringSwitch<std::string>(type)
    .EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
                        ", Record);\n")
    .Case("TypeSourceInfo *",
          "AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
    .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
    .Case("IdentifierInfo *", 
          "AddIdentifierRef(" + std::string(name) + ", Record);\n")
    .Default("Record.push_back(" + std::string(name) + ");\n");
}

// Normalize attribute name by removing leading and trailing
// underscores. For example, __foo, foo__, __foo__ would
// become foo.
static StringRef NormalizeAttrName(StringRef AttrName) {
  if (AttrName.startswith("__"))
    AttrName = AttrName.substr(2, AttrName.size());

  if (AttrName.endswith("__"))
    AttrName = AttrName.substr(0, AttrName.size() - 2);

  return AttrName;
}

// Normalize the name by removing any and all leading and trailing underscores.
// This is different from NormalizeAttrName in that it also handles names like
// _pascal and __pascal.
static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
  while (Name.startswith("_"))
    Name = Name.substr(1, Name.size());
  while (Name.endswith("_"))
    Name = Name.substr(0, Name.size() - 1);
  return Name;
}

// Normalize attribute spelling only if the spelling has both leading
// and trailing underscores. For example, __ms_struct__ will be 
// normalized to "ms_struct"; __cdecl will remain intact.
static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
  if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
    AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
  }

  return AttrSpelling;
}

typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;

static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
                                       ParsedAttrMap *Dupes = nullptr) {
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::set<std::string> Seen;
  ParsedAttrMap R;
  for (const auto *Attr : Attrs) {
    if (Attr->getValueAsBit("SemaHandler")) {
      std::string AN;
      if (Attr->isSubClassOf("TargetSpecificAttr") &&
          !Attr->isValueUnset("ParseKind")) {
        AN = Attr->getValueAsString("ParseKind");

        // If this attribute has already been handled, it does not need to be
        // handled again.
        if (Seen.find(AN) != Seen.end()) {
          if (Dupes)
            Dupes->push_back(std::make_pair(AN, Attr));
          continue;
        }
        Seen.insert(AN);
      } else
        AN = NormalizeAttrName(Attr->getName()).str();

      R.push_back(std::make_pair(AN, Attr));
    }
  }
  return R;
}

namespace {
  class Argument {
    std::string lowerName, upperName;
    StringRef attrName;
    bool isOpt;

  public:
    Argument(const Record &Arg, StringRef Attr)
      : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
        attrName(Attr), isOpt(false) {
      if (!lowerName.empty()) {
        lowerName[0] = std::tolower(lowerName[0]);
        upperName[0] = std::toupper(upperName[0]);
      }
    }
    virtual ~Argument() {}

    StringRef getLowerName() const { return lowerName; }
    StringRef getUpperName() const { return upperName; }
    StringRef getAttrName() const { return attrName; }

    bool isOptional() const { return isOpt; }
    void setOptional(bool set) { isOpt = set; }

    // These functions print the argument contents formatted in different ways.
    virtual void writeAccessors(raw_ostream &OS) const = 0;
    virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
    virtual void writeCloneArgs(raw_ostream &OS) const = 0;
    virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
    virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
    virtual void writeCtorBody(raw_ostream &OS) const {}
    virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
    virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
    virtual void writeCtorParameters(raw_ostream &OS) const = 0;
    virtual void writeDeclarations(raw_ostream &OS) const = 0;
    virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
    virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
    virtual void writePCHWrite(raw_ostream &OS) const = 0;
    virtual void writeValue(raw_ostream &OS) const = 0;
    virtual void writeDump(raw_ostream &OS) const = 0;
    virtual void writeDumpChildren(raw_ostream &OS) const {}
    virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }

    virtual bool isEnumArg() const { return false; }
    virtual bool isVariadicEnumArg() const { return false; }
    virtual bool isVariadic() const { return false; }

    virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
      OS << getUpperName();
    }
  };

  class SimpleArgument : public Argument {
    std::string type;

  public:
    SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
      : Argument(Arg, Attr), type(T)
    {}

    std::string getType() const { return type; }

    void writeAccessors(raw_ostream &OS) const override {
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const override {
      OS << getLowerName();
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorInitializers(raw_ostream &OS) const override {
      OS << getLowerName() << "(" << getUpperName() << ")";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
      OS << getLowerName() << "()";
    }
    void writeCtorParameters(raw_ostream &OS) const override {
      OS << type << " " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const override {
      OS << type << " " << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const override {
      std::string read = ReadPCHRecord(type);
      OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const override {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const override {
      OS << "    " << WritePCHRecord(type, "SA->get" +
                                           std::string(getUpperName()) + "()");
    }
    void writeValue(raw_ostream &OS) const override {
      if (type == "FunctionDecl *") {
        OS << "\" << get" << getUpperName()
           << "()->getNameInfo().getAsString() << \"";
      } else if (type == "IdentifierInfo *") {
        OS << "\" << get" << getUpperName() << "()->getName() << \"";
      } else if (type == "TypeSourceInfo *") {
        OS << "\" << get" << getUpperName() << "().getAsString() << \"";
      } else {
        OS << "\" << get" << getUpperName() << "() << \"";
      }
    }
    void writeDump(raw_ostream &OS) const override {
      if (type == "FunctionDecl *") {
        OS << "    OS << \" \";\n";
        OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n"; 
      } else if (type == "IdentifierInfo *") {
        OS << "    OS << \" \" << SA->get" << getUpperName()
           << "()->getName();\n";
      } else if (type == "TypeSourceInfo *") {
        OS << "    OS << \" \" << SA->get" << getUpperName()
           << "().getAsString();\n";
      } else if (type == "bool") {
        OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
           << getUpperName() << "\";\n";
      } else if (type == "int" || type == "unsigned") {
        OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
      } else {
        llvm_unreachable("Unknown SimpleArgument type!");
      }
    }
  };

  class DefaultSimpleArgument : public SimpleArgument {
    int64_t Default;

  public:
    DefaultSimpleArgument(const Record &Arg, StringRef Attr,
                          std::string T, int64_t Default)
      : SimpleArgument(Arg, Attr, T), Default(Default) {}

    void writeAccessors(raw_ostream &OS) const override {
      SimpleArgument::writeAccessors(OS);

      OS << "\n\n  static const " << getType() << " Default" << getUpperName()
         << " = " << Default << ";";
    }
  };

  class StringArgument : public Argument {
  public:
    StringArgument(const Record &Arg, StringRef Attr)
      : Argument(Arg, Attr)
    {}

    void writeAccessors(raw_ostream &OS) const override {
      OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
      OS << "    return llvm::StringRef(" << getLowerName() << ", "
         << getLowerName() << "Length);\n";
      OS << "  }\n";
      OS << "  unsigned get" << getUpperName() << "Length() const {\n";
      OS << "    return " << getLowerName() << "Length;\n";
      OS << "  }\n";
      OS << "  void set" << getUpperName()
         << "(ASTContext &C, llvm::StringRef S) {\n";
      OS << "    " << getLowerName() << "Length = S.size();\n";
      OS << "    this->" << getLowerName() << " = new (C, 1) char ["
         << getLowerName() << "Length];\n";
      OS << "    std::memcpy(this->" << getLowerName() << ", S.data(), "
         << getLowerName() << "Length);\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const override {
      OS << "get" << getUpperName() << "()";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorBody(raw_ostream &OS) const override {
      OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName()
         << ".data(), " << getLowerName() << "Length);";
    }
    void writeCtorInitializers(raw_ostream &OS) const override {
      OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
         << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
         << "Length])";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
      OS << getLowerName() << "Length(0)," << getLowerName() << "(0)";
    }
    void writeCtorParameters(raw_ostream &OS) const override {
      OS << "llvm::StringRef " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const override {
      OS << "unsigned " << getLowerName() << "Length;\n";
      OS << "char *" << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const override {
      OS << "    std::string " << getLowerName()
         << "= ReadString(Record, Idx);\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const override {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const override {
      OS << "    AddString(SA->get" << getUpperName() << "(), Record);\n";
    }
    void writeValue(raw_ostream &OS) const override {
      OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
    }
    void writeDump(raw_ostream &OS) const override {
      OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
         << "() << \"\\\"\";\n";
    }
  };

  class AlignedArgument : public Argument {
  public:
    AlignedArgument(const Record &Arg, StringRef Attr)
      : Argument(Arg, Attr)
    {}

    void writeAccessors(raw_ostream &OS) const override {
      OS << "  bool is" << getUpperName() << "Dependent() const;\n";

      OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";

      OS << "  bool is" << getUpperName() << "Expr() const {\n";
      OS << "    return is" << getLowerName() << "Expr;\n";
      OS << "  }\n";

      OS << "  Expr *get" << getUpperName() << "Expr() const {\n";
      OS << "    assert(is" << getLowerName() << "Expr);\n";
      OS << "    return " << getLowerName() << "Expr;\n";
      OS << "  }\n";

      OS << "  TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
      OS << "    assert(!is" << getLowerName() << "Expr);\n";
      OS << "    return " << getLowerName() << "Type;\n";
      OS << "  }";
    }
    void writeAccessorDefinitions(raw_ostream &OS) const override {
      OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
         << "Dependent() const {\n";
      OS << "  if (is" << getLowerName() << "Expr)\n";
      OS << "    return " << getLowerName() << "Expr && (" << getLowerName()
         << "Expr->isValueDependent() || " << getLowerName()
         << "Expr->isTypeDependent());\n"; 
      OS << "  else\n";
      OS << "    return " << getLowerName()
         << "Type->getType()->isDependentType();\n";
      OS << "}\n";

      // FIXME: Do not do the calculation here
      // FIXME: Handle types correctly
      // A null pointer means maximum alignment
      // FIXME: Load the platform-specific maximum alignment, rather than
      //        16, the x86 max.
      OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
         << "(ASTContext &Ctx) const {\n";
      OS << "  assert(!is" << getUpperName() << "Dependent());\n";
      OS << "  if (is" << getLowerName() << "Expr)\n";
      OS << "    return (" << getLowerName() << "Expr ? " << getLowerName()
         << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue() : 16)"
         << "* Ctx.getCharWidth();\n";
      OS << "  else\n";
      OS << "    return 0; // FIXME\n";
      OS << "}\n";
    }
    void writeCloneArgs(raw_ostream &OS) const override {
      OS << "is" << getLowerName() << "Expr, is" << getLowerName()
         << "Expr ? static_cast<void*>(" << getLowerName()
         << "Expr) : " << getLowerName()
         << "Type";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
      // FIXME: move the definition in Sema::InstantiateAttrs to here.
      // In the meantime, aligned attributes are cloned.
    }
    void writeCtorBody(raw_ostream &OS) const override {
      OS << "    if (is" << getLowerName() << "Expr)\n";
      OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
         << getUpperName() << ");\n";
      OS << "    else\n";
      OS << "       " << getLowerName()
         << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
         << ");";
    }
    void writeCtorInitializers(raw_ostream &OS) const override {
      OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
      OS << "is" << getLowerName() << "Expr(false)";
    }
    void writeCtorParameters(raw_ostream &OS) const override {
      OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
    }
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
      OS << "Is" << getUpperName() << "Expr, " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const override {
      OS << "bool is" << getLowerName() << "Expr;\n";
      OS << "union {\n";
      OS << "Expr *" << getLowerName() << "Expr;\n";
      OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
      OS << "};";
    }
    void writePCHReadArgs(raw_ostream &OS) const override {
      OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
    }
    void writePCHReadDecls(raw_ostream &OS) const override {
      OS << "    bool is" << getLowerName() << "Expr = Record[Idx++];\n";
      OS << "    void *" << getLowerName() << "Ptr;\n";
      OS << "    if (is" << getLowerName() << "Expr)\n";
      OS << "      " << getLowerName() << "Ptr = ReadExpr(F);\n";
      OS << "    else\n";
      OS << "      " << getLowerName()
         << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
    }
    void writePCHWrite(raw_ostream &OS) const override {
      OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
      OS << "    if (SA->is" << getUpperName() << "Expr())\n";
      OS << "      AddStmt(SA->get" << getUpperName() << "Expr());\n";
      OS << "    else\n";
      OS << "      AddTypeSourceInfo(SA->get" << getUpperName()
         << "Type(), Record);\n";
    }
    void writeValue(raw_ostream &OS) const override {
      OS << "\";\n";
      // The aligned attribute argument expression is optional.
      OS << "    if (is" << getLowerName() << "Expr && "
         << getLowerName() << "Expr)\n";
      OS << "      " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n";
      OS << "    OS << \"";
    }
    void writeDump(raw_ostream &OS) const override {
    }
    void writeDumpChildren(raw_ostream &OS) const override {
      OS << "    if (SA->is" << getUpperName() << "Expr()) {\n";
      OS << "      lastChild();\n";
      OS << "      dumpStmt(SA->get" << getUpperName() << "Expr());\n";
      OS << "    } else\n";
      OS << "      dumpType(SA->get" << getUpperName()
         << "Type()->getType());\n";
    }
    void writeHasChildren(raw_ostream &OS) const override {
      OS << "SA->is" << getUpperName() << "Expr()";
    }
  };

  class VariadicArgument : public Argument {
    std::string Type, ArgName, ArgSizeName, RangeName;

  public:
    VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
        : Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
          ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}

    std::string getType() const { return Type; }
    bool isVariadic() const override { return true; }

    void writeAccessors(raw_ostream &OS) const override {
      std::string IteratorType = getLowerName().str() + "_iterator";
      std::string BeginFn = getLowerName().str() + "_begin()";
      std::string EndFn = getLowerName().str() + "_end()";
      
      OS << "  typedef " << Type << "* " << IteratorType << ";\n";
      OS << "  " << IteratorType << " " << BeginFn << " const {"
         << " return " << ArgName << "; }\n";
      OS << "  " << IteratorType << " " << EndFn << " const {"
         << " return " << ArgName << " + " << ArgSizeName << "; }\n";
      OS << "  unsigned " << getLowerName() << "_size() const {"
         << " return " << ArgSizeName << "; }\n";
      OS << "  llvm::iterator_range<" << IteratorType << "> " << RangeName
         << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
         << "); }\n";
    }
    void writeCloneArgs(raw_ostream &OS) const override {
      OS << ArgName << ", " << ArgSizeName;
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
      // This isn't elegant, but we have to go through public methods...
      OS << "A->" << getLowerName() << "_begin(), "
         << "A->" << getLowerName() << "_size()";
    }
    void writeCtorBody(raw_ostream &OS) const override {
      OS << "    std::copy(" << getUpperName() << ", " << getUpperName()
         << " + " << ArgSizeName << ", " << ArgName << ");";
    }
    void writeCtorInitializers(raw_ostream &OS) const override {
      OS << ArgSizeName << "(" << getUpperName() << "Size), "
         << ArgName << "(new (Ctx, 16) " << getType() << "["
         << ArgSizeName << "])";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
      OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
    }
    void writeCtorParameters(raw_ostream &OS) const override {
      OS << getType() << " *" << getUpperName() << ", unsigned "
         << getUpperName() << "Size";
    }
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
      OS << getUpperName() << ", " << getUpperName() << "Size";
    }
    void writeDeclarations(raw_ostream &OS) const override {
      OS << "  unsigned " << ArgSizeName << ";\n";
      OS << "  " << getType() << " *" << ArgName << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const override {
      OS << "  unsigned " << getLowerName() << "Size = Record[Idx++];\n";
      OS << "  SmallVector<" << Type << ", 4> " << getLowerName()
         << ";\n";
      OS << "  " << getLowerName() << ".reserve(" << getLowerName()
         << "Size);\n";
      OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
      
      std::string read = ReadPCHRecord(Type);
      OS << "    " << getLowerName() << ".push_back(" << read << ");\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const override {
      OS << getLowerName() << ".data(), " << getLowerName() << "Size";
    }
    void writePCHWrite(raw_ostream &OS) const override {
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
      OS << "    for (auto &Val : SA->" << RangeName << "())\n";
      OS << "      " << WritePCHRecord(Type, "Val");
    }
    void writeValue(raw_ostream &OS) const override {
      OS << "\";\n";
      OS << "  bool isFirst = true;\n"
         << "  for (const auto &Val : " << RangeName << "()) {\n"
         << "    if (isFirst) isFirst = false;\n"
         << "    else OS << \", \";\n"
         << "    OS << Val;\n"
         << "  }\n";
      OS << "  OS << \"";
    }
    void writeDump(raw_ostream &OS) const override {
      OS << "    for (const auto &Val : SA->" << RangeName << "())\n";
      OS << "      OS << \" \" << Val;\n";
    }
  };

  // Unique the enums, but maintain the original declaration ordering.
  std::vector<std::string>
  uniqueEnumsInOrder(const std::vector<std::string> &enums) {
    std::vector<std::string> uniques;
    std::set<std::string> unique_set(enums.begin(), enums.end());
    for (const auto &i : enums) {
      std::set<std::string>::iterator set_i = unique_set.find(i);
      if (set_i != unique_set.end()) {
        uniques.push_back(i);
        unique_set.erase(set_i);
      }
    }
    return uniques;
  }

  class EnumArgument : public Argument {
    std::string type;
    std::vector<std::string> values, enums, uniques;
  public:
    EnumArgument(const Record &Arg, StringRef Attr)
      : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
        values(Arg.getValueAsListOfStrings("Values")),
        enums(Arg.getValueAsListOfStrings("Enums")),
        uniques(uniqueEnumsInOrder(enums))
    {
      // FIXME: Emit a proper error
      assert(!uniques.empty());
    }

    bool isEnumArg() const override { return true; }

    void writeAccessors(raw_ostream &OS) const override {
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const override {
      OS << getLowerName();
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorInitializers(raw_ostream &OS) const override {
      OS << getLowerName() << "(" << getUpperName() << ")";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
      OS << getLowerName() << "(" << type << "(0))";
    }
    void writeCtorParameters(raw_ostream &OS) const override {
      OS << type << " " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const override {
      std::vector<std::string>::const_iterator i = uniques.begin(),
                                               e = uniques.end();
      // The last one needs to not have a comma.
      --e;

      OS << "public:\n";
      OS << "  enum " << type << " {\n";
      for (; i != e; ++i)
        OS << "    " << *i << ",\n";
      OS << "    " << *e << "\n";
      OS << "  };\n";
      OS << "private:\n";
      OS << "  " << type << " " << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const override {
      OS << "    " << getAttrName() << "Attr::" << type << " " << getLowerName()
         << "(static_cast<" << getAttrName() << "Attr::" << type
         << ">(Record[Idx++]));\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const override {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const override {
      OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
    }
    void writeValue(raw_ostream &OS) const override {
      OS << "\" << get" << getUpperName() << "() << \"";
    }
    void writeDump(raw_ostream &OS) const override {
      OS << "    switch(SA->get" << getUpperName() << "()) {\n";
      for (const auto &I : uniques) {
        OS << "    case " << getAttrName() << "Attr::" << I << ":\n";
        OS << "      OS << \" " << I << "\";\n";
        OS << "      break;\n";
      }
      OS << "    }\n";
    }

    void writeConversion(raw_ostream &OS) const {
      OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
      OS << type << " &Out) {\n";
      OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
      OS << type << ">>(Val)\n";
      for (size_t I = 0; I < enums.size(); ++I) {
        OS << "      .Case(\"" << values[I] << "\", ";
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
      }
      OS << "      .Default(Optional<" << type << ">());\n";
      OS << "    if (R) {\n";
      OS << "      Out = *R;\n      return true;\n    }\n";
      OS << "    return false;\n";
      OS << "  }\n";
    }
  };
  
  class VariadicEnumArgument: public VariadicArgument {
    std::string type, QualifiedTypeName;
    std::vector<std::string> values, enums, uniques;
  public:
    VariadicEnumArgument(const Record &Arg, StringRef Attr)
      : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
        type(Arg.getValueAsString("Type")),
        values(Arg.getValueAsListOfStrings("Values")),
        enums(Arg.getValueAsListOfStrings("Enums")),
        uniques(uniqueEnumsInOrder(enums))
    {
      QualifiedTypeName = getAttrName().str() + "Attr::" + type;
      
      // FIXME: Emit a proper error
      assert(!uniques.empty());
    }

    bool isVariadicEnumArg() const override { return true; }
    
    void writeDeclarations(raw_ostream &OS) const override {
      std::vector<std::string>::const_iterator i = uniques.begin(),
                                               e = uniques.end();
      // The last one needs to not have a comma.
      --e;

      OS << "public:\n";
      OS << "  enum " << type << " {\n";
      for (; i != e; ++i)
        OS << "    " << *i << ",\n";
      OS << "    " << *e << "\n";
      OS << "  };\n";
      OS << "private:\n";
      
      VariadicArgument::writeDeclarations(OS);
    }
    void writeDump(raw_ostream &OS) const override {
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
         << getLowerName() << "_end(); I != E; ++I) {\n";
      OS << "      switch(*I) {\n";
      for (const auto &UI : uniques) {
        OS << "    case " << getAttrName() << "Attr::" << UI << ":\n";
        OS << "      OS << \" " << UI << "\";\n";
        OS << "      break;\n";
      }
      OS << "      }\n";
      OS << "    }\n";
    }
    void writePCHReadDecls(raw_ostream &OS) const override {
      OS << "    unsigned " << getLowerName() << "Size = Record[Idx++];\n";
      OS << "    SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
         << ";\n";
      OS << "    " << getLowerName() << ".reserve(" << getLowerName()
         << "Size);\n";
      OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
      OS << "      " << getLowerName() << ".push_back(" << "static_cast<"
         << QualifiedTypeName << ">(Record[Idx++]));\n";
    }
    void writePCHWrite(raw_ostream &OS) const override {
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
         << getLowerName() << "_end(); i != e; ++i)\n";
      OS << "      " << WritePCHRecord(QualifiedTypeName, "(*i)");
    }
    void writeConversion(raw_ostream &OS) const {
      OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
      OS << type << " &Out) {\n";
      OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
      OS << type << ">>(Val)\n";
      for (size_t I = 0; I < enums.size(); ++I) {
        OS << "      .Case(\"" << values[I] << "\", ";
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
      }
      OS << "      .Default(Optional<" << type << ">());\n";
      OS << "    if (R) {\n";
      OS << "      Out = *R;\n      return true;\n    }\n";
      OS << "    return false;\n";
      OS << "  }\n";
    }
  };

  class VersionArgument : public Argument {
  public:
    VersionArgument(const Record &Arg, StringRef Attr)
      : Argument(Arg, Attr)
    {}

    void writeAccessors(raw_ostream &OS) const override {
      OS << "  VersionTuple get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }\n";
      OS << "  void set" << getUpperName() 
         << "(ASTContext &C, VersionTuple V) {\n";
      OS << "    " << getLowerName() << " = V;\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const override {
      OS << "get" << getUpperName() << "()";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorInitializers(raw_ostream &OS) const override {
      OS << getLowerName() << "(" << getUpperName() << ")";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
      OS << getLowerName() << "()";
    }
    void writeCtorParameters(raw_ostream &OS) const override {
      OS << "VersionTuple " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const override {
      OS << "VersionTuple " << getLowerName() << ";\n";
    }
    void writePCHReadDecls(raw_ostream &OS) const override {
      OS << "    VersionTuple " << getLowerName()
         << "= ReadVersionTuple(Record, Idx);\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const override {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const override {
      OS << "    AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
    }
    void writeValue(raw_ostream &OS) const override {
      OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
    }
    void writeDump(raw_ostream &OS) const override {
      OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
    }
  };

  class ExprArgument : public SimpleArgument {
  public:
    ExprArgument(const Record &Arg, StringRef Attr)
      : SimpleArgument(Arg, Attr, "Expr *")
    {}

    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      OS << "  if (!"
         << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
      OS << "    return false;\n";
    }

    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
      OS << "tempInst" << getUpperName();
    }

    void writeTemplateInstantiation(raw_ostream &OS) const override {
      OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
      OS << "      {\n";
      OS << "        EnterExpressionEvaluationContext "
         << "Unevaluated(S, Sema::Unevaluated);\n";
      OS << "        ExprResult " << "Result = S.SubstExpr("
         << "A->get" << getUpperName() << "(), TemplateArgs);\n";
      OS << "        tempInst" << getUpperName() << " = "
         << "Result.getAs<Expr>();\n";
      OS << "      }\n";
    }

    void writeDump(raw_ostream &OS) const override {}

    void writeDumpChildren(raw_ostream &OS) const override {
      OS << "    lastChild();\n";
      OS << "    dumpStmt(SA->get" << getUpperName() << "());\n";
    }
    void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
  };

  class VariadicExprArgument : public VariadicArgument {
  public:
    VariadicExprArgument(const Record &Arg, StringRef Attr)
      : VariadicArgument(Arg, Attr, "Expr *")
    {}

    void writeASTVisitorTraversal(raw_ostream &OS) const override {
      OS << "  {\n";
      OS << "    " << getType() << " *I = A->" << getLowerName()
         << "_begin();\n";
      OS << "    " << getType() << " *E = A->" << getLowerName()
         << "_end();\n";
      OS << "    for (; I != E; ++I) {\n";
      OS << "      if (!getDerived().TraverseStmt(*I))\n";
      OS << "        return false;\n";
      OS << "    }\n";
      OS << "  }\n";
    }

    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
      OS << "tempInst" << getUpperName() << ", "
         << "A->" << getLowerName() << "_size()";
    }

    void writeTemplateInstantiation(raw_ostream &OS) const override {
      OS << "      " << getType() << " *tempInst" << getUpperName()
         << " = new (C, 16) " << getType()
         << "[A->" << getLowerName() << "_size()];\n";
      OS << "      {\n";
      OS << "        EnterExpressionEvaluationContext "
         << "Unevaluated(S, Sema::Unevaluated);\n";
      OS << "        " << getType() << " *TI = tempInst" << getUpperName()
         << ";\n";
      OS << "        " << getType() << " *I = A->" << getLowerName()
         << "_begin();\n";
      OS << "        " << getType() << " *E = A->" << getLowerName()
         << "_end();\n";
      OS << "        for (; I != E; ++I, ++TI) {\n";
      OS << "          ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
      OS << "          *TI = Result.getAs<Expr>();\n";
      OS << "        }\n";
      OS << "      }\n";
    }

    void writeDump(raw_ostream &OS) const override {}

    void writeDumpChildren(raw_ostream &OS) const override {
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
         << getLowerName() << "_end(); I != E; ++I) {\n";
      OS << "      if (I + 1 == E)\n";
      OS << "        lastChild();\n";
      OS << "      dumpStmt(*I);\n";
      OS << "    }\n";
    }

    void writeHasChildren(raw_ostream &OS) const override {
      OS << "SA->" << getLowerName() << "_begin() != "
         << "SA->" << getLowerName() << "_end()";
    }
  };

  class TypeArgument : public SimpleArgument {
  public:
    TypeArgument(const Record &Arg, StringRef Attr)
      : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
    {}

    void writeAccessors(raw_ostream &OS) const override {
      OS << "  QualType get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << "->getType();\n";
      OS << "  }";
      OS << "  " << getType() << " get" << getUpperName() << "Loc() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
      OS << "A->get" << getUpperName() << "Loc()";
    }
    void writePCHWrite(raw_ostream &OS) const override {
      OS << "    " << WritePCHRecord(
          getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
    }
  };
}

static std::unique_ptr<Argument>
createArgument(const Record &Arg, StringRef Attr,
               const Record *Search = nullptr) {
  if (!Search)
    Search = &Arg;

  std::unique_ptr<Argument> Ptr;
  llvm::StringRef ArgName = Search->getName();

  if (ArgName == "AlignedArgument")
    Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
  else if (ArgName == "EnumArgument")
    Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
  else if (ArgName == "ExprArgument")
    Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
  else if (ArgName == "FunctionArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
  else if (ArgName == "IdentifierArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
  else if (ArgName == "DefaultBoolArgument")
    Ptr = llvm::make_unique<DefaultSimpleArgument>(
        Arg, Attr, "bool", Arg.getValueAsBit("Default"));
  else if (ArgName == "BoolArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
  else if (ArgName == "DefaultIntArgument")
    Ptr = llvm::make_unique<DefaultSimpleArgument>(
        Arg, Attr, "int", Arg.getValueAsInt("Default"));
  else if (ArgName == "IntArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
  else if (ArgName == "StringArgument")
    Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
  else if (ArgName == "TypeArgument")
    Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
  else if (ArgName == "UnsignedArgument")
    Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
  else if (ArgName == "VariadicUnsignedArgument")
    Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
  else if (ArgName == "VariadicEnumArgument")
    Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
  else if (ArgName == "VariadicExprArgument")
    Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
  else if (ArgName == "VersionArgument")
    Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);

  if (!Ptr) {
    // Search in reverse order so that the most-derived type is handled first.
    std::vector<Record*> Bases = Search->getSuperClasses();
    for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
      if ((Ptr = createArgument(Arg, Attr, Base)))
        break;
    }
  }

  if (Ptr && Arg.getValueAsBit("Optional"))
    Ptr->setOptional(true);

  return Ptr;
}

static void writeAvailabilityValue(raw_ostream &OS) {
  OS << "\" << getPlatform()->getName();\n"
     << "  if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
     << "  if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
     << "  if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
     << "  if (getUnavailable()) OS << \", unavailable\";\n"
     << "  OS << \"";
}

static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);

  OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
  if (Spellings.empty()) {
    OS << "  return \"(No spelling)\";\n}\n\n";
    return;
  }

  OS << "  switch (SpellingListIndex) {\n"
        "  default:\n"
        "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
        "    return \"(No spelling)\";\n";

  for (unsigned I = 0; I < Spellings.size(); ++I)
    OS << "  case " << I << ":\n"
          "    return \"" << Spellings[I].name() << "\";\n";
  // End of the switch statement.
  OS << "  }\n";
  // End of the getSpelling function.
  OS << "}\n\n";
}

static void
writePrettyPrintFunction(Record &R,
                         const std::vector<std::unique_ptr<Argument>> &Args,
                         raw_ostream &OS) {
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);

  OS << "void " << R.getName() << "Attr::printPretty("
    << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";

  if (Spellings.empty()) {
    OS << "}\n\n";
    return;
  }

  OS <<
    "  switch (SpellingListIndex) {\n"
    "  default:\n"
    "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
    "    break;\n";

  for (unsigned I = 0; I < Spellings.size(); ++ I) {
    llvm::SmallString<16> Prefix;
    llvm::SmallString<8> Suffix;
    // The actual spelling of the name and namespace (if applicable)
    // of an attribute without considering prefix and suffix.
    llvm::SmallString<64> Spelling;
    std::string Name = Spellings[I].name();
    std::string Variety = Spellings[I].variety();

    if (Variety == "GNU") {
      Prefix = " __attribute__((";
      Suffix = "))";
    } else if (Variety == "CXX11") {
      Prefix = " [[";
      Suffix = "]]";
      std::string Namespace = Spellings[I].nameSpace();
      if (!Namespace.empty()) {
        Spelling += Namespace;
        Spelling += "::";
      }
    } else if (Variety == "Declspec") {
      Prefix = " __declspec(";
      Suffix = ")";
    } else if (Variety == "Keyword") {
      Prefix = " ";
      Suffix = "";
    } else if (Variety == "Pragma") {
      Prefix = "#pragma ";
      Suffix = "\n";
      std::string Namespace = Spellings[I].nameSpace();
      if (!Namespace.empty()) {
        Spelling += Namespace;
        Spelling += " ";
      }
    } else {
      llvm_unreachable("Unknown attribute syntax variety!");
    }

    Spelling += Name;

    OS <<
      "  case " << I << " : {\n"
      "    OS << \"" + Prefix.str() + Spelling.str();

    if (Variety == "Pragma") {
      OS << " \";\n";
      OS << "    printPrettyPragma(OS, Policy);\n";
      OS << "    break;\n";
      OS << "  }\n";
      continue;
    }

    // FIXME: always printing the parenthesis isn't the correct behavior for
    // attributes which have optional arguments that were not provided. For
    // instance: __attribute__((aligned)) will be pretty printed as
    // __attribute__((aligned())). The logic should check whether there is only
    // a single argument, and if it is optional, whether it has been provided.
    if (!Args.empty())
      OS << "(";
    if (Spelling == "availability") {
      writeAvailabilityValue(OS);
    } else {
      for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
        if (I != Args.begin()) OS << ", ";
        (*I)->writeValue(OS);
      }
    }

    if (!Args.empty())
      OS << ")";
    OS << Suffix.str() + "\";\n";

    OS <<
      "    break;\n"
      "  }\n";
  }

  // End of the switch statement.
  OS << "}\n";
  // End of the print function.
  OS << "}\n\n";
}

/// \brief Return the index of a spelling in a spelling list.
static unsigned
getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
                     const FlattenedSpelling &Spelling) {
  assert(SpellingList.size() && "Spelling list is empty!");

  for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
    const FlattenedSpelling &S = SpellingList[Index];
    if (S.variety() != Spelling.variety())
      continue;
    if (S.nameSpace() != Spelling.nameSpace())
      continue;
    if (S.name() != Spelling.name())
      continue;

    return Index;
  }

  llvm_unreachable("Unknown spelling!");
}

static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
  std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
  for (const auto *Accessor : Accessors) {
    std::string Name = Accessor->getValueAsString("Name");
    std::vector<FlattenedSpelling> Spellings = 
      GetFlattenedSpellings(*Accessor);
    std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
    assert(SpellingList.size() &&
           "Attribute with empty spelling list can't have accessors!");

    OS << "  bool " << Name << "() const { return SpellingListIndex == ";
    for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
      OS << getSpellingListIndex(SpellingList, Spellings[Index]);
      if (Index != Spellings.size() -1)
        OS << " ||\n    SpellingListIndex == ";
      else
        OS << "; }\n";
    }
  }
}

static bool
SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
  assert(!Spellings.empty() && "An empty list of spellings was provided");
  std::string FirstName = NormalizeNameForSpellingComparison(
    Spellings.front().name());
  for (const auto &Spelling :
       llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
    std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
    if (Name != FirstName)
      return false;
  }
  return true;
}

typedef std::map<unsigned, std::string> SemanticSpellingMap;
static std::string
CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
                        SemanticSpellingMap &Map) {
  // The enumerants are automatically generated based on the variety,
  // namespace (if present) and name for each attribute spelling. However,
  // care is taken to avoid trampling on the reserved namespace due to
  // underscores.
  std::string Ret("  enum Spelling {\n");
  std::set<std::string> Uniques;
  unsigned Idx = 0;
  for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
    const FlattenedSpelling &S = *I;
    std::string Variety = S.variety();
    std::string Spelling = S.name();
    std::string Namespace = S.nameSpace();
    std::string EnumName = "";

    EnumName += (Variety + "_");
    if (!Namespace.empty())
      EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
      "_");
    EnumName += NormalizeNameForSpellingComparison(Spelling);

    // Even if the name is not unique, this spelling index corresponds to a
    // particular enumerant name that we've calculated.
    Map[Idx] = EnumName;

    // Since we have been stripping underscores to avoid trampling on the
    // reserved namespace, we may have inadvertently created duplicate
    // enumerant names. These duplicates are not considered part of the
    // semantic spelling, and can be elided.
    if (Uniques.find(EnumName) != Uniques.end())
      continue;

    Uniques.insert(EnumName);
    if (I != Spellings.begin())
      Ret += ",\n";
    Ret += "    " + EnumName;
  }
  Ret += "\n  };\n\n";
  return Ret;
}

void WriteSemanticSpellingSwitch(const std::string &VarName,
                                 const SemanticSpellingMap &Map,
                                 raw_ostream &OS) {
  OS << "  switch (" << VarName << ") {\n    default: "
    << "llvm_unreachable(\"Unknown spelling list index\");\n";
  for (const auto &I : Map)
    OS << "    case " << I.first << ": return " << I.second << ";\n";
  OS << "  }\n";
}

// Emits the LateParsed property for attributes.
static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (const auto *Attr : Attrs) {
    bool LateParsed = Attr->getValueAsBit("LateParsed");

    if (LateParsed) {
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);

      // FIXME: Handle non-GNU attributes
      for (const auto &I : Spellings) {
        if (I.variety() != "GNU")
          continue;
        OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
      }
    }
  }
  OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
}

/// \brief Emits the first-argument-is-type property for attributes.
static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (const auto *Attr : Attrs) {
    // Determine whether the first argument is a type.
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
    if (Args.empty())
      continue;

    if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
      continue;

    // All these spellings take a single type argument.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
    std::set<std::string> Emitted;
    for (const auto &S : Spellings) {
      if (Emitted.insert(S.name()).second)
        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
    }
  }
  OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
}

/// \brief Emits the parse-arguments-in-unevaluated-context property for
/// attributes.
static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
  ParsedAttrMap Attrs = getParsedAttrList(Records);
  for (const auto &I : Attrs) {
    const Record &Attr = *I.second;

    if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
      continue;

    // All these spellings take are parsed unevaluated.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
    std::set<std::string> Emitted;
    for (const auto &S : Spellings) {
      if (Emitted.insert(S.name()).second)
        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
    }
  }
  OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
}

static bool isIdentifierArgument(Record *Arg) {
  return !Arg->getSuperClasses().empty() &&
    llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
    .Case("IdentifierArgument", true)
    .Case("EnumArgument", true)
    .Default(false);
}

// Emits the first-argument-is-identifier property for attributes.
static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (const auto *Attr : Attrs) {
    // Determine whether the first argument is an identifier.
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
    if (Args.empty() || !isIdentifierArgument(Args[0]))
      continue;

    // All these spellings take an identifier argument.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
    std::set<std::string> Emitted;
    for (const auto &S : Spellings) {
      if (Emitted.insert(S.name()).second)
        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
    }
  }
  OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
}

namespace clang {

// Emits the class definitions for attributes.
void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute classes' definitions", OS);

  OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
  OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;

    // FIXME: Currently, documentation is generated as-needed due to the fact
    // that there is no way to allow a generated project "reach into" the docs
    // directory (for instance, it may be an out-of-tree build). However, we want
    // to ensure that every attribute has a Documentation field, and produce an
    // error if it has been neglected. Otherwise, the on-demand generation which
    // happens server-side will fail. This code is ensuring that functionality,
    // even though this Emitter doesn't technically need the documentation.
    // When attribute documentation can be generated as part of the build
    // itself, this code can be removed.
    (void)R.getValueAsListOfDefs("Documentation");
    
    if (!R.getValueAsBit("ASTNode"))
      continue;
    
    const std::vector<Record *> Supers = R.getSuperClasses();
    assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
    std::string SuperName;
    for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
      const Record &R = *Super;
      if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
        SuperName = R.getName();
    }

    OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";

    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    std::vector<std::unique_ptr<Argument>> Args;
    Args.reserve(ArgRecords.size());

    for (const auto *ArgRecord : ArgRecords) {
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));
      Args.back()->writeDeclarations(OS);
      OS << "\n\n";
    }

    OS << "\npublic:\n";

    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);

    // If there are zero or one spellings, all spelling-related functionality
    // can be elided. If all of the spellings share the same name, the spelling
    // functionality can also be elided.
    bool ElideSpelling = (Spellings.size() <= 1) ||
                         SpellingNamesAreCommon(Spellings);

    // This maps spelling index values to semantic Spelling enumerants.
    SemanticSpellingMap SemanticToSyntacticMap;

    if (!ElideSpelling)
      OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);

    OS << "  static " << R.getName() << "Attr *CreateImplicit(";
    OS << "ASTContext &Ctx";
    if (!ElideSpelling)
      OS << ", Spelling S";
    for (auto const &ai : Args) {
      OS << ", ";
      ai->writeCtorParameters(OS);
    }
    OS << ", SourceRange Loc = SourceRange()";
    OS << ") {\n";
    OS << "    " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
    OS << "Attr(Loc, Ctx, ";
    for (auto const &ai : Args) {
      ai->writeImplicitCtorArgs(OS);
      OS << ", ";
    }
    OS << (ElideSpelling ? "0" : "S") << ");\n";
    OS << "    A->setImplicit(true);\n";
    OS << "    return A;\n  }\n\n";

    OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
    
    bool HasOpt = false;
    for (auto const &ai : Args) {
      OS << "              , ";
      ai->writeCtorParameters(OS);
      OS << "\n";
      if (ai->isOptional())
        HasOpt = true;
    }

    OS << "              , ";
    OS << "unsigned SI\n";

    OS << "             )\n";
    OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";

    for (auto const &ai : Args) {
      OS << "              , ";
      ai->writeCtorInitializers(OS);
      OS << "\n";
    }

    OS << "  {\n";
  
    for (auto const &ai : Args) {
      ai->writeCtorBody(OS);
      OS << "\n";
    }
    OS << "  }\n\n";

    // If there are optional arguments, write out a constructor that elides the
    // optional arguments as well.
    if (HasOpt) {
      OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
      for (auto const &ai : Args) {
        if (!ai->isOptional()) {
          OS << "              , ";
          ai->writeCtorParameters(OS);
          OS << "\n";
        }
      }

      OS << "              , ";
      OS << "unsigned SI\n";

      OS << "             )\n";
      OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";

      for (auto const &ai : Args) {
        OS << "              , ";
        ai->writeCtorDefaultInitializers(OS);
        OS << "\n";
      }

      OS << "  {\n";
  
      for (auto const &ai : Args) {
        if (!ai->isOptional()) {
          ai->writeCtorBody(OS);
          OS << "\n";
        }
      }
      OS << "  }\n\n";
    }

    OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const override;\n";
    OS << "  void printPretty(raw_ostream &OS,\n"
       << "                   const PrintingPolicy &Policy) const override;\n";
    OS << "  const char *getSpelling() const override;\n";
    
    if (!ElideSpelling) {
      assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
      OS << "  Spelling getSemanticSpelling() const {\n";
      WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
                                  OS);
      OS << "  }\n";
    }

    writeAttrAccessorDefinition(R, OS);

    for (auto const &ai : Args) {
      ai->writeAccessors(OS);
      OS << "\n\n";

      if (ai->isEnumArg())
        static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
      else if (ai->isVariadicEnumArg())
        static_cast<const VariadicEnumArgument *>(ai.get())
            ->writeConversion(OS);
    }

    OS << R.getValueAsString("AdditionalMembers");
    OS << "\n\n";

    OS << "  static bool classof(const Attr *A) { return A->getKind() == "
       << "attr::" << R.getName() << "; }\n";

    bool LateParsed = R.getValueAsBit("LateParsed");
    OS << "  bool isLateParsed() const override { return "
       << LateParsed << "; }\n";

    if (R.getValueAsBit("DuplicatesAllowedWhileMerging"))
      OS << "  bool duplicatesAllowed() const override { return true; }\n\n";

    OS << "};\n\n";
  }

  OS << "#endif\n";
}

// Emits the class method definitions for attributes.
void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute classes' member function definitions", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (auto *Attr : Attrs) {
    Record &R = *Attr;
    
    if (!R.getValueAsBit("ASTNode"))
      continue;

    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    std::vector<std::unique_ptr<Argument>> Args;
    for (const auto *Arg : ArgRecords)
      Args.emplace_back(createArgument(*Arg, R.getName()));

    for (auto const &ai : Args)
      ai->writeAccessorDefinitions(OS);

    OS << R.getName() << "Attr *" << R.getName()
       << "Attr::clone(ASTContext &C) const {\n";
    OS << "  auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
    for (auto const &ai : Args) {
      OS << ", ";
      ai->writeCloneArgs(OS);
    }
    OS << ", getSpellingListIndex());\n";
    OS << "  A->Inherited = Inherited;\n";
    OS << "  A->IsPackExpansion = IsPackExpansion;\n";
    OS << "  A->Implicit = Implicit;\n";
    OS << "  return A;\n}\n\n";

    writePrettyPrintFunction(R, Args, OS);
    writeGetSpellingFunction(R, OS);
  }
}

} // end namespace clang

static void EmitAttrList(raw_ostream &OS, StringRef Class,
                         const std::vector<Record*> &AttrList) {
  std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end();

  if (i != e) {
    // Move the end iterator back to emit the last attribute.
    for(--e; i != e; ++i) {
      if (!(*i)->getValueAsBit("ASTNode"))
        continue;
      
      OS << Class << "(" << (*i)->getName() << ")\n";
    }
    
    OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
  }
}

namespace clang {

// Emits the enumeration list for attributes.
void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);

  OS << "#ifndef LAST_ATTR\n";
  OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef INHERITABLE_ATTR\n";
  OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef LAST_INHERITABLE_ATTR\n";
  OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
  OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
  OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
        " INHERITABLE_PARAM_ATTR(NAME)\n";
  OS << "#endif\n\n";

  Record *InhClass = Records.getClass("InheritableAttr");
  Record *InhParamClass = Records.getClass("InheritableParamAttr");
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
                       NonInhAttrs, InhAttrs, InhParamAttrs;
  for (auto *Attr : Attrs) {
    if (!Attr->getValueAsBit("ASTNode"))
      continue;
    
    if (Attr->isSubClassOf(InhParamClass))
      InhParamAttrs.push_back(Attr);
    else if (Attr->isSubClassOf(InhClass))
      InhAttrs.push_back(Attr);
    else
      NonInhAttrs.push_back(Attr);
  }

  EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
  EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
  EmitAttrList(OS, "ATTR", NonInhAttrs);

  OS << "#undef LAST_ATTR\n";
  OS << "#undef INHERITABLE_ATTR\n";
  OS << "#undef LAST_INHERITABLE_ATTR\n";
  OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
  OS << "#undef ATTR\n";
}

// Emits the code to read an attribute from a precompiled header.
void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute deserialization code", OS);

  Record *InhClass = Records.getClass("InheritableAttr");
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
                       ArgRecords;
  std::vector<std::unique_ptr<Argument>> Args;

  OS << "  switch (Kind) {\n";
  OS << "  default:\n";
  OS << "    llvm_unreachable(\"Unknown attribute!\");\n";
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    
    OS << "  case attr::" << R.getName() << ": {\n";
    if (R.isSubClassOf(InhClass))
      OS << "    bool isInherited = Record[Idx++];\n";
    OS << "    bool isImplicit = Record[Idx++];\n";
    OS << "    unsigned Spelling = Record[Idx++];\n";
    ArgRecords = R.getValueAsListOfDefs("Args");
    Args.clear();
    for (const auto *Arg : ArgRecords) {
      Args.emplace_back(createArgument(*Arg, R.getName()));
      Args.back()->writePCHReadDecls(OS);
    }
    OS << "    New = new (Context) " << R.getName() << "Attr(Range, Context";
    for (auto const &ri : Args) {
      OS << ", ";
      ri->writePCHReadArgs(OS);
    }
    OS << ", Spelling);\n";
    if (R.isSubClassOf(InhClass))
      OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
    OS << "    New->setImplicit(isImplicit);\n";
    OS << "    break;\n";
    OS << "  }\n";
  }
  OS << "  }\n";
}

// Emits the code to write an attribute to a precompiled header.
void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute serialization code", OS);

  Record *InhClass = Records.getClass("InheritableAttr");
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;

  OS << "  switch (A->getKind()) {\n";
  OS << "  default:\n";
  OS << "    llvm_unreachable(\"Unknown attribute kind!\");\n";
  OS << "    break;\n";
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    OS << "  case attr::" << R.getName() << ": {\n";
    Args = R.getValueAsListOfDefs("Args");
    if (R.isSubClassOf(InhClass) || !Args.empty())
      OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
         << "Attr>(A);\n";
    if (R.isSubClassOf(InhClass))
      OS << "    Record.push_back(SA->isInherited());\n";
    OS << "    Record.push_back(A->isImplicit());\n";
    OS << "    Record.push_back(A->getSpellingListIndex());\n";

    for (const auto *Arg : Args)
      createArgument(*Arg, R.getName())->writePCHWrite(OS);
    OS << "    break;\n";
    OS << "  }\n";
  }
  OS << "  }\n";
}

static void GenerateHasAttrSpellingStringSwitch(
    const std::vector<Record *> &Attrs, raw_ostream &OS,
    const std::string &Variety = "", const std::string &Scope = "") {
  for (const auto *Attr : Attrs) {
    // It is assumed that there will be an llvm::Triple object named T within
    // scope that can be used to determine whether the attribute exists in
    // a given target.
    std::string Test;
    if (Attr->isSubClassOf("TargetSpecificAttr")) {
      const Record *R = Attr->getValueAsDef("Target");
      std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");

      Test += "(";
      for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) {
        std::string Part = *AI;
        Test += "T.getArch() == llvm::Triple::" + Part;
        if (AI + 1 != AE)
          Test += " || ";
      }
      Test += ")";

      std::vector<std::string> OSes;
      if (!R->isValueUnset("OSes")) {
        Test += " && (";
        std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
        for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) {
          std::string Part = *AI;

          Test += "T.getOS() == llvm::Triple::" + Part;
          if (AI + 1 != AE)
            Test += " || ";
        }
        Test += ")";
      }
      
      // If this is the C++11 variety, also add in the LangOpts test.
      if (Variety == "CXX11")
        Test += " && LangOpts.CPlusPlus11";
    } else if (Variety == "CXX11")
      // C++11 mode should be checked against LangOpts, which is presumed to be
      // present in the caller.
      Test = "LangOpts.CPlusPlus11";
    else
      Test = "true";

    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
    for (const auto &S : Spellings)
      if (Variety.empty() || (Variety == S.variety() &&
                              (Scope.empty() || Scope == S.nameSpace())))
        OS << "    .Case(\"" << S.name() << "\", " << Test << ")\n";
  }
  OS << "    .Default(false);\n";
}

// Emits the list of spellings for attributes.
void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Code to implement the __has_attribute logic", OS);

  // Separate all of the attributes out into four group: generic, C++11, GNU,
  // and declspecs. Then generate a big switch statement for each of them.
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<Record *> Declspec, GNU, Pragma;
  std::map<std::string, std::vector<Record *>> CXX;

  // Walk over the list of all attributes, and split them out based on the
  // spelling variety.
  for (auto *R : Attrs) {
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
    for (const auto &SI : Spellings) {
      std::string Variety = SI.variety();
      if (Variety == "GNU")
        GNU.push_back(R);
      else if (Variety == "Declspec")
        Declspec.push_back(R);
      else if (Variety == "CXX11")
        CXX[SI.nameSpace()].push_back(R);
      else if (Variety == "Pragma")
        Pragma.push_back(R);
    }
  }

  OS << "switch (Syntax) {\n";
  OS << "case AttrSyntax::Generic:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Attrs, OS);
  OS << "case AttrSyntax::GNU:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
  OS << "case AttrSyntax::Declspec:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
  OS << "case AttrSyntax::Pragma:\n";
  OS << "  return llvm::StringSwitch<bool>(Name)\n";
  GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
  OS << "case AttrSyntax::CXX: {\n";
  // C++11-style attributes are further split out based on the Scope.
  for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(),
                                                              E = CXX.end();
       I != E; ++I) {
    if (I != CXX.begin())
      OS << " else ";
    if (I->first.empty())
      OS << "if (!Scope || Scope->getName() == \"\") {\n";
    else
      OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
    OS << "  return llvm::StringSwitch<bool>(Name)\n";
    GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
    OS << "}";
  }
  OS << "\n}\n";
  OS << "}\n";
}

void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Code to translate different attribute spellings "
                       "into internal identifiers", OS);

  OS <<
    "  switch (AttrKind) {\n"
    "  default:\n"
    "    llvm_unreachable(\"Unknown attribute kind!\");\n"
    "    break;\n";

  ParsedAttrMap Attrs = getParsedAttrList(Records);
  for (const auto &I : Attrs) {
    const Record &R = *I.second;
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
    OS << "  case AT_" << I.first << ": {\n";
    for (unsigned I = 0; I < Spellings.size(); ++ I) {
      OS << "    if (Name == \"" << Spellings[I].name() << "\" && "
         << "SyntaxUsed == "
         << StringSwitch<unsigned>(Spellings[I].variety())
                .Case("GNU", 0)
                .Case("CXX11", 1)
                .Case("Declspec", 2)
                .Case("Keyword", 3)
                .Case("Pragma", 4)
                .Default(0)
         << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
         << "        return " << I << ";\n";
    }

    OS << "    break;\n";
    OS << "  }\n";
  }

  OS << "  }\n";
  OS << "  return 0;\n";
}

// Emits code used by RecursiveASTVisitor to visit attributes
void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  // Write method declarations for Traverse* methods.
  // We emit this here because we only generate methods for attributes that
  // are declared as ASTNodes.
  OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    OS << "  bool Traverse"
       << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
    OS << "  bool Visit"
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
       << "    return true; \n"
       << "  };\n";
  }
  OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";

  // Write individual Traverse* methods for each attribute class.
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
    if (!R.getValueAsBit("ASTNode"))
      continue;

    OS << "template <typename Derived>\n"
       << "bool VISITORCLASS<Derived>::Traverse"
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
       << "  if (!getDerived().VisitAttr(A))\n"
       << "    return false;\n"
       << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
       << "    return false;\n";

    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    for (const auto *Arg : ArgRecords)
      createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);

    OS << "  return true;\n";
    OS << "}\n\n";
  }

  // Write generic Traverse routine
  OS << "template <typename Derived>\n"
     << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
     << "  if (!A)\n"
     << "    return true;\n"
     << "\n"
     << "  switch (A->getKind()) {\n"
     << "    default:\n"
     << "      return true;\n";

  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
    if (!R.getValueAsBit("ASTNode"))
      continue;

    OS << "    case attr::" << R.getName() << ":\n"
       << "      return getDerived().Traverse" << R.getName() << "Attr("
       << "cast<" << R.getName() << "Attr>(A));\n";
  }
  OS << "  }\n";  // end case
  OS << "}\n";  // end function
  OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
}

// Emits code to instantiate dependent attributes on templates.
void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Template instantiation code for attributes", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  OS << "namespace clang {\n"
     << "namespace sema {\n\n"
     << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
     << "Sema &S,\n"
     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
     << "  switch (At->getKind()) {\n"
     << "    default:\n"
     << "      break;\n";

  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
    if (!R.getValueAsBit("ASTNode"))
      continue;

    OS << "    case attr::" << R.getName() << ": {\n";
    bool ShouldClone = R.getValueAsBit("Clone");

    if (!ShouldClone) {
      OS << "      return NULL;\n";
      OS << "    }\n";
      continue;
    }

    OS << "      const " << R.getName() << "Attr *A = cast<"
       << R.getName() << "Attr>(At);\n";
    bool TDependent = R.getValueAsBit("TemplateDependent");

    if (!TDependent) {
      OS << "      return A->clone(C);\n";
      OS << "    }\n";
      continue;
    }

    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    std::vector<std::unique_ptr<Argument>> Args;
    Args.reserve(ArgRecords.size());

    for (const auto *ArgRecord : ArgRecords)
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));

    for (auto const &ai : Args)
      ai->writeTemplateInstantiation(OS);

    OS << "      return new (C) " << R.getName() << "Attr(A->getLocation(), C";
    for (auto const &ai : Args) {
      OS << ", ";
      ai->writeTemplateInstantiationArgs(OS);
    }
    OS << ", A->getSpellingListIndex());\n    }\n";
  }
  OS << "  } // end switch\n"
     << "  llvm_unreachable(\"Unknown attribute!\");\n"
     << "  return 0;\n"
     << "}\n\n"
     << "} // end namespace sema\n"
     << "} // end namespace clang\n";
}

// Emits the list of parsed attributes.
void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);

  OS << "#ifndef PARSED_ATTR\n";
  OS << "#define PARSED_ATTR(NAME) NAME\n";
  OS << "#endif\n\n";
  
  ParsedAttrMap Names = getParsedAttrList(Records);
  for (const auto &I : Names) {
    OS << "PARSED_ATTR(" << I.first << ")\n";
  }
}

static bool isArgVariadic(const Record &R, StringRef AttrName) {
  return createArgument(R, AttrName)->isVariadic();
}

static void emitArgInfo(const Record &R, std::stringstream &OS) {
  // This function will count the number of arguments specified for the
  // attribute and emit the number of required arguments followed by the
  // number of optional arguments.
  std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
  unsigned ArgCount = 0, OptCount = 0;
  bool HasVariadic = false;
  for (const auto *Arg : Args) {
    Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
    if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
      HasVariadic = true;
  }

  // If there is a variadic argument, we will set the optional argument count
  // to its largest value. Since it's currently a 4-bit number, we set it to 15.
  OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
}

static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
  OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
  OS << "const Decl *) {\n";
  OS << "  return true;\n";
  OS << "}\n\n";
}

static std::string CalculateDiagnostic(const Record &S) {
  // If the SubjectList object has a custom diagnostic associated with it,
  // return that directly.
  std::string CustomDiag = S.getValueAsString("CustomDiag");
  if (!CustomDiag.empty())
    return CustomDiag;

  // Given the list of subjects, determine what diagnostic best fits.
  enum {
    Func = 1U << 0,
    Var = 1U << 1,
    ObjCMethod = 1U << 2,
    Param = 1U << 3,
    Class = 1U << 4,
    GenericRecord = 1U << 5,
    Type = 1U << 6,
    ObjCIVar = 1U << 7,
    ObjCProp = 1U << 8,
    ObjCInterface = 1U << 9,
    Block = 1U << 10,
    Namespace = 1U << 11,
    Field = 1U << 12,
    CXXMethod = 1U << 13,
    ObjCProtocol = 1U << 14
  };
  uint32_t SubMask = 0;

  std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
  for (const auto *Subject : Subjects) {
    const Record &R = *Subject;
    std::string Name;

    if (R.isSubClassOf("SubsetSubject")) {
      PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
      // As a fallback, look through the SubsetSubject to see what its base
      // type is, and use that. This needs to be updated if SubsetSubjects
      // are allowed within other SubsetSubjects.
      Name = R.getValueAsDef("Base")->getName();
    } else
      Name = R.getName();

    uint32_t V = StringSwitch<uint32_t>(Name)
                   .Case("Function", Func)
                   .Case("Var", Var)
                   .Case("ObjCMethod", ObjCMethod)
                   .Case("ParmVar", Param)
                   .Case("TypedefName", Type)
                   .Case("ObjCIvar", ObjCIVar)
                   .Case("ObjCProperty", ObjCProp)
                   .Case("Record", GenericRecord)
                   .Case("ObjCInterface", ObjCInterface)
                   .Case("ObjCProtocol", ObjCProtocol)
                   .Case("Block", Block)
                   .Case("CXXRecord", Class)
                   .Case("Namespace", Namespace)
                   .Case("Field", Field)
                   .Case("CXXMethod", CXXMethod)
                   .Default(0);
    if (!V) {
      // Something wasn't in our mapping, so be helpful and let the developer
      // know about it.
      PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
      return "";
    }

    SubMask |= V;
  }

  switch (SubMask) {
    // For the simple cases where there's only a single entry in the mask, we
    // don't have to resort to bit fiddling.
    case Func:  return "ExpectedFunction";
    case Var:   return "ExpectedVariable";
    case Param: return "ExpectedParameter";
    case Class: return "ExpectedClass";
    case CXXMethod:
      // FIXME: Currently, this maps to ExpectedMethod based on existing code,
      // but should map to something a bit more accurate at some point.
    case ObjCMethod:  return "ExpectedMethod";
    case Type:  return "ExpectedType";
    case ObjCInterface: return "ExpectedObjectiveCInterface";
    case ObjCProtocol: return "ExpectedObjectiveCProtocol";
    
    // "GenericRecord" means struct, union or class; check the language options
    // and if not compiling for C++, strip off the class part. Note that this
    // relies on the fact that the context for this declares "Sema &S".
    case GenericRecord:
      return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
                                           "ExpectedStructOrUnion)";
    case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
    case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
    case Func | Param:
    case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
    case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
    case Func | Var: return "ExpectedVariableOrFunction";

    // If not compiling for C++, the class portion does not apply.
    case Func | Var | Class:
      return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
                                           "ExpectedVariableOrFunction)";

    case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
    case ObjCProtocol | ObjCInterface:
      return "ExpectedObjectiveCInterfaceOrProtocol";
    case Field | Var: return "ExpectedFieldOrGlobalVar";
  }

  PrintFatalError(S.getLoc(),
                  "Could not deduce diagnostic argument for Attr subjects");

  return "";
}

static std::string GetSubjectWithSuffix(const Record *R) {
  std::string B = R->getName();
  if (B == "DeclBase")
    return "Decl";
  return B + "Decl";
}
static std::string GenerateCustomAppertainsTo(const Record &Subject,
                                              raw_ostream &OS) {
  std::string FnName = "is" + Subject.getName();

  // If this code has already been generated, simply return the previous
  // instance of it.
  static std::set<std::string> CustomSubjectSet;
  std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
  if (I != CustomSubjectSet.end())
    return *I;

  Record *Base = Subject.getValueAsDef("Base");

  // Not currently support custom subjects within custom subjects.
  if (Base->isSubClassOf("SubsetSubject")) {
    PrintFatalError(Subject.getLoc(),
                    "SubsetSubjects within SubsetSubjects is not supported");
    return "";
  }

  OS << "static bool " << FnName << "(const Decl *D) {\n";
  OS << "  if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
  OS << GetSubjectWithSuffix(Base);
  OS << ">(D))\n";
  OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
  OS << "  return false;\n";
  OS << "}\n\n";

  CustomSubjectSet.insert(FnName);
  return FnName;
}

static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
  // If the attribute does not contain a Subjects definition, then use the
  // default appertainsTo logic.
  if (Attr.isValueUnset("Subjects"))
    return "defaultAppertainsTo";

  const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");

  // If the list of subjects is empty, it is assumed that the attribute
  // appertains to everything.
  if (Subjects.empty())
    return "defaultAppertainsTo";

  bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");

  // Otherwise, generate an appertainsTo check specific to this attribute which
  // checks all of the given subjects against the Decl passed in. Return the
  // name of that check to the caller.
  std::string FnName = "check" + Attr.getName() + "AppertainsTo";
  std::stringstream SS;
  SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
  SS << "const Decl *D) {\n";
  SS << "  if (";
  for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
    // If the subject has custom code associated with it, generate a function
    // for it. The function cannot be inlined into this check (yet) because it
    // requires the subject to be of a specific type, and were that information
    // inlined here, it would not support an attribute with multiple custom
    // subjects.
    if ((*I)->isSubClassOf("SubsetSubject")) {
      SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
    } else {
      SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
    }

    if (I + 1 != E)
      SS << " && ";
  }
  SS << ") {\n";
  SS << "    S.Diag(Attr.getLoc(), diag::";
  SS << (Warn ? "warn_attribute_wrong_decl_type" :
               "err_attribute_wrong_decl_type");
  SS << ")\n";
  SS << "      << Attr.getName() << ";
  SS << CalculateDiagnostic(*SubjectObj) << ";\n";
  SS << "    return false;\n";
  SS << "  }\n";
  SS << "  return true;\n";
  SS << "}\n\n";

  OS << SS.str();
  return FnName;
}

static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
  OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
  OS << "const AttributeList &) {\n";
  OS << "  return true;\n";
  OS << "}\n\n";
}

static std::string GenerateLangOptRequirements(const Record &R,
                                               raw_ostream &OS) {
  // If the attribute has an empty or unset list of language requirements,
  // return the default handler.
  std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
  if (LangOpts.empty())
    return "defaultDiagnoseLangOpts";

  // Generate the test condition, as well as a unique function name for the
  // diagnostic test. The list of options should usually be short (one or two
  // options), and the uniqueness isn't strictly necessary (it is just for
  // codegen efficiency).
  std::string FnName = "check", Test;
  for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
    std::string Part = (*I)->getValueAsString("Name");
    Test += "S.LangOpts." + Part;
    if (I + 1 != E)
      Test += " || ";
    FnName += Part;
  }
  FnName += "LangOpts";

  // If this code has already been generated, simply return the previous
  // instance of it.
  static std::set<std::string> CustomLangOptsSet;
  std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
  if (I != CustomLangOptsSet.end())
    return *I;

  OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
  OS << "  if (" << Test << ")\n";
  OS << "    return true;\n\n";
  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
  OS << "<< Attr.getName();\n";
  OS << "  return false;\n";
  OS << "}\n\n";

  CustomLangOptsSet.insert(FnName);
  return FnName;
}

static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
  OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n";
  OS << "  return true;\n";
  OS << "}\n\n";
}

static std::string GenerateTargetRequirements(const Record &Attr,
                                              const ParsedAttrMap &Dupes,
                                              raw_ostream &OS) {
  // If the attribute is not a target specific attribute, return the default
  // target handler.
  if (!Attr.isSubClassOf("TargetSpecificAttr"))
    return "defaultTargetRequirements";

  // Get the list of architectures to be tested for.
  const Record *R = Attr.getValueAsDef("Target");
  std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
  if (Arches.empty()) {
    PrintError(Attr.getLoc(), "Empty list of target architectures for a "
                              "target-specific attr");
    return "defaultTargetRequirements";
  }

  // If there are other attributes which share the same parsed attribute kind,
  // such as target-specific attributes with a shared spelling, collapse the
  // duplicate architectures. This is required because a shared target-specific
  // attribute has only one AttributeList::Kind enumeration value, but it
  // applies to multiple target architectures. In order for the attribute to be
  // considered valid, all of its architectures need to be included.
  if (!Attr.isValueUnset("ParseKind")) {
    std::string APK = Attr.getValueAsString("ParseKind");
    for (const auto &I : Dupes) {
      if (I.first == APK) {
        std::vector<std::string> DA = I.second->getValueAsDef("Target")
                                          ->getValueAsListOfStrings("Arches");
        std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
      }
    }
  }

  std::string FnName = "isTarget", Test = "(";
  for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
    std::string Part = *I;
    Test += "Arch == llvm::Triple::" + Part;
    if (I + 1 != E)
      Test += " || ";
    FnName += Part;
  }
  Test += ")";

  // If the target also requires OS testing, generate those tests as well.
  bool UsesOS = false;
  if (!R->isValueUnset("OSes")) {
    UsesOS = true;
    
    // We know that there was at least one arch test, so we need to and in the
    // OS tests.
    Test += " && (";
    std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
    for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
      std::string Part = *I;

      Test += "OS == llvm::Triple::" + Part;
      if (I + 1 != E)
        Test += " || ";
      FnName += Part;
    }
    Test += ")";
  }

  // If this code has already been generated, simply return the previous
  // instance of it.
  static std::set<std::string> CustomTargetSet;
  std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
  if (I != CustomTargetSet.end())
    return *I;

  OS << "static bool " << FnName << "(const llvm::Triple &T) {\n";
  OS << "  llvm::Triple::ArchType Arch = T.getArch();\n";
  if (UsesOS)
    OS << "  llvm::Triple::OSType OS = T.getOS();\n";
  OS << "  return " << Test << ";\n";
  OS << "}\n\n";

  CustomTargetSet.insert(FnName);
  return FnName;
}

static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
  OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
     << "const AttributeList &Attr) {\n";
  OS << "  return UINT_MAX;\n";
  OS << "}\n\n";
}

static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
                                                           raw_ostream &OS) {
  // If the attribute does not have a semantic form, we can bail out early.
  if (!Attr.getValueAsBit("ASTNode"))
    return "defaultSpellingIndexToSemanticSpelling";

  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);

  // If there are zero or one spellings, or all of the spellings share the same
  // name, we can also bail out early.
  if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
    return "defaultSpellingIndexToSemanticSpelling";

  // Generate the enumeration we will use for the mapping.
  SemanticSpellingMap SemanticToSyntacticMap;
  std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
  std::string Name = Attr.getName() + "AttrSpellingMap";

  OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
  OS << Enum;
  OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
  WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
  OS << "}\n\n";

  return Name;
}

static bool IsKnownToGCC(const Record &Attr) {
  // Look at the spellings for this subject; if there are any spellings which
  // claim to be known to GCC, the attribute is known to GCC.
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  for (const auto &I : Spellings) {
    if (I.knownToGCC())
      return true;
  }
  return false;
}

/// Emits the parsed attribute helpers
void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Parsed attribute helpers", OS);

  // Get the list of parsed attributes, and accept the optional list of
  // duplicates due to the ParseKind.
  ParsedAttrMap Dupes;
  ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);

  // Generate the default appertainsTo, target and language option diagnostic,
  // and spelling list index mapping methods.
  GenerateDefaultAppertainsTo(OS);
  GenerateDefaultLangOptRequirements(OS);
  GenerateDefaultTargetRequirements(OS);
  GenerateDefaultSpellingIndexToSemanticSpelling(OS);

  // Generate the appertainsTo diagnostic methods and write their names into
  // another mapping. At the same time, generate the AttrInfoMap object
  // contents. Due to the reliance on generated code, use separate streams so
  // that code will not be interleaved.
  std::stringstream SS;
  for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
    // TODO: If the attribute's kind appears in the list of duplicates, that is
    // because it is a target-specific attribute that appears multiple times.
    // It would be beneficial to test whether the duplicates are "similar
    // enough" to each other to not cause problems. For instance, check that
    // the spellings are identical, and custom parsing rules match, etc.

    // We need to generate struct instances based off ParsedAttrInfo from
    // AttributeList.cpp.
    SS << "  { ";
    emitArgInfo(*I->second, SS);
    SS << ", " << I->second->getValueAsBit("HasCustomParsing");
    SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
    SS << ", " << I->second->isSubClassOf("TypeAttr");
    SS << ", " << IsKnownToGCC(*I->second);
    SS << ", " << GenerateAppertainsTo(*I->second, OS);
    SS << ", " << GenerateLangOptRequirements(*I->second, OS);
    SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
    SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
    SS << " }";

    if (I + 1 != E)
      SS << ",";

    SS << "  // AT_" << I->first << "\n";
  }

  OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
  OS << SS.str();
  OS << "};\n\n";
}

// Emits the kind list of parsed attributes
void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute name matcher", OS);

  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma;
  std::set<std::string> Seen;
  for (const auto *A : Attrs) {
    const Record &Attr = *A;

    bool SemaHandler = Attr.getValueAsBit("SemaHandler");
    bool Ignored = Attr.getValueAsBit("Ignored");
    if (SemaHandler || Ignored) {
      // Attribute spellings can be shared between target-specific attributes,
      // and can be shared between syntaxes for the same attribute. For
      // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
      // specific attribute, or MSP430-specific attribute. Additionally, an
      // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
      // for the same semantic attribute. Ultimately, we need to map each of
      // these to a single AttributeList::Kind value, but the StringMatcher
      // class cannot handle duplicate match strings. So we generate a list of
      // string to match based on the syntax, and emit multiple string matchers
      // depending on the syntax used.
      std::string AttrName;
      if (Attr.isSubClassOf("TargetSpecificAttr") &&
          !Attr.isValueUnset("ParseKind")) {
        AttrName = Attr.getValueAsString("ParseKind");
        if (Seen.find(AttrName) != Seen.end())
          continue;
        Seen.insert(AttrName);
      } else
        AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();

      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
      for (const auto &S : Spellings) {
        std::string RawSpelling = S.name();
        std::vector<StringMatcher::StringPair> *Matches = nullptr;
        std::string Spelling, Variety = S.variety();
        if (Variety == "CXX11") {
          Matches = &CXX11;
          Spelling += S.nameSpace();
          Spelling += "::";
        } else if (Variety == "GNU")
          Matches = &GNU;
        else if (Variety == "Declspec")
          Matches = &Declspec;
        else if (Variety == "Keyword")
          Matches = &Keywords;
        else if (Variety == "Pragma")
          Matches = &Pragma;

        assert(Matches && "Unsupported spelling variety found");

        Spelling += NormalizeAttrSpelling(RawSpelling);
        if (SemaHandler)
          Matches->push_back(StringMatcher::StringPair(Spelling,
                              "return AttributeList::AT_" + AttrName + ";"));
        else
          Matches->push_back(StringMatcher::StringPair(Spelling,
                              "return AttributeList::IgnoredAttribute;"));
      }
    }
  }
  
  OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
  OS << "AttributeList::Syntax Syntax) {\n";
  OS << "  if (AttributeList::AS_GNU == Syntax) {\n";
  StringMatcher("Name", GNU, OS).Emit();
  OS << "  } else if (AttributeList::AS_Declspec == Syntax) {\n";
  StringMatcher("Name", Declspec, OS).Emit();
  OS << "  } else if (AttributeList::AS_CXX11 == Syntax) {\n";
  StringMatcher("Name", CXX11, OS).Emit();
  OS << "  } else if (AttributeList::AS_Keyword == Syntax) {\n";
  StringMatcher("Name", Keywords, OS).Emit();
  OS << "  } else if (AttributeList::AS_Pragma == Syntax) {\n";
  StringMatcher("Name", Pragma, OS).Emit();
  OS << "  }\n";
  OS << "  return AttributeList::UnknownAttribute;\n"
     << "}\n";
}

// Emits the code to dump an attribute.
void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute dumper", OS);

  OS <<
    "  switch (A->getKind()) {\n"
    "  default:\n"
    "    llvm_unreachable(\"Unknown attribute kind!\");\n"
    "    break;\n";
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  for (const auto *Attr : Attrs) {
    const Record &R = *Attr;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    OS << "  case attr::" << R.getName() << ": {\n";

    // If the attribute has a semantically-meaningful name (which is determined
    // by whether there is a Spelling enumeration for it), then write out the
    // spelling used for the attribute.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
    if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
      OS << "    OS << \" \" << A->getSpelling();\n";

    Args = R.getValueAsListOfDefs("Args");
    if (!Args.empty()) {
      OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
         << "Attr>(A);\n";
      for (const auto *Arg : Args)
        createArgument(*Arg, R.getName())->writeDump(OS);

      // Code for detecting the last child.
      OS << "    bool OldMoreChildren = hasMoreChildren();\n";
      OS << "    bool MoreChildren;\n";

      for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI) {
        // More code for detecting the last child.
        OS << "    MoreChildren = OldMoreChildren";
        for (auto Next = AI + 1; Next != AE; ++Next) {
          OS << " || ";
          createArgument(**Next, R.getName())->writeHasChildren(OS);
        }
        OS << ";\n";
        OS << "    setMoreChildren(MoreChildren);\n";

        createArgument(**AI, R.getName())->writeDumpChildren(OS);
      }

      // Reset the last child.
      OS << "    setMoreChildren(OldMoreChildren);\n";
    }
    OS <<
      "    break;\n"
      "  }\n";
  }
  OS << "  }\n";
}

void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
                                       raw_ostream &OS) {
  emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
  emitClangAttrArgContextList(Records, OS);
  emitClangAttrIdentifierArgList(Records, OS);
  emitClangAttrTypeArgList(Records, OS);
  emitClangAttrLateParsedList(Records, OS);
}

class DocumentationData {
public:
  const Record *Documentation;
  const Record *Attribute;

  DocumentationData(const Record &Documentation, const Record &Attribute)
      : Documentation(&Documentation), Attribute(&Attribute) {}
};

static void WriteCategoryHeader(const Record *DocCategory,
                                raw_ostream &OS) {
  const std::string &Name = DocCategory->getValueAsString("Name");
  OS << Name << "\n" << std::string(Name.length(), '=') << "\n";

  // If there is content, print that as well.
  std::string ContentStr = DocCategory->getValueAsString("Content");
  if (!ContentStr.empty()) {
    // Trim leading and trailing newlines and spaces.
    StringRef Content(ContentStr);
    while (Content.startswith("\r") || Content.startswith("\n") ||
           Content.startswith(" ") || Content.startswith("\t"))
           Content = Content.substr(1);
    while (Content.endswith("\r") || Content.endswith("\n") ||
           Content.endswith(" ") || Content.endswith("\t"))
           Content = Content.substr(0, Content.size() - 1);
    OS << Content;
  }
  OS << "\n\n";
}

enum SpellingKind {
  GNU = 1 << 0,
  CXX11 = 1 << 1,
  Declspec = 1 << 2,
  Keyword = 1 << 3,
  Pragma = 1 << 4
};

static void WriteDocumentation(const DocumentationData &Doc,
                               raw_ostream &OS) {
  // FIXME: there is no way to have a per-spelling category for the attribute
  // documentation. This may not be a limiting factor since the spellings
  // should generally be consistently applied across the category.

  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);

  // Determine the heading to be used for this attribute.
  std::string Heading = Doc.Documentation->getValueAsString("Heading");
  bool CustomHeading = !Heading.empty();
  if (Heading.empty()) {
    // If there's only one spelling, we can simply use that.
    if (Spellings.size() == 1)
      Heading = Spellings.begin()->name();
    else {
      std::set<std::string> Uniques;
      for (auto I = Spellings.begin(), E = Spellings.end();
           I != E && Uniques.size() <= 1; ++I) {
        std::string Spelling = NormalizeNameForSpellingComparison(I->name());
        Uniques.insert(Spelling);
      }
      // If the semantic map has only one spelling, that is sufficient for our
      // needs.
      if (Uniques.size() == 1)
        Heading = *Uniques.begin();
    }
  }

  // If the heading is still empty, it is an error.
  if (Heading.empty())
    PrintFatalError(Doc.Attribute->getLoc(),
                    "This attribute requires a heading to be specified");

  // Gather a list of unique spellings; this is not the same as the semantic
  // spelling for the attribute. Variations in underscores and other non-
  // semantic characters are still acceptable.
  std::vector<std::string> Names;

  unsigned SupportedSpellings = 0;
  for (const auto &I : Spellings) {
    SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
                            .Case("GNU", GNU)
                            .Case("CXX11", CXX11)
                            .Case("Declspec", Declspec)
                            .Case("Keyword", Keyword)
                            .Case("Pragma", Pragma);

    // Mask in the supported spelling.
    SupportedSpellings |= Kind;

    std::string Name;
    if (Kind == CXX11 && !I.nameSpace().empty())
      Name = I.nameSpace() + "::";
    Name += I.name();

    // If this name is the same as the heading, do not add it.
    if (Name != Heading)
      Names.push_back(Name);
  }

  // Print out the heading for the attribute. If there are alternate spellings,
  // then display those after the heading.
  if (!CustomHeading && !Names.empty()) {
    Heading += " (";
    for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
      if (I != Names.begin())
        Heading += ", ";
      Heading += *I;
    }
    Heading += ")";
  }
  OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";

  if (!SupportedSpellings)
    PrintFatalError(Doc.Attribute->getLoc(),
                    "Attribute has no supported spellings; cannot be "
                    "documented");

  // List what spelling syntaxes the attribute supports.
  OS << ".. csv-table:: Supported Syntaxes\n";
  OS << "   :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
  OS << " \"Pragma\"\n\n";
  OS << "   \"";
  if (SupportedSpellings & GNU) OS << "X";
  OS << "\",\"";
  if (SupportedSpellings & CXX11) OS << "X";
  OS << "\",\"";
  if (SupportedSpellings & Declspec) OS << "X";
  OS << "\",\"";
  if (SupportedSpellings & Keyword) OS << "X";
  OS << "\", \"";
  if (SupportedSpellings & Pragma) OS << "X";
  OS << "\"\n\n";

  // If the attribute is deprecated, print a message about it, and possibly
  // provide a replacement attribute.
  if (!Doc.Documentation->isValueUnset("Deprecated")) {
    OS << "This attribute has been deprecated, and may be removed in a future "
       << "version of Clang.";
    const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
    std::string Replacement = Deprecated.getValueAsString("Replacement");
    if (!Replacement.empty())
      OS << "  This attribute has been superseded by ``"
         << Replacement << "``.";
    OS << "\n\n";
  }

  std::string ContentStr = Doc.Documentation->getValueAsString("Content");
  // Trim leading and trailing newlines and spaces.
  StringRef Content(ContentStr);
  while (Content.startswith("\r") || Content.startswith("\n") ||
         Content.startswith(" ") || Content.startswith("\t"))
    Content = Content.substr(1);
  while (Content.endswith("\r") || Content.endswith("\n") ||
         Content.endswith(" ") || Content.endswith("\t"))
    Content = Content.substr(0, Content.size() - 1);
  OS << Content;

  OS << "\n\n\n";
}

void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
  // Get the documentation introduction paragraph.
  const Record *Documentation = Records.getDef("GlobalDocumentation");
  if (!Documentation) {
    PrintFatalError("The Documentation top-level definition is missing, "
                    "no documentation will be generated.");
    return;
  }

  OS << Documentation->getValueAsString("Intro") << "\n";

  // Gather the Documentation lists from each of the attributes, based on the
  // category provided.
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
  for (const auto *A : Attrs) {
    const Record &Attr = *A;
    std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
    for (const auto *D : Docs) {
      const Record &Doc = *D;
      const Record *Category = Doc.getValueAsDef("Category");
      // If the category is "undocumented", then there cannot be any other
      // documentation categories (otherwise, the attribute would become
      // documented).
      std::string Cat = Category->getValueAsString("Name");
      bool Undocumented = Cat == "Undocumented";
      if (Undocumented && Docs.size() > 1)
        PrintFatalError(Doc.getLoc(),
                        "Attribute is \"Undocumented\", but has multiple "
                        "documentation categories");      

      if (!Undocumented)
        SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
    }
  }

  // Having split the attributes out based on what documentation goes where,
  // we can begin to generate sections of documentation.
  for (const auto &I : SplitDocs) {
    WriteCategoryHeader(I.first, OS);

    // Walk over each of the attributes in the category and write out their
    // documentation.
    for (const auto &Doc : I.second)
      WriteDocumentation(Doc, OS);
  }
}

} // end namespace clang
@


1.1.1.5.4.1
log
@file ClangAttrEmitter.cpp was added on branch yamt-pagecache on 2014-05-22 16:19:50 +0000
@
text
@d1 2861
@


1.1.1.5.4.2
log
@sync with head.

for a reference, the tree before this commit was tagged
as yamt-pagecache-tag8.

this commit was splitted into small chunks to avoid
a limitation of cvs.  ("Protocol error: too many arguments")
@
text
@a0 2861
//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang attribute processing code
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/StringMatcher.h"
#include "llvm/TableGen/TableGenBackend.h"
#include <algorithm>
#include <cctype>
#include <set>
#include <sstream>

using namespace llvm;

class FlattenedSpelling {
  std::string V, N, NS;
  bool K;

public:
  FlattenedSpelling(const std::string &Variety, const std::string &Name,
                    const std::string &Namespace, bool KnownToGCC) :
    V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
  explicit FlattenedSpelling(const Record &Spelling) :
    V(Spelling.getValueAsString("Variety")),
    N(Spelling.getValueAsString("Name")) {

    assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
           "flattened!");
    if (V == "CXX11")
      NS = Spelling.getValueAsString("Namespace");
    bool Unset;
    K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
  }

  const std::string &variety() const { return V; }
  const std::string &name() const { return N; }
  const std::string &nameSpace() const { return NS; }
  bool knownToGCC() const { return K; }
};

std::vector<FlattenedSpelling> GetFlattenedSpellings(const Record &Attr) {
  std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
  std::vector<FlattenedSpelling> Ret;

  for (std::vector<Record *>::const_iterator I = Spellings.begin(),
       E = Spellings.end(); I != E; ++I) {
    const Record &Spelling = **I;

    if (Spelling.getValueAsString("Variety") == "GCC") {
      // Gin up two new spelling objects to add into the list.
      Ret.push_back(FlattenedSpelling("GNU", Spelling.getValueAsString("Name"),
                                      "", true));
      Ret.push_back(FlattenedSpelling("CXX11",
                                      Spelling.getValueAsString("Name"),
                                      "gnu", true));
    } else
      Ret.push_back(FlattenedSpelling(Spelling));
  }

  return Ret;
}

static std::string ReadPCHRecord(StringRef type) {
  return StringSwitch<std::string>(type)
    .EndsWith("Decl *", "GetLocalDeclAs<" 
              + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
    .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
    .Case("Expr *", "ReadExpr(F)")
    .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
    .Default("Record[Idx++]");
}

// Assumes that the way to get the value is SA->getname()
static std::string WritePCHRecord(StringRef type, StringRef name) {
  return StringSwitch<std::string>(type)
    .EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
                        ", Record);\n")
    .Case("TypeSourceInfo *",
          "AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
    .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
    .Case("IdentifierInfo *", 
          "AddIdentifierRef(" + std::string(name) + ", Record);\n")
    .Default("Record.push_back(" + std::string(name) + ");\n");
}

// Normalize attribute name by removing leading and trailing
// underscores. For example, __foo, foo__, __foo__ would
// become foo.
static StringRef NormalizeAttrName(StringRef AttrName) {
  if (AttrName.startswith("__"))
    AttrName = AttrName.substr(2, AttrName.size());

  if (AttrName.endswith("__"))
    AttrName = AttrName.substr(0, AttrName.size() - 2);

  return AttrName;
}

// Normalize the name by removing any and all leading and trailing underscores.
// This is different from NormalizeAttrName in that it also handles names like
// _pascal and __pascal.
static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
  while (Name.startswith("_"))
    Name = Name.substr(1, Name.size());
  while (Name.endswith("_"))
    Name = Name.substr(0, Name.size() - 1);
  return Name;
}

// Normalize attribute spelling only if the spelling has both leading
// and trailing underscores. For example, __ms_struct__ will be 
// normalized to "ms_struct"; __cdecl will remain intact.
static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
  if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
    AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
  }

  return AttrSpelling;
}

typedef std::vector<std::pair<std::string, Record *> > ParsedAttrMap;

static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
                                       ParsedAttrMap *Dupes = 0) {
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::set<std::string> Seen;
  ParsedAttrMap R;
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;
    if (Attr.getValueAsBit("SemaHandler")) {
      std::string AN;
      if (Attr.isSubClassOf("TargetSpecificAttr") &&
          !Attr.isValueUnset("ParseKind")) {
        AN = Attr.getValueAsString("ParseKind");

        // If this attribute has already been handled, it does not need to be
        // handled again.
        if (Seen.find(AN) != Seen.end()) {
          if (Dupes)
            Dupes->push_back(std::make_pair(AN, *I));
          continue;
        }
        Seen.insert(AN);
      } else
        AN = NormalizeAttrName(Attr.getName()).str();

      R.push_back(std::make_pair(AN, *I));
    }
  }
  return R;
}

namespace {
  class Argument {
    std::string lowerName, upperName;
    StringRef attrName;
    bool isOpt;

  public:
    Argument(Record &Arg, StringRef Attr)
      : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
        attrName(Attr), isOpt(false) {
      if (!lowerName.empty()) {
        lowerName[0] = std::tolower(lowerName[0]);
        upperName[0] = std::toupper(upperName[0]);
      }
    }
    virtual ~Argument() {}

    StringRef getLowerName() const { return lowerName; }
    StringRef getUpperName() const { return upperName; }
    StringRef getAttrName() const { return attrName; }

    bool isOptional() const { return isOpt; }
    void setOptional(bool set) { isOpt = set; }

    // These functions print the argument contents formatted in different ways.
    virtual void writeAccessors(raw_ostream &OS) const = 0;
    virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
    virtual void writeCloneArgs(raw_ostream &OS) const = 0;
    virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
    virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
    virtual void writeCtorBody(raw_ostream &OS) const {}
    virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
    virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
    virtual void writeCtorParameters(raw_ostream &OS) const = 0;
    virtual void writeDeclarations(raw_ostream &OS) const = 0;
    virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
    virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
    virtual void writePCHWrite(raw_ostream &OS) const = 0;
    virtual void writeValue(raw_ostream &OS) const = 0;
    virtual void writeDump(raw_ostream &OS) const = 0;
    virtual void writeDumpChildren(raw_ostream &OS) const {}
    virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }

    virtual bool isEnumArg() const { return false; }
    virtual bool isVariadicEnumArg() const { return false; }

    virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
      OS << getUpperName();
    }
  };

  class SimpleArgument : public Argument {
    std::string type;

  public:
    SimpleArgument(Record &Arg, StringRef Attr, std::string T)
      : Argument(Arg, Attr), type(T)
    {}

    std::string getType() const { return type; }

    void writeAccessors(raw_ostream &OS) const {
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "(" << getUpperName() << ")";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "()";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << type << " " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << type << " " << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      std::string read = ReadPCHRecord(type);
      OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    " << WritePCHRecord(type, "SA->get" +
                                           std::string(getUpperName()) + "()");
    }
    void writeValue(raw_ostream &OS) const {
      if (type == "FunctionDecl *") {
        OS << "\" << get" << getUpperName()
           << "()->getNameInfo().getAsString() << \"";
      } else if (type == "IdentifierInfo *") {
        OS << "\" << get" << getUpperName() << "()->getName() << \"";
      } else if (type == "TypeSourceInfo *") {
        OS << "\" << get" << getUpperName() << "().getAsString() << \"";
      } else {
        OS << "\" << get" << getUpperName() << "() << \"";
      }
    }
    void writeDump(raw_ostream &OS) const {
      if (type == "FunctionDecl *") {
        OS << "    OS << \" \";\n";
        OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n"; 
      } else if (type == "IdentifierInfo *") {
        OS << "    OS << \" \" << SA->get" << getUpperName()
           << "()->getName();\n";
      } else if (type == "TypeSourceInfo *") {
        OS << "    OS << \" \" << SA->get" << getUpperName()
           << "().getAsString();\n";
      } else if (type == "bool") {
        OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
           << getUpperName() << "\";\n";
      } else if (type == "int" || type == "unsigned") {
        OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
      } else {
        llvm_unreachable("Unknown SimpleArgument type!");
      }
    }
  };

  class DefaultSimpleArgument : public SimpleArgument {
    int64_t Default;

  public:
    DefaultSimpleArgument(Record &Arg, StringRef Attr,
                          std::string T, int64_t Default)
      : SimpleArgument(Arg, Attr, T), Default(Default) {}

    void writeAccessors(raw_ostream &OS) const {
      SimpleArgument::writeAccessors(OS);

      OS << "\n\n  static const " << getType() << " Default" << getUpperName()
         << " = " << Default << ";";
    }
  };

  class StringArgument : public Argument {
  public:
    StringArgument(Record &Arg, StringRef Attr)
      : Argument(Arg, Attr)
    {}

    void writeAccessors(raw_ostream &OS) const {
      OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
      OS << "    return llvm::StringRef(" << getLowerName() << ", "
         << getLowerName() << "Length);\n";
      OS << "  }\n";
      OS << "  unsigned get" << getUpperName() << "Length() const {\n";
      OS << "    return " << getLowerName() << "Length;\n";
      OS << "  }\n";
      OS << "  void set" << getUpperName()
         << "(ASTContext &C, llvm::StringRef S) {\n";
      OS << "    " << getLowerName() << "Length = S.size();\n";
      OS << "    this->" << getLowerName() << " = new (C, 1) char ["
         << getLowerName() << "Length];\n";
      OS << "    std::memcpy(this->" << getLowerName() << ", S.data(), "
         << getLowerName() << "Length);\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << "get" << getUpperName() << "()";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorBody(raw_ostream &OS) const {
      OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName()
         << ".data(), " << getLowerName() << "Length);";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
         << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
         << "Length])";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "Length(0)," << getLowerName() << "(0)";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << "llvm::StringRef " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << "unsigned " << getLowerName() << "Length;\n";
      OS << "char *" << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    std::string " << getLowerName()
         << "= ReadString(Record, Idx);\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    AddString(SA->get" << getUpperName() << "(), Record);\n";
    }
    void writeValue(raw_ostream &OS) const {
      OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
         << "() << \"\\\"\";\n";
    }
  };

  class AlignedArgument : public Argument {
  public:
    AlignedArgument(Record &Arg, StringRef Attr)
      : Argument(Arg, Attr)
    {}

    void writeAccessors(raw_ostream &OS) const {
      OS << "  bool is" << getUpperName() << "Dependent() const;\n";

      OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";

      OS << "  bool is" << getUpperName() << "Expr() const {\n";
      OS << "    return is" << getLowerName() << "Expr;\n";
      OS << "  }\n";

      OS << "  Expr *get" << getUpperName() << "Expr() const {\n";
      OS << "    assert(is" << getLowerName() << "Expr);\n";
      OS << "    return " << getLowerName() << "Expr;\n";
      OS << "  }\n";

      OS << "  TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
      OS << "    assert(!is" << getLowerName() << "Expr);\n";
      OS << "    return " << getLowerName() << "Type;\n";
      OS << "  }";
    }
    void writeAccessorDefinitions(raw_ostream &OS) const {
      OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
         << "Dependent() const {\n";
      OS << "  if (is" << getLowerName() << "Expr)\n";
      OS << "    return " << getLowerName() << "Expr && (" << getLowerName()
         << "Expr->isValueDependent() || " << getLowerName()
         << "Expr->isTypeDependent());\n"; 
      OS << "  else\n";
      OS << "    return " << getLowerName()
         << "Type->getType()->isDependentType();\n";
      OS << "}\n";

      // FIXME: Do not do the calculation here
      // FIXME: Handle types correctly
      // A null pointer means maximum alignment
      // FIXME: Load the platform-specific maximum alignment, rather than
      //        16, the x86 max.
      OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
         << "(ASTContext &Ctx) const {\n";
      OS << "  assert(!is" << getUpperName() << "Dependent());\n";
      OS << "  if (is" << getLowerName() << "Expr)\n";
      OS << "    return (" << getLowerName() << "Expr ? " << getLowerName()
         << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue() : 16)"
         << "* Ctx.getCharWidth();\n";
      OS << "  else\n";
      OS << "    return 0; // FIXME\n";
      OS << "}\n";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << "is" << getLowerName() << "Expr, is" << getLowerName()
         << "Expr ? static_cast<void*>(" << getLowerName()
         << "Expr) : " << getLowerName()
         << "Type";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      // FIXME: move the definition in Sema::InstantiateAttrs to here.
      // In the meantime, aligned attributes are cloned.
    }
    void writeCtorBody(raw_ostream &OS) const {
      OS << "    if (is" << getLowerName() << "Expr)\n";
      OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
         << getUpperName() << ");\n";
      OS << "    else\n";
      OS << "       " << getLowerName()
         << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
         << ");";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << "is" << getLowerName() << "Expr(false)";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
    }
    void writeImplicitCtorArgs(raw_ostream &OS) const {
      OS << "Is" << getUpperName() << "Expr, " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << "bool is" << getLowerName() << "Expr;\n";
      OS << "union {\n";
      OS << "Expr *" << getLowerName() << "Expr;\n";
      OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
      OS << "};";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    bool is" << getLowerName() << "Expr = Record[Idx++];\n";
      OS << "    void *" << getLowerName() << "Ptr;\n";
      OS << "    if (is" << getLowerName() << "Expr)\n";
      OS << "      " << getLowerName() << "Ptr = ReadExpr(F);\n";
      OS << "    else\n";
      OS << "      " << getLowerName()
         << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
      OS << "    if (SA->is" << getUpperName() << "Expr())\n";
      OS << "      AddStmt(SA->get" << getUpperName() << "Expr());\n";
      OS << "    else\n";
      OS << "      AddTypeSourceInfo(SA->get" << getUpperName()
         << "Type(), Record);\n";
    }
    void writeValue(raw_ostream &OS) const {
      OS << "\";\n"
         << "  " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n"
         << "  OS << \"";
    }
    void writeDump(raw_ostream &OS) const {
    }
    void writeDumpChildren(raw_ostream &OS) const {
      OS << "    if (SA->is" << getUpperName() << "Expr()) {\n";
      OS << "      lastChild();\n";
      OS << "      dumpStmt(SA->get" << getUpperName() << "Expr());\n";
      OS << "    } else\n";
      OS << "      dumpType(SA->get" << getUpperName()
         << "Type()->getType());\n";
    }
    void writeHasChildren(raw_ostream &OS) const {
      OS << "SA->is" << getUpperName() << "Expr()";
    }
  };

  class VariadicArgument : public Argument {
    std::string type;

  public:
    VariadicArgument(Record &Arg, StringRef Attr, std::string T)
      : Argument(Arg, Attr), type(T)
    {}

    std::string getType() const { return type; }

    void writeAccessors(raw_ostream &OS) const {
      OS << "  typedef " << type << "* " << getLowerName() << "_iterator;\n";
      OS << "  " << getLowerName() << "_iterator " << getLowerName()
         << "_begin() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }\n";
      OS << "  " << getLowerName() << "_iterator " << getLowerName()
         << "_end() const {\n";
      OS << "    return " << getLowerName() << " + " << getLowerName()
         << "Size;\n";
      OS << "  }\n";
      OS << "  unsigned " << getLowerName() << "_size() const {\n"
         << "    return " << getLowerName() << "Size;\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << getLowerName() << ", " << getLowerName() << "Size";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      // This isn't elegant, but we have to go through public methods...
      OS << "A->" << getLowerName() << "_begin(), "
         << "A->" << getLowerName() << "_size()";
    }
    void writeCtorBody(raw_ostream &OS) const {
      // FIXME: memcpy is not safe on non-trivial types.
      OS << "    std::memcpy(" << getLowerName() << ", " << getUpperName()
         << ", " << getLowerName() << "Size * sizeof(" << getType() << "));\n";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "Size(" << getUpperName() << "Size), "
         << getLowerName() << "(new (Ctx, 16) " << getType() << "["
         << getLowerName() << "Size])";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "Size(0), " << getLowerName() << "(0)";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << getType() << " *" << getUpperName() << ", unsigned "
         << getUpperName() << "Size";
    }
    void writeImplicitCtorArgs(raw_ostream &OS) const {
      OS << getUpperName() << ", " << getUpperName() << "Size";
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << "  unsigned " << getLowerName() << "Size;\n";
      OS << "  " << getType() << " *" << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "  unsigned " << getLowerName() << "Size = Record[Idx++];\n";
      OS << "  SmallVector<" << type << ", 4> " << getLowerName()
         << ";\n";
      OS << "  " << getLowerName() << ".reserve(" << getLowerName()
         << "Size);\n";
      OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
      
      std::string read = ReadPCHRecord(type);
      OS << "    " << getLowerName() << ".push_back(" << read << ");\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName() << ".data(), " << getLowerName() << "Size";
    }
    void writePCHWrite(raw_ostream &OS) const{
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
         << getLowerName() << "_end(); i != e; ++i)\n";
      OS << "      " << WritePCHRecord(type, "(*i)");
    }
    void writeValue(raw_ostream &OS) const {
      OS << "\";\n";
      OS << "  bool isFirst = true;\n"
         << "  for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator i = " << getLowerName() << "_begin(), e = "
         << getLowerName() << "_end(); i != e; ++i) {\n"
         << "    if (isFirst) isFirst = false;\n"
         << "    else OS << \", \";\n"
         << "    OS << *i;\n"
         << "  }\n";
      OS << "  OS << \"";
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
         << getLowerName() << "_end(); I != E; ++I)\n";
      OS << "      OS << \" \" << *I;\n";
    }
  };

  // Unique the enums, but maintain the original declaration ordering.
  std::vector<std::string>
  uniqueEnumsInOrder(const std::vector<std::string> &enums) {
    std::vector<std::string> uniques;
    std::set<std::string> unique_set(enums.begin(), enums.end());
    for (std::vector<std::string>::const_iterator i = enums.begin(),
                                                  e = enums.end();
         i != e; ++i) {
      std::set<std::string>::iterator set_i = unique_set.find(*i);
      if (set_i != unique_set.end()) {
        uniques.push_back(*i);
        unique_set.erase(set_i);
      }
    }
    return uniques;
  }

  class EnumArgument : public Argument {
    std::string type;
    std::vector<std::string> values, enums, uniques;
  public:
    EnumArgument(Record &Arg, StringRef Attr)
      : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
        values(Arg.getValueAsListOfStrings("Values")),
        enums(Arg.getValueAsListOfStrings("Enums")),
        uniques(uniqueEnumsInOrder(enums))
    {
      // FIXME: Emit a proper error
      assert(!uniques.empty());
    }

    bool isEnumArg() const { return true; }

    void writeAccessors(raw_ostream &OS) const {
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "(" << getUpperName() << ")";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "(" << type << "(0))";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << type << " " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      std::vector<std::string>::const_iterator i = uniques.begin(),
                                               e = uniques.end();
      // The last one needs to not have a comma.
      --e;

      OS << "public:\n";
      OS << "  enum " << type << " {\n";
      for (; i != e; ++i)
        OS << "    " << *i << ",\n";
      OS << "    " << *e << "\n";
      OS << "  };\n";
      OS << "private:\n";
      OS << "  " << type << " " << getLowerName() << ";";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    " << getAttrName() << "Attr::" << type << " " << getLowerName()
         << "(static_cast<" << getAttrName() << "Attr::" << type
         << ">(Record[Idx++]));\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
    }
    void writeValue(raw_ostream &OS) const {
      OS << "\" << get" << getUpperName() << "() << \"";
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    switch(SA->get" << getUpperName() << "()) {\n";
      for (std::vector<std::string>::const_iterator I = uniques.begin(),
           E = uniques.end(); I != E; ++I) {
        OS << "    case " << getAttrName() << "Attr::" << *I << ":\n";
        OS << "      OS << \" " << *I << "\";\n";
        OS << "      break;\n";
      }
      OS << "    }\n";
    }

    void writeConversion(raw_ostream &OS) const {
      OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
      OS << type << " &Out) {\n";
      OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
      OS << type << "> >(Val)\n";
      for (size_t I = 0; I < enums.size(); ++I) {
        OS << "      .Case(\"" << values[I] << "\", ";
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
      }
      OS << "      .Default(Optional<" << type << ">());\n";
      OS << "    if (R) {\n";
      OS << "      Out = *R;\n      return true;\n    }\n";
      OS << "    return false;\n";
      OS << "  }\n";
    }
  };
  
  class VariadicEnumArgument: public VariadicArgument {
    std::string type, QualifiedTypeName;
    std::vector<std::string> values, enums, uniques;
  public:
    VariadicEnumArgument(Record &Arg, StringRef Attr)
      : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
        type(Arg.getValueAsString("Type")),
        values(Arg.getValueAsListOfStrings("Values")),
        enums(Arg.getValueAsListOfStrings("Enums")),
        uniques(uniqueEnumsInOrder(enums))
    {
      QualifiedTypeName = getAttrName().str() + "Attr::" + type;
      
      // FIXME: Emit a proper error
      assert(!uniques.empty());
    }

    bool isVariadicEnumArg() const { return true; }
    
    void writeDeclarations(raw_ostream &OS) const {
      std::vector<std::string>::const_iterator i = uniques.begin(),
                                               e = uniques.end();
      // The last one needs to not have a comma.
      --e;

      OS << "public:\n";
      OS << "  enum " << type << " {\n";
      for (; i != e; ++i)
        OS << "    " << *i << ",\n";
      OS << "    " << *e << "\n";
      OS << "  };\n";
      OS << "private:\n";
      
      VariadicArgument::writeDeclarations(OS);
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
         << getLowerName() << "_end(); I != E; ++I) {\n";
      OS << "      switch(*I) {\n";
      for (std::vector<std::string>::const_iterator UI = uniques.begin(),
           UE = uniques.end(); UI != UE; ++UI) {
        OS << "    case " << getAttrName() << "Attr::" << *UI << ":\n";
        OS << "      OS << \" " << *UI << "\";\n";
        OS << "      break;\n";
      }
      OS << "      }\n";
      OS << "    }\n";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    unsigned " << getLowerName() << "Size = Record[Idx++];\n";
      OS << "    SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
         << ";\n";
      OS << "    " << getLowerName() << ".reserve(" << getLowerName()
         << "Size);\n";
      OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
      OS << "      " << getLowerName() << ".push_back(" << "static_cast<"
         << QualifiedTypeName << ">(Record[Idx++]));\n";
    }
    void writePCHWrite(raw_ostream &OS) const{
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
         << getLowerName() << "_end(); i != e; ++i)\n";
      OS << "      " << WritePCHRecord(QualifiedTypeName, "(*i)");
    }
    void writeConversion(raw_ostream &OS) const {
      OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
      OS << type << " &Out) {\n";
      OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
      OS << type << "> >(Val)\n";
      for (size_t I = 0; I < enums.size(); ++I) {
        OS << "      .Case(\"" << values[I] << "\", ";
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
      }
      OS << "      .Default(Optional<" << type << ">());\n";
      OS << "    if (R) {\n";
      OS << "      Out = *R;\n      return true;\n    }\n";
      OS << "    return false;\n";
      OS << "  }\n";
    }
  };

  class VersionArgument : public Argument {
  public:
    VersionArgument(Record &Arg, StringRef Attr)
      : Argument(Arg, Attr)
    {}

    void writeAccessors(raw_ostream &OS) const {
      OS << "  VersionTuple get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }\n";
      OS << "  void set" << getUpperName() 
         << "(ASTContext &C, VersionTuple V) {\n";
      OS << "    " << getLowerName() << " = V;\n";
      OS << "  }";
    }
    void writeCloneArgs(raw_ostream &OS) const {
      OS << "get" << getUpperName() << "()";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "()";
    }
    void writeCtorBody(raw_ostream &OS) const {
    }
    void writeCtorInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "(" << getUpperName() << ")";
    }
    void writeCtorDefaultInitializers(raw_ostream &OS) const {
      OS << getLowerName() << "()";
    }
    void writeCtorParameters(raw_ostream &OS) const {
      OS << "VersionTuple " << getUpperName();
    }
    void writeDeclarations(raw_ostream &OS) const {
      OS << "VersionTuple " << getLowerName() << ";\n";
    }
    void writePCHReadDecls(raw_ostream &OS) const {
      OS << "    VersionTuple " << getLowerName()
         << "= ReadVersionTuple(Record, Idx);\n";
    }
    void writePCHReadArgs(raw_ostream &OS) const {
      OS << getLowerName();
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
    }
    void writeValue(raw_ostream &OS) const {
      OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
    }
    void writeDump(raw_ostream &OS) const {
      OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
    }
  };

  class ExprArgument : public SimpleArgument {
  public:
    ExprArgument(Record &Arg, StringRef Attr)
      : SimpleArgument(Arg, Attr, "Expr *")
    {}

    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {
      OS << "  if (!"
         << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
      OS << "    return false;\n";
    }

    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "tempInst" << getUpperName();
    }

    void writeTemplateInstantiation(raw_ostream &OS) const {
      OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
      OS << "      {\n";
      OS << "        EnterExpressionEvaluationContext "
         << "Unevaluated(S, Sema::Unevaluated);\n";
      OS << "        ExprResult " << "Result = S.SubstExpr("
         << "A->get" << getUpperName() << "(), TemplateArgs);\n";
      OS << "        tempInst" << getUpperName() << " = "
         << "Result.takeAs<Expr>();\n";
      OS << "      }\n";
    }

    void writeDump(raw_ostream &OS) const {
    }

    void writeDumpChildren(raw_ostream &OS) const {
      OS << "    lastChild();\n";
      OS << "    dumpStmt(SA->get" << getUpperName() << "());\n";
    }
    void writeHasChildren(raw_ostream &OS) const { OS << "true"; }
  };

  class VariadicExprArgument : public VariadicArgument {
  public:
    VariadicExprArgument(Record &Arg, StringRef Attr)
      : VariadicArgument(Arg, Attr, "Expr *")
    {}

    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {
      OS << "  {\n";
      OS << "    " << getType() << " *I = A->" << getLowerName()
         << "_begin();\n";
      OS << "    " << getType() << " *E = A->" << getLowerName()
         << "_end();\n";
      OS << "    for (; I != E; ++I) {\n";
      OS << "      if (!getDerived().TraverseStmt(*I))\n";
      OS << "        return false;\n";
      OS << "    }\n";
      OS << "  }\n";
    }

    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "tempInst" << getUpperName() << ", "
         << "A->" << getLowerName() << "_size()";
    }

    void writeTemplateInstantiation(raw_ostream &OS) const {
      OS << "      " << getType() << " *tempInst" << getUpperName()
         << " = new (C, 16) " << getType()
         << "[A->" << getLowerName() << "_size()];\n";
      OS << "      {\n";
      OS << "        EnterExpressionEvaluationContext "
         << "Unevaluated(S, Sema::Unevaluated);\n";
      OS << "        " << getType() << " *TI = tempInst" << getUpperName()
         << ";\n";
      OS << "        " << getType() << " *I = A->" << getLowerName()
         << "_begin();\n";
      OS << "        " << getType() << " *E = A->" << getLowerName()
         << "_end();\n";
      OS << "        for (; I != E; ++I, ++TI) {\n";
      OS << "          ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
      OS << "          *TI = Result.takeAs<Expr>();\n";
      OS << "        }\n";
      OS << "      }\n";
    }

    void writeDump(raw_ostream &OS) const {
    }

    void writeDumpChildren(raw_ostream &OS) const {
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
         << getLowerName() << "_end(); I != E; ++I) {\n";
      OS << "      if (I + 1 == E)\n";
      OS << "        lastChild();\n";
      OS << "      dumpStmt(*I);\n";
      OS << "    }\n";
    }

    void writeHasChildren(raw_ostream &OS) const {
      OS << "SA->" << getLowerName() << "_begin() != "
         << "SA->" << getLowerName() << "_end()";
    }
  };

  class TypeArgument : public SimpleArgument {
  public:
    TypeArgument(Record &Arg, StringRef Attr)
      : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
    {}

    void writeAccessors(raw_ostream &OS) const {
      OS << "  QualType get" << getUpperName() << "() const {\n";
      OS << "    return " << getLowerName() << "->getType();\n";
      OS << "  }";
      OS << "  " << getType() << " get" << getUpperName() << "Loc() const {\n";
      OS << "    return " << getLowerName() << ";\n";
      OS << "  }";
    }
    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
      OS << "A->get" << getUpperName() << "Loc()";
    }
    void writePCHWrite(raw_ostream &OS) const {
      OS << "    " << WritePCHRecord(
          getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
    }
  };
}

static Argument *createArgument(Record &Arg, StringRef Attr,
                                Record *Search = 0) {
  if (!Search)
    Search = &Arg;

  Argument *Ptr = 0;
  llvm::StringRef ArgName = Search->getName();

  if (ArgName == "AlignedArgument") Ptr = new AlignedArgument(Arg, Attr);
  else if (ArgName == "EnumArgument") Ptr = new EnumArgument(Arg, Attr);
  else if (ArgName == "ExprArgument") Ptr = new ExprArgument(Arg, Attr);
  else if (ArgName == "FunctionArgument")
    Ptr = new SimpleArgument(Arg, Attr, "FunctionDecl *");
  else if (ArgName == "IdentifierArgument")
    Ptr = new SimpleArgument(Arg, Attr, "IdentifierInfo *");
  else if (ArgName == "DefaultBoolArgument")
    Ptr = new DefaultSimpleArgument(Arg, Attr, "bool",
                                    Arg.getValueAsBit("Default"));
  else if (ArgName == "BoolArgument") Ptr = new SimpleArgument(Arg, Attr, 
                                                               "bool");
  else if (ArgName == "DefaultIntArgument")
    Ptr = new DefaultSimpleArgument(Arg, Attr, "int",
                                    Arg.getValueAsInt("Default"));
  else if (ArgName == "IntArgument") Ptr = new SimpleArgument(Arg, Attr, "int");
  else if (ArgName == "StringArgument") Ptr = new StringArgument(Arg, Attr);
  else if (ArgName == "TypeArgument") Ptr = new TypeArgument(Arg, Attr);
  else if (ArgName == "UnsignedArgument")
    Ptr = new SimpleArgument(Arg, Attr, "unsigned");
  else if (ArgName == "VariadicUnsignedArgument")
    Ptr = new VariadicArgument(Arg, Attr, "unsigned");
  else if (ArgName == "VariadicEnumArgument")
    Ptr = new VariadicEnumArgument(Arg, Attr);
  else if (ArgName == "VariadicExprArgument")
    Ptr = new VariadicExprArgument(Arg, Attr);
  else if (ArgName == "VersionArgument")
    Ptr = new VersionArgument(Arg, Attr);

  if (!Ptr) {
    // Search in reverse order so that the most-derived type is handled first.
    std::vector<Record*> Bases = Search->getSuperClasses();
    for (std::vector<Record*>::reverse_iterator i = Bases.rbegin(),
         e = Bases.rend(); i != e; ++i) {
      Ptr = createArgument(Arg, Attr, *i);
      if (Ptr)
        break;
    }
  }

  if (Ptr && Arg.getValueAsBit("Optional"))
    Ptr->setOptional(true);

  return Ptr;
}

static void writeAvailabilityValue(raw_ostream &OS) {
  OS << "\" << getPlatform()->getName();\n"
     << "  if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
     << "  if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
     << "  if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
     << "  if (getUnavailable()) OS << \", unavailable\";\n"
     << "  OS << \"";
}

static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);

  OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
  if (Spellings.empty()) {
    OS << "  return \"(No spelling)\";\n}\n\n";
    return;
  }

  OS << "  switch (SpellingListIndex) {\n"
        "  default:\n"
        "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
        "    return \"(No spelling)\";\n";

  for (unsigned I = 0; I < Spellings.size(); ++I)
    OS << "  case " << I << ":\n"
          "    return \"" << Spellings[I].name() << "\";\n";
  // End of the switch statement.
  OS << "  }\n";
  // End of the getSpelling function.
  OS << "}\n\n";
}

static void writePrettyPrintFunction(Record &R, std::vector<Argument*> &Args,
                                     raw_ostream &OS) {
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);

  OS << "void " << R.getName() << "Attr::printPretty("
    << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";

  if (Spellings.size() == 0) {
    OS << "}\n\n";
    return;
  }

  OS <<
    "  switch (SpellingListIndex) {\n"
    "  default:\n"
    "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
    "    break;\n";

  for (unsigned I = 0; I < Spellings.size(); ++ I) {
    llvm::SmallString<16> Prefix;
    llvm::SmallString<8> Suffix;
    // The actual spelling of the name and namespace (if applicable)
    // of an attribute without considering prefix and suffix.
    llvm::SmallString<64> Spelling;
    std::string Name = Spellings[I].name();
    std::string Variety = Spellings[I].variety();

    if (Variety == "GNU") {
      Prefix = " __attribute__((";
      Suffix = "))";
    } else if (Variety == "CXX11") {
      Prefix = " [[";
      Suffix = "]]";
      std::string Namespace = Spellings[I].nameSpace();
      if (Namespace != "") {
        Spelling += Namespace;
        Spelling += "::";
      }
    } else if (Variety == "Declspec") {
      Prefix = " __declspec(";
      Suffix = ")";
    } else if (Variety == "Keyword") {
      Prefix = " ";
      Suffix = "";
    } else {
      llvm_unreachable("Unknown attribute syntax variety!");
    }

    Spelling += Name;

    OS <<
      "  case " << I << " : {\n"
      "    OS << \"" + Prefix.str() + Spelling.str();

    if (Args.size()) OS << "(";
    if (Spelling == "availability") {
      writeAvailabilityValue(OS);
    } else {
      for (std::vector<Argument*>::const_iterator I = Args.begin(),
           E = Args.end(); I != E; ++ I) {
        if (I != Args.begin()) OS << ", ";
        (*I)->writeValue(OS);
      }
    }

    if (Args.size()) OS << ")";
    OS << Suffix.str() + "\";\n";

    OS <<
      "    break;\n"
      "  }\n";
  }

  // End of the switch statement.
  OS << "}\n";
  // End of the print function.
  OS << "}\n\n";
}

/// \brief Return the index of a spelling in a spelling list.
static unsigned
getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
                     const FlattenedSpelling &Spelling) {
  assert(SpellingList.size() && "Spelling list is empty!");

  for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
    const FlattenedSpelling &S = SpellingList[Index];
    if (S.variety() != Spelling.variety())
      continue;
    if (S.nameSpace() != Spelling.nameSpace())
      continue;
    if (S.name() != Spelling.name())
      continue;

    return Index;
  }

  llvm_unreachable("Unknown spelling!");
}

static void writeAttrAccessorDefinition(Record &R, raw_ostream &OS) {
  std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
  for (std::vector<Record*>::const_iterator I = Accessors.begin(),
       E = Accessors.end(); I != E; ++I) {
    Record *Accessor = *I;
    std::string Name = Accessor->getValueAsString("Name");
    std::vector<FlattenedSpelling> Spellings = 
      GetFlattenedSpellings(*Accessor);
    std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
    assert(SpellingList.size() &&
           "Attribute with empty spelling list can't have accessors!");

    OS << "  bool " << Name << "() const { return SpellingListIndex == ";
    for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
      OS << getSpellingListIndex(SpellingList, Spellings[Index]);
      if (Index != Spellings.size() -1)
        OS << " ||\n    SpellingListIndex == ";
      else
        OS << "; }\n";
    }
  }
}

static bool
SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
  assert(!Spellings.empty() && "An empty list of spellings was provided");
  std::string FirstName = NormalizeNameForSpellingComparison(
    Spellings.front().name());
  for (std::vector<FlattenedSpelling>::const_iterator
       I = llvm::next(Spellings.begin()), E = Spellings.end(); I != E; ++I) {
    std::string Name = NormalizeNameForSpellingComparison(I->name());
    if (Name != FirstName)
      return false;
  }
  return true;
}

typedef std::map<unsigned, std::string> SemanticSpellingMap;
static std::string
CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
                        SemanticSpellingMap &Map) {
  // The enumerants are automatically generated based on the variety,
  // namespace (if present) and name for each attribute spelling. However,
  // care is taken to avoid trampling on the reserved namespace due to
  // underscores.
  std::string Ret("  enum Spelling {\n");
  std::set<std::string> Uniques;
  unsigned Idx = 0;
  for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
        E = Spellings.end(); I != E; ++I, ++Idx) {
    const FlattenedSpelling &S = *I;
    std::string Variety = S.variety();
    std::string Spelling = S.name();
    std::string Namespace = S.nameSpace();
    std::string EnumName = "";

    EnumName += (Variety + "_");
    if (!Namespace.empty())
      EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
      "_");
    EnumName += NormalizeNameForSpellingComparison(Spelling);

    // Even if the name is not unique, this spelling index corresponds to a
    // particular enumerant name that we've calculated.
    Map[Idx] = EnumName;

    // Since we have been stripping underscores to avoid trampling on the
    // reserved namespace, we may have inadvertently created duplicate
    // enumerant names. These duplicates are not considered part of the
    // semantic spelling, and can be elided.
    if (Uniques.find(EnumName) != Uniques.end())
      continue;

    Uniques.insert(EnumName);
    if (I != Spellings.begin())
      Ret += ",\n";
    Ret += "    " + EnumName;
  }
  Ret += "\n  };\n\n";
  return Ret;
}

void WriteSemanticSpellingSwitch(const std::string &VarName,
                                 const SemanticSpellingMap &Map,
                                 raw_ostream &OS) {
  OS << "  switch (" << VarName << ") {\n    default: "
    << "llvm_unreachable(\"Unknown spelling list index\");\n";
  for (SemanticSpellingMap::const_iterator I = Map.begin(), E = Map.end();
       I != E; ++I)
       OS << "    case " << I->first << ": return " << I->second << ";\n";
  OS << "  }\n";
}

// Emits the LateParsed property for attributes.
static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    bool LateParsed = Attr.getValueAsBit("LateParsed");

    if (LateParsed) {
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);

      // FIXME: Handle non-GNU attributes
      for (std::vector<FlattenedSpelling>::const_iterator
           I = Spellings.begin(), E = Spellings.end(); I != E; ++I) {
        if (I->variety() != "GNU")
          continue;
        OS << ".Case(\"" << I->name() << "\", " << LateParsed << ")\n";
      }
    }
  }
  OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
}

/// \brief Emits the first-argument-is-type property for attributes.
static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record *>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    // Determine whether the first argument is a type.
    std::vector<Record *> Args = Attr.getValueAsListOfDefs("Args");
    if (Args.empty())
      continue;

    if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
      continue;

    // All these spellings take a single type argument.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
    std::set<std::string> Emitted;
    for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      if (Emitted.insert(I->name()).second)
        OS << ".Case(\"" << I->name() << "\", " << "true" << ")\n";
    }
  }
  OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
}

/// \brief Emits the parse-arguments-in-unevaluated-context property for
/// attributes.
static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
  ParsedAttrMap Attrs = getParsedAttrList(Records);
  for (ParsedAttrMap::const_iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    const Record &Attr = *I->second;

    if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
      continue;

    // All these spellings take are parsed unevaluated.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
    std::set<std::string> Emitted;
    for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      if (Emitted.insert(I->name()).second)
        OS << ".Case(\"" << I->name() << "\", " << "true" << ")\n";
    }
  }
  OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
}

static bool isIdentifierArgument(Record *Arg) {
  return !Arg->getSuperClasses().empty() &&
    llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
    .Case("IdentifierArgument", true)
    .Case("EnumArgument", true)
    .Default(false);
}

// Emits the first-argument-is-identifier property for attributes.
static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
  OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    // Determine whether the first argument is an identifier.
    std::vector<Record *> Args = Attr.getValueAsListOfDefs("Args");
    if (Args.empty() || !isIdentifierArgument(Args[0]))
      continue;

    // All these spellings take an identifier argument.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
    std::set<std::string> Emitted;
    for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I) {
      if (Emitted.insert(I->name()).second)
        OS << ".Case(\"" << I->name() << "\", " << "true" << ")\n";
    }
  }
  OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
}

namespace clang {

// Emits the class definitions for attributes.
void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute classes' definitions", OS);

  OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
  OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  for (std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end();
       i != e; ++i) {
    Record &R = **i;

    // FIXME: Currently, documentation is generated as-needed due to the fact
    // that there is no way to allow a generated project "reach into" the docs
    // directory (for instance, it may be an out-of-tree build). However, we want
    // to ensure that every attribute has a Documentation field, and produce an
    // error if it has been neglected. Otherwise, the on-demand generation which
    // happens server-side will fail. This code is ensuring that functionality,
    // even though this Emitter doesn't technically need the documentation.
    // When attribute documentation can be generated as part of the build
    // itself, this code can be removed.
    (void)R.getValueAsListOfDefs("Documentation");
    
    if (!R.getValueAsBit("ASTNode"))
      continue;
    
    const std::vector<Record *> Supers = R.getSuperClasses();
    assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
    std::string SuperName;
    for (std::vector<Record *>::const_reverse_iterator I = Supers.rbegin(),
         E = Supers.rend(); I != E; ++I) {
      const Record &R = **I;
      if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
        SuperName = R.getName();
    }

    OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";

    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    std::vector<Argument*> Args;
    std::vector<Argument*>::iterator ai, ae;
    Args.reserve(ArgRecords.size());

    for (std::vector<Record*>::iterator ri = ArgRecords.begin(),
                                        re = ArgRecords.end();
         ri != re; ++ri) {
      Record &ArgRecord = **ri;
      Argument *Arg = createArgument(ArgRecord, R.getName());
      assert(Arg);
      Args.push_back(Arg);

      Arg->writeDeclarations(OS);
      OS << "\n\n";
    }

    ae = Args.end();

    OS << "\npublic:\n";

    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);

    // If there are zero or one spellings, all spelling-related functionality
    // can be elided. If all of the spellings share the same name, the spelling
    // functionality can also be elided.
    bool ElideSpelling = (Spellings.size() <= 1) ||
                         SpellingNamesAreCommon(Spellings);

    // This maps spelling index values to semantic Spelling enumerants.
    SemanticSpellingMap SemanticToSyntacticMap;

    if (!ElideSpelling)
      OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);

    OS << "  static " << R.getName() << "Attr *CreateImplicit(";
    OS << "ASTContext &Ctx";
    if (!ElideSpelling)
      OS << ", Spelling S";
    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << ", ";
      (*ai)->writeCtorParameters(OS);
    }
    OS << ", SourceRange Loc = SourceRange()";
    OS << ") {\n";
    OS << "    " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
    OS << "Attr(Loc, Ctx, ";
    for (ai = Args.begin(); ai != ae; ++ai) {
      (*ai)->writeImplicitCtorArgs(OS);
      OS << ", ";
    }
    OS << (ElideSpelling ? "0" : "S") << ");\n";
    OS << "    A->setImplicit(true);\n";
    OS << "    return A;\n  }\n\n";

    OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
    
    bool HasOpt = false;
    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << "              , ";
      (*ai)->writeCtorParameters(OS);
      OS << "\n";
      if ((*ai)->isOptional())
        HasOpt = true;
    }

    OS << "              , ";
    OS << "unsigned SI\n";

    OS << "             )\n";
    OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";

    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << "              , ";
      (*ai)->writeCtorInitializers(OS);
      OS << "\n";
    }

    OS << "  {\n";
  
    for (ai = Args.begin(); ai != ae; ++ai) {
      (*ai)->writeCtorBody(OS);
      OS << "\n";
    }
    OS << "  }\n\n";

    // If there are optional arguments, write out a constructor that elides the
    // optional arguments as well.
    if (HasOpt) {
      OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
      for (ai = Args.begin(); ai != ae; ++ai) {
        if (!(*ai)->isOptional()) {
          OS << "              , ";
          (*ai)->writeCtorParameters(OS);
          OS << "\n";
        }
      }

      OS << "              , ";
      OS << "unsigned SI\n";

      OS << "             )\n";
      OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";

      for (ai = Args.begin(); ai != ae; ++ai) {
        OS << "              , ";
        (*ai)->writeCtorDefaultInitializers(OS);
        OS << "\n";
      }

      OS << "  {\n";
  
      for (ai = Args.begin(); ai != ae; ++ai) {
        if (!(*ai)->isOptional()) {
          (*ai)->writeCtorBody(OS);
          OS << "\n";
        }
      }
      OS << "  }\n\n";
    }

    OS << "  virtual " << R.getName() << "Attr *clone (ASTContext &C) const;\n";
    OS << "  virtual void printPretty(raw_ostream &OS,\n"
       << "                           const PrintingPolicy &Policy) const;\n";
    OS << "  virtual const char *getSpelling() const;\n";
    
    if (!ElideSpelling) {
      assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
      OS << "  Spelling getSemanticSpelling() const {\n";
      WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
                                  OS);
      OS << "  }\n";
    }

    writeAttrAccessorDefinition(R, OS);

    for (ai = Args.begin(); ai != ae; ++ai) {
      (*ai)->writeAccessors(OS);
      OS << "\n\n";

      if ((*ai)->isEnumArg()) {
        EnumArgument *EA = (EnumArgument *)*ai;
        EA->writeConversion(OS);
      } else if ((*ai)->isVariadicEnumArg()) {
        VariadicEnumArgument *VEA = (VariadicEnumArgument *)*ai;
        VEA->writeConversion(OS);
      }
    }

    OS << R.getValueAsString("AdditionalMembers");
    OS << "\n\n";

    OS << "  static bool classof(const Attr *A) { return A->getKind() == "
       << "attr::" << R.getName() << "; }\n";

    bool LateParsed = R.getValueAsBit("LateParsed");
    OS << "  virtual bool isLateParsed() const { return "
       << LateParsed << "; }\n";

    if (R.getValueAsBit("DuplicatesAllowedWhileMerging"))
      OS << "  virtual bool duplicatesAllowed() const { return true; }\n\n";

    OS << "};\n\n";
  }

  OS << "#endif\n";
}

// Emits the class method definitions for attributes.
void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute classes' member function definitions", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end(), ri, re;
  std::vector<Argument*>::iterator ai, ae;

  for (; i != e; ++i) {
    Record &R = **i;
    
    if (!R.getValueAsBit("ASTNode"))
      continue;
    
    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    std::vector<Argument*> Args;
    for (ri = ArgRecords.begin(), re = ArgRecords.end(); ri != re; ++ri)
      Args.push_back(createArgument(**ri, R.getName()));

    for (ai = Args.begin(), ae = Args.end(); ai != ae; ++ai)
      (*ai)->writeAccessorDefinitions(OS);

    OS << R.getName() << "Attr *" << R.getName()
       << "Attr::clone(ASTContext &C) const {\n";
    OS << "  return new (C) " << R.getName() << "Attr(getLocation(), C";
    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << ", ";
      (*ai)->writeCloneArgs(OS);
    }
    OS << ", getSpellingListIndex());\n}\n\n";

    writePrettyPrintFunction(R, Args, OS);
    writeGetSpellingFunction(R, OS);
  }
}

} // end namespace clang

static void EmitAttrList(raw_ostream &OS, StringRef Class,
                         const std::vector<Record*> &AttrList) {
  std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end();

  if (i != e) {
    // Move the end iterator back to emit the last attribute.
    for(--e; i != e; ++i) {
      if (!(*i)->getValueAsBit("ASTNode"))
        continue;
      
      OS << Class << "(" << (*i)->getName() << ")\n";
    }
    
    OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
  }
}

namespace clang {

// Emits the enumeration list for attributes.
void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);

  OS << "#ifndef LAST_ATTR\n";
  OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef INHERITABLE_ATTR\n";
  OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef LAST_INHERITABLE_ATTR\n";
  OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
  OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
  OS << "#endif\n\n";

  OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
  OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
        " INHERITABLE_PARAM_ATTR(NAME)\n";
  OS << "#endif\n\n";

  Record *InhClass = Records.getClass("InheritableAttr");
  Record *InhParamClass = Records.getClass("InheritableParamAttr");
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
                       NonInhAttrs, InhAttrs, InhParamAttrs;
  for (std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end();
       i != e; ++i) {
    if (!(*i)->getValueAsBit("ASTNode"))
      continue;
    
    if ((*i)->isSubClassOf(InhParamClass))
      InhParamAttrs.push_back(*i);
    else if ((*i)->isSubClassOf(InhClass))
      InhAttrs.push_back(*i);
    else
      NonInhAttrs.push_back(*i);
  }

  EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
  EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
  EmitAttrList(OS, "ATTR", NonInhAttrs);

  OS << "#undef LAST_ATTR\n";
  OS << "#undef INHERITABLE_ATTR\n";
  OS << "#undef LAST_INHERITABLE_ATTR\n";
  OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
  OS << "#undef ATTR\n";
}

// Emits the code to read an attribute from a precompiled header.
void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute deserialization code", OS);

  Record *InhClass = Records.getClass("InheritableAttr");
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
                       ArgRecords;
  std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end(), ai, ae;
  std::vector<Argument*> Args;
  std::vector<Argument*>::iterator ri, re;

  OS << "  switch (Kind) {\n";
  OS << "  default:\n";
  OS << "    assert(0 && \"Unknown attribute!\");\n";
  OS << "    break;\n";
  for (; i != e; ++i) {
    Record &R = **i;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    
    OS << "  case attr::" << R.getName() << ": {\n";
    if (R.isSubClassOf(InhClass))
      OS << "    bool isInherited = Record[Idx++];\n";
    OS << "    bool isImplicit = Record[Idx++];\n";
    OS << "    unsigned Spelling = Record[Idx++];\n";
    ArgRecords = R.getValueAsListOfDefs("Args");
    Args.clear();
    for (ai = ArgRecords.begin(), ae = ArgRecords.end(); ai != ae; ++ai) {
      Argument *A = createArgument(**ai, R.getName());
      Args.push_back(A);
      A->writePCHReadDecls(OS);
    }
    OS << "    New = new (Context) " << R.getName() << "Attr(Range, Context";
    for (ri = Args.begin(), re = Args.end(); ri != re; ++ri) {
      OS << ", ";
      (*ri)->writePCHReadArgs(OS);
    }
    OS << ", Spelling);\n";
    if (R.isSubClassOf(InhClass))
      OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
    OS << "    New->setImplicit(isImplicit);\n";
    OS << "    break;\n";
    OS << "  }\n";
  }
  OS << "  }\n";
}

// Emits the code to write an attribute to a precompiled header.
void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute serialization code", OS);

  Record *InhClass = Records.getClass("InheritableAttr");
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end(), ai, ae;

  OS << "  switch (A->getKind()) {\n";
  OS << "  default:\n";
  OS << "    llvm_unreachable(\"Unknown attribute kind!\");\n";
  OS << "    break;\n";
  for (; i != e; ++i) {
    Record &R = **i;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    OS << "  case attr::" << R.getName() << ": {\n";
    Args = R.getValueAsListOfDefs("Args");
    if (R.isSubClassOf(InhClass) || !Args.empty())
      OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
         << "Attr>(A);\n";
    if (R.isSubClassOf(InhClass))
      OS << "    Record.push_back(SA->isInherited());\n";
    OS << "    Record.push_back(A->isImplicit());\n";
    OS << "    Record.push_back(A->getSpellingListIndex());\n";

    for (ai = Args.begin(), ae = Args.end(); ai != ae; ++ai)
      createArgument(**ai, R.getName())->writePCHWrite(OS);
    OS << "    break;\n";
    OS << "  }\n";
  }
  OS << "  }\n";
}

// Emits the list of spellings for attributes.
void EmitClangAttrSpellingList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("llvm::StringSwitch code to match attributes based on "
                       "the target triple, T", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    // It is assumed that there will be an llvm::Triple object named T within
    // scope that can be used to determine whether the attribute exists in
    // a given target.
    std::string Test;
    if (Attr.isSubClassOf("TargetSpecificAttr")) {
      const Record *R = Attr.getValueAsDef("Target");
      std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");

      Test += "(";
      for (std::vector<std::string>::const_iterator AI = Arches.begin(),
           AE = Arches.end(); AI != AE; ++AI) {
        std::string Part = *AI;
        Test += "T.getArch() == llvm::Triple::" + Part;
        if (AI + 1 != AE)
          Test += " || ";
      }
      Test += ")";

      std::vector<std::string> OSes;
      if (!R->isValueUnset("OSes")) {
        Test += " && (";
        std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
        for (std::vector<std::string>::const_iterator AI = OSes.begin(),
             AE = OSes.end(); AI != AE; ++AI) {
          std::string Part = *AI;

          Test += "T.getOS() == llvm::Triple::" + Part;
          if (AI + 1 != AE)
            Test += " || ";
        }
        Test += ")";
      }
    } else
      Test = "true";

    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
    for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
         E = Spellings.end(); I != E; ++I)
      OS << ".Case(\"" << I->name() << "\", " << Test << ")\n";
  }

}

void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Code to translate different attribute spellings "
                       "into internal identifiers", OS);

  OS <<
    "  switch (AttrKind) {\n"
    "  default:\n"
    "    llvm_unreachable(\"Unknown attribute kind!\");\n"
    "    break;\n";

  ParsedAttrMap Attrs = getParsedAttrList(Records);
  for (ParsedAttrMap::const_iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = *I->second;
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
    OS << "  case AT_" << I->first << ": {\n";
    for (unsigned I = 0; I < Spellings.size(); ++ I) {
      OS << "    if (Name == \""
        << Spellings[I].name() << "\" && "
        << "SyntaxUsed == "
        << StringSwitch<unsigned>(Spellings[I].variety())
          .Case("GNU", 0)
          .Case("CXX11", 1)
          .Case("Declspec", 2)
          .Case("Keyword", 3)
          .Default(0)
        << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
        << "        return " << I << ";\n";
    }

    OS << "    break;\n";
    OS << "  }\n";
  }

  OS << "  }\n";
  OS << "  return 0;\n";
}

// Emits code used by RecursiveASTVisitor to visit attributes
void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  // Write method declarations for Traverse* methods.
  // We emit this here because we only generate methods for attributes that
  // are declared as ASTNodes.
  OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    OS << "  bool Traverse"
       << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
    OS << "  bool Visit"
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
       << "    return true; \n"
       << "  };\n";
  }
  OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";

  // Write individual Traverse* methods for each attribute class.
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    if (!R.getValueAsBit("ASTNode"))
      continue;

    OS << "template <typename Derived>\n"
       << "bool VISITORCLASS<Derived>::Traverse"
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
       << "  if (!getDerived().VisitAttr(A))\n"
       << "    return false;\n"
       << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
       << "    return false;\n";

    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    for (std::vector<Record*>::iterator ri = ArgRecords.begin(),
                                        re = ArgRecords.end();
         ri != re; ++ri) {
      Record &ArgRecord = **ri;
      Argument *Arg = createArgument(ArgRecord, R.getName());
      assert(Arg);
      Arg->writeASTVisitorTraversal(OS);
    }

    OS << "  return true;\n";
    OS << "}\n\n";
  }

  // Write generic Traverse routine
  OS << "template <typename Derived>\n"
     << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
     << "  if (!A)\n"
     << "    return true;\n"
     << "\n"
     << "  switch (A->getKind()) {\n"
     << "    default:\n"
     << "      return true;\n";

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    if (!R.getValueAsBit("ASTNode"))
      continue;

    OS << "    case attr::" << R.getName() << ":\n"
       << "      return getDerived().Traverse" << R.getName() << "Attr("
       << "cast<" << R.getName() << "Attr>(A));\n";
  }
  OS << "  }\n";  // end case
  OS << "}\n";  // end function
  OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
}

// Emits code to instantiate dependent attributes on templates.
void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Template instantiation code for attributes", OS);

  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");

  OS << "namespace clang {\n"
     << "namespace sema {\n\n"
     << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
     << "Sema &S,\n"
     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
     << "  switch (At->getKind()) {\n"
     << "    default:\n"
     << "      break;\n";

  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    if (!R.getValueAsBit("ASTNode"))
      continue;

    OS << "    case attr::" << R.getName() << ": {\n";
    bool ShouldClone = R.getValueAsBit("Clone");

    if (!ShouldClone) {
      OS << "      return NULL;\n";
      OS << "    }\n";
      continue;
    }

    OS << "      const " << R.getName() << "Attr *A = cast<"
       << R.getName() << "Attr>(At);\n";
    bool TDependent = R.getValueAsBit("TemplateDependent");

    if (!TDependent) {
      OS << "      return A->clone(C);\n";
      OS << "    }\n";
      continue;
    }

    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
    std::vector<Argument*> Args;
    std::vector<Argument*>::iterator ai, ae;
    Args.reserve(ArgRecords.size());

    for (std::vector<Record*>::iterator ri = ArgRecords.begin(),
                                        re = ArgRecords.end();
         ri != re; ++ri) {
      Record &ArgRecord = **ri;
      Argument *Arg = createArgument(ArgRecord, R.getName());
      assert(Arg);
      Args.push_back(Arg);
    }
    ae = Args.end();

    for (ai = Args.begin(); ai != ae; ++ai) {
      (*ai)->writeTemplateInstantiation(OS);
    }
    OS << "      return new (C) " << R.getName() << "Attr(A->getLocation(), C";
    for (ai = Args.begin(); ai != ae; ++ai) {
      OS << ", ";
      (*ai)->writeTemplateInstantiationArgs(OS);
    }
    OS << ", A->getSpellingListIndex());\n    }\n";
  }
  OS << "  } // end switch\n"
     << "  llvm_unreachable(\"Unknown attribute!\");\n"
     << "  return 0;\n"
     << "}\n\n"
     << "} // end namespace sema\n"
     << "} // end namespace clang\n";
}

// Emits the list of parsed attributes.
void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);

  OS << "#ifndef PARSED_ATTR\n";
  OS << "#define PARSED_ATTR(NAME) NAME\n";
  OS << "#endif\n\n";
  
  ParsedAttrMap Names = getParsedAttrList(Records);
  for (ParsedAttrMap::iterator I = Names.begin(), E = Names.end(); I != E;
       ++I) {
    OS << "PARSED_ATTR(" << I->first << ")\n";
  }
}

static void emitArgInfo(const Record &R, std::stringstream &OS) {
  // This function will count the number of arguments specified for the
  // attribute and emit the number of required arguments followed by the
  // number of optional arguments.
  std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
  unsigned ArgCount = 0, OptCount = 0;
  for (std::vector<Record *>::const_iterator I = Args.begin(), E = Args.end();
       I != E; ++I) {
    const Record &Arg = **I;
    Arg.getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
  }
  OS << ArgCount << ", " << OptCount;
}

static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
  OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
  OS << "const Decl *) {\n";
  OS << "  return true;\n";
  OS << "}\n\n";
}

static std::string CalculateDiagnostic(const Record &S) {
  // If the SubjectList object has a custom diagnostic associated with it,
  // return that directly.
  std::string CustomDiag = S.getValueAsString("CustomDiag");
  if (!CustomDiag.empty())
    return CustomDiag;

  // Given the list of subjects, determine what diagnostic best fits.
  enum {
    Func = 1U << 0,
    Var = 1U << 1,
    ObjCMethod = 1U << 2,
    Param = 1U << 3,
    Class = 1U << 4,
    GenericRecord = 1U << 5,
    Type = 1U << 6,
    ObjCIVar = 1U << 7,
    ObjCProp = 1U << 8,
    ObjCInterface = 1U << 9,
    Block = 1U << 10,
    Namespace = 1U << 11,
    FuncTemplate = 1U << 12,
    Field = 1U << 13,
    CXXMethod = 1U << 14,
    ObjCProtocol = 1U << 15
  };
  uint32_t SubMask = 0;

  std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
  for (std::vector<Record *>::const_iterator I = Subjects.begin(),
       E = Subjects.end(); I != E; ++I) {
    const Record &R = (**I);
    std::string Name;

    if (R.isSubClassOf("SubsetSubject")) {
      PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
      // As a fallback, look through the SubsetSubject to see what its base
      // type is, and use that. This needs to be updated if SubsetSubjects
      // are allowed within other SubsetSubjects.
      Name = R.getValueAsDef("Base")->getName();
    } else
      Name = R.getName();

    uint32_t V = StringSwitch<uint32_t>(Name)
                   .Case("Function", Func)
                   .Case("Var", Var)
                   .Case("ObjCMethod", ObjCMethod)
                   .Case("ParmVar", Param)
                   .Case("TypedefName", Type)
                   .Case("ObjCIvar", ObjCIVar)
                   .Case("ObjCProperty", ObjCProp)
                   .Case("Record", GenericRecord)
                   .Case("ObjCInterface", ObjCInterface)
                   .Case("ObjCProtocol", ObjCProtocol)
                   .Case("Block", Block)
                   .Case("CXXRecord", Class)
                   .Case("Namespace", Namespace)
                   .Case("FunctionTemplate", FuncTemplate)
                   .Case("Field", Field)
                   .Case("CXXMethod", CXXMethod)
                   .Default(0);
    if (!V) {
      // Something wasn't in our mapping, so be helpful and let the developer
      // know about it.
      PrintFatalError((*I)->getLoc(), "Unknown subject type: " +
                      (*I)->getName());
      return "";
    }

    SubMask |= V;
  }

  switch (SubMask) {
    // For the simple cases where there's only a single entry in the mask, we
    // don't have to resort to bit fiddling.
    case Func:  return "ExpectedFunction";
    case Var:   return "ExpectedVariable";
    case Param: return "ExpectedParameter";
    case Class: return "ExpectedClass";
    case CXXMethod:
      // FIXME: Currently, this maps to ExpectedMethod based on existing code,
      // but should map to something a bit more accurate at some point.
    case ObjCMethod:  return "ExpectedMethod";
    case Type:  return "ExpectedType";
    case ObjCInterface: return "ExpectedObjectiveCInterface";
    case ObjCProtocol: return "ExpectedObjectiveCProtocol";
    
    // "GenericRecord" means struct, union or class; check the language options
    // and if not compiling for C++, strip off the class part. Note that this
    // relies on the fact that the context for this declares "Sema &S".
    case GenericRecord:
      return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
                                           "ExpectedStructOrUnion)";
    case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
    case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
    case Func | Param:
    case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
    case Func | FuncTemplate:
    case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
    case Func | Var: return "ExpectedVariableOrFunction";

    // If not compiling for C++, the class portion does not apply.
    case Func | Var | Class:
      return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
                                           "ExpectedVariableOrFunction)";

    case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
    case Field | Var: return "ExpectedFieldOrGlobalVar";
  }

  PrintFatalError(S.getLoc(),
                  "Could not deduce diagnostic argument for Attr subjects");

  return "";
}

static std::string GetSubjectWithSuffix(const Record *R) {
  std::string B = R->getName();
  if (B == "DeclBase")
    return "Decl";
  return B + "Decl";
}
static std::string GenerateCustomAppertainsTo(const Record &Subject,
                                              raw_ostream &OS) {
  std::string FnName = "is" + Subject.getName();

  // If this code has already been generated, simply return the previous
  // instance of it.
  static std::set<std::string> CustomSubjectSet;
  std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
  if (I != CustomSubjectSet.end())
    return *I;

  Record *Base = Subject.getValueAsDef("Base");

  // Not currently support custom subjects within custom subjects.
  if (Base->isSubClassOf("SubsetSubject")) {
    PrintFatalError(Subject.getLoc(),
                    "SubsetSubjects within SubsetSubjects is not supported");
    return "";
  }

  OS << "static bool " << FnName << "(const Decl *D) {\n";
  OS << "  if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
  OS << GetSubjectWithSuffix(Base);
  OS << ">(D))\n";
  OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
  OS << "  return false;\n";
  OS << "}\n\n";

  CustomSubjectSet.insert(FnName);
  return FnName;
}

static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
  // If the attribute does not contain a Subjects definition, then use the
  // default appertainsTo logic.
  if (Attr.isValueUnset("Subjects"))
    return "defaultAppertainsTo";

  const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");

  // If the list of subjects is empty, it is assumed that the attribute
  // appertains to everything.
  if (Subjects.empty())
    return "defaultAppertainsTo";

  bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");

  // Otherwise, generate an appertainsTo check specific to this attribute which
  // checks all of the given subjects against the Decl passed in. Return the
  // name of that check to the caller.
  std::string FnName = "check" + Attr.getName() + "AppertainsTo";
  std::stringstream SS;
  SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
  SS << "const Decl *D) {\n";
  SS << "  if (";
  for (std::vector<Record *>::const_iterator I = Subjects.begin(),
       E = Subjects.end(); I != E; ++I) {
    // If the subject has custom code associated with it, generate a function
    // for it. The function cannot be inlined into this check (yet) because it
    // requires the subject to be of a specific type, and were that information
    // inlined here, it would not support an attribute with multiple custom
    // subjects.
    if ((*I)->isSubClassOf("SubsetSubject")) {
      SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
    } else {
      SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
    }

    if (I + 1 != E)
      SS << " && ";
  }
  SS << ") {\n";
  SS << "    S.Diag(Attr.getLoc(), diag::";
  SS << (Warn ? "warn_attribute_wrong_decl_type" :
               "err_attribute_wrong_decl_type");
  SS << ")\n";
  SS << "      << Attr.getName() << ";
  SS << CalculateDiagnostic(*SubjectObj) << ";\n";
  SS << "    return false;\n";
  SS << "  }\n";
  SS << "  return true;\n";
  SS << "}\n\n";

  OS << SS.str();
  return FnName;
}

static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
  OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
  OS << "const AttributeList &) {\n";
  OS << "  return true;\n";
  OS << "}\n\n";
}

static std::string GenerateLangOptRequirements(const Record &R,
                                               raw_ostream &OS) {
  // If the attribute has an empty or unset list of language requirements,
  // return the default handler.
  std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
  if (LangOpts.empty())
    return "defaultDiagnoseLangOpts";

  // Generate the test condition, as well as a unique function name for the
  // diagnostic test. The list of options should usually be short (one or two
  // options), and the uniqueness isn't strictly necessary (it is just for
  // codegen efficiency).
  std::string FnName = "check", Test;
  for (std::vector<Record *>::const_iterator I = LangOpts.begin(),
       E = LangOpts.end(); I != E; ++I) {
    std::string Part = (*I)->getValueAsString("Name");
    Test += "S.LangOpts." + Part;
    if (I + 1 != E)
      Test += " || ";
    FnName += Part;
  }
  FnName += "LangOpts";

  // If this code has already been generated, simply return the previous
  // instance of it.
  static std::set<std::string> CustomLangOptsSet;
  std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
  if (I != CustomLangOptsSet.end())
    return *I;

  OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
  OS << "  if (" << Test << ")\n";
  OS << "    return true;\n\n";
  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
  OS << "<< Attr.getName();\n";
  OS << "  return false;\n";
  OS << "}\n\n";

  CustomLangOptsSet.insert(FnName);
  return FnName;
}

static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
  OS << "static bool defaultTargetRequirements(llvm::Triple) {\n";
  OS << "  return true;\n";
  OS << "}\n\n";
}

static std::string GenerateTargetRequirements(const Record &Attr,
                                              const ParsedAttrMap &Dupes,
                                              raw_ostream &OS) {
  // If the attribute is not a target specific attribute, return the default
  // target handler.
  if (!Attr.isSubClassOf("TargetSpecificAttr"))
    return "defaultTargetRequirements";

  // Get the list of architectures to be tested for.
  const Record *R = Attr.getValueAsDef("Target");
  std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
  if (Arches.empty()) {
    PrintError(Attr.getLoc(), "Empty list of target architectures for a "
                              "target-specific attr");
    return "defaultTargetRequirements";
  }

  // If there are other attributes which share the same parsed attribute kind,
  // such as target-specific attributes with a shared spelling, collapse the
  // duplicate architectures. This is required because a shared target-specific
  // attribute has only one AttributeList::Kind enumeration value, but it
  // applies to multiple target architectures. In order for the attribute to be
  // considered valid, all of its architectures need to be included.
  if (!Attr.isValueUnset("ParseKind")) {
    std::string APK = Attr.getValueAsString("ParseKind");
    for (ParsedAttrMap::const_iterator I = Dupes.begin(), E = Dupes.end();
         I != E; ++I) {
      if (I->first == APK) {
        std::vector<std::string> DA = I->second->getValueAsDef("Target")->
                                            getValueAsListOfStrings("Arches");
        std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
      }
    }
  }

  std::string FnName = "isTarget", Test = "(";
  for (std::vector<std::string>::const_iterator I = Arches.begin(),
       E = Arches.end(); I != E; ++I) {
    std::string Part = *I;
    Test += "Arch == llvm::Triple::" + Part;
    if (I + 1 != E)
      Test += " || ";
    FnName += Part;
  }
  Test += ")";

  // If the target also requires OS testing, generate those tests as well.
  bool UsesOS = false;
  if (!R->isValueUnset("OSes")) {
    UsesOS = true;
    
    // We know that there was at least one arch test, so we need to and in the
    // OS tests.
    Test += " && (";
    std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
    for (std::vector<std::string>::const_iterator I = OSes.begin(),
         E = OSes.end(); I != E; ++I) {
      std::string Part = *I;

      Test += "OS == llvm::Triple::" + Part;
      if (I + 1 != E)
        Test += " || ";
      FnName += Part;
    }
    Test += ")";
  }

  // If this code has already been generated, simply return the previous
  // instance of it.
  static std::set<std::string> CustomTargetSet;
  std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
  if (I != CustomTargetSet.end())
    return *I;

  OS << "static bool " << FnName << "(llvm::Triple T) {\n";
  OS << "  llvm::Triple::ArchType Arch = T.getArch();\n";
  if (UsesOS)
    OS << "  llvm::Triple::OSType OS = T.getOS();\n";
  OS << "  return " << Test << ";\n";
  OS << "}\n\n";

  CustomTargetSet.insert(FnName);
  return FnName;
}

static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
  OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
     << "const AttributeList &Attr) {\n";
  OS << "  return UINT_MAX;\n";
  OS << "}\n\n";
}

static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
                                                           raw_ostream &OS) {
  // If the attribute does not have a semantic form, we can bail out early.
  if (!Attr.getValueAsBit("ASTNode"))
    return "defaultSpellingIndexToSemanticSpelling";

  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);

  // If there are zero or one spellings, or all of the spellings share the same
  // name, we can also bail out early.
  if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
    return "defaultSpellingIndexToSemanticSpelling";

  // Generate the enumeration we will use for the mapping.
  SemanticSpellingMap SemanticToSyntacticMap;
  std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
  std::string Name = Attr.getName() + "AttrSpellingMap";

  OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
  OS << Enum;
  OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
  WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
  OS << "}\n\n";

  return Name;
}

static bool IsKnownToGCC(const Record &Attr) {
  // Look at the spellings for this subject; if there are any spellings which
  // claim to be known to GCC, the attribute is known to GCC.
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
       E = Spellings.end(); I != E; ++I) {
    if (I->knownToGCC())
      return true;
  }
  return false;
}

/// Emits the parsed attribute helpers
void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Parsed attribute helpers", OS);

  // Get the list of parsed attributes, and accept the optional list of
  // duplicates due to the ParseKind.
  ParsedAttrMap Dupes;
  ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);

  // Generate the default appertainsTo, target and language option diagnostic,
  // and spelling list index mapping methods.
  GenerateDefaultAppertainsTo(OS);
  GenerateDefaultLangOptRequirements(OS);
  GenerateDefaultTargetRequirements(OS);
  GenerateDefaultSpellingIndexToSemanticSpelling(OS);

  // Generate the appertainsTo diagnostic methods and write their names into
  // another mapping. At the same time, generate the AttrInfoMap object
  // contents. Due to the reliance on generated code, use separate streams so
  // that code will not be interleaved.
  std::stringstream SS;
  for (ParsedAttrMap::iterator I = Attrs.begin(), E = Attrs.end(); I != E;
       ++I) {
    // TODO: If the attribute's kind appears in the list of duplicates, that is
    // because it is a target-specific attribute that appears multiple times.
    // It would be beneficial to test whether the duplicates are "similar
    // enough" to each other to not cause problems. For instance, check that
    // the spellings are identical, and custom parsing rules match, etc.

    // We need to generate struct instances based off ParsedAttrInfo from
    // AttributeList.cpp.
    SS << "  { ";
    emitArgInfo(*I->second, SS);
    SS << ", " << I->second->getValueAsBit("HasCustomParsing");
    SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
    SS << ", " << I->second->isSubClassOf("TypeAttr");
    SS << ", " << IsKnownToGCC(*I->second);
    SS << ", " << GenerateAppertainsTo(*I->second, OS);
    SS << ", " << GenerateLangOptRequirements(*I->second, OS);
    SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
    SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
    SS << " }";

    if (I + 1 != E)
      SS << ",";

    SS << "  // AT_" << I->first << "\n";
  }

  OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
  OS << SS.str();
  OS << "};\n\n";
}

// Emits the kind list of parsed attributes
void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute name matcher", OS);

  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords;
  std::set<std::string> Seen;
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &Attr = **I;

    bool SemaHandler = Attr.getValueAsBit("SemaHandler");
    bool Ignored = Attr.getValueAsBit("Ignored");
    if (SemaHandler || Ignored) {
      // Attribute spellings can be shared between target-specific attributes,
      // and can be shared between syntaxes for the same attribute. For
      // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
      // specific attribute, or MSP430-specific attribute. Additionally, an
      // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
      // for the same semantic attribute. Ultimately, we need to map each of
      // these to a single AttributeList::Kind value, but the StringMatcher
      // class cannot handle duplicate match strings. So we generate a list of
      // string to match based on the syntax, and emit multiple string matchers
      // depending on the syntax used.
      std::string AttrName;
      if (Attr.isSubClassOf("TargetSpecificAttr") &&
          !Attr.isValueUnset("ParseKind")) {
        AttrName = Attr.getValueAsString("ParseKind");
        if (Seen.find(AttrName) != Seen.end())
          continue;
        Seen.insert(AttrName);
      } else
        AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();

      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
      for (std::vector<FlattenedSpelling>::const_iterator
           I = Spellings.begin(), E = Spellings.end(); I != E; ++I) {
        std::string RawSpelling = I->name();
        std::vector<StringMatcher::StringPair> *Matches = 0;
        std::string Spelling, Variety = I->variety();
        if (Variety == "CXX11") {
          Matches = &CXX11;
          Spelling += I->nameSpace();
          Spelling += "::";
        } else if (Variety == "GNU")
          Matches = &GNU;
        else if (Variety == "Declspec")
          Matches = &Declspec;
        else if (Variety == "Keyword")
          Matches = &Keywords;

        assert(Matches && "Unsupported spelling variety found");

        Spelling += NormalizeAttrSpelling(RawSpelling);
        if (SemaHandler)
          Matches->push_back(StringMatcher::StringPair(Spelling,
                              "return AttributeList::AT_" + AttrName + ";"));
        else
          Matches->push_back(StringMatcher::StringPair(Spelling,
                              "return AttributeList::IgnoredAttribute;"));
      }
    }
  }
  
  OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
  OS << "AttributeList::Syntax Syntax) {\n";
  OS << "  if (AttributeList::AS_GNU == Syntax) {\n";
  StringMatcher("Name", GNU, OS).Emit();
  OS << "  } else if (AttributeList::AS_Declspec == Syntax) {\n";
  StringMatcher("Name", Declspec, OS).Emit();
  OS << "  } else if (AttributeList::AS_CXX11 == Syntax) {\n";
  StringMatcher("Name", CXX11, OS).Emit();
  OS << "  } else if (AttributeList::AS_Keyword == Syntax) {\n";
  StringMatcher("Name", Keywords, OS).Emit();
  OS << "  }\n";
  OS << "  return AttributeList::UnknownAttribute;\n"
     << "}\n";
}

// Emits the code to dump an attribute.
void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
  emitSourceFileHeader("Attribute dumper", OS);

  OS <<
    "  switch (A->getKind()) {\n"
    "  default:\n"
    "    llvm_unreachable(\"Unknown attribute kind!\");\n"
    "    break;\n";
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
       I != E; ++I) {
    Record &R = **I;
    if (!R.getValueAsBit("ASTNode"))
      continue;
    OS << "  case attr::" << R.getName() << ": {\n";

    // If the attribute has a semantically-meaningful name (which is determined
    // by whether there is a Spelling enumeration for it), then write out the
    // spelling used for the attribute.
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
    if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
      OS << "    OS << \" \" << A->getSpelling();\n";

    Args = R.getValueAsListOfDefs("Args");
    if (!Args.empty()) {
      OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
         << "Attr>(A);\n";
      for (std::vector<Record*>::iterator I = Args.begin(), E = Args.end();
           I != E; ++I)
        createArgument(**I, R.getName())->writeDump(OS);

      // Code for detecting the last child.
      OS << "    bool OldMoreChildren = hasMoreChildren();\n";
      OS << "    bool MoreChildren = OldMoreChildren;\n";     

      for (std::vector<Record*>::iterator I = Args.begin(), E = Args.end();
           I != E; ++I) {
        // More code for detecting the last child.
        OS << "    MoreChildren = OldMoreChildren";
        for (std::vector<Record*>::iterator Next = I + 1; Next != E; ++Next) {
          OS << " || ";
          createArgument(**Next, R.getName())->writeHasChildren(OS);
        }
        OS << ";\n";
        OS << "    setMoreChildren(MoreChildren);\n";

        createArgument(**I, R.getName())->writeDumpChildren(OS);
      }

      // Reset the last child.
      OS << "    setMoreChildren(OldMoreChildren);\n";
    }
    OS <<
      "    break;\n"
      "  }\n";
  }
  OS << "  }\n";
}

void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
                                       raw_ostream &OS) {
  emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
  emitClangAttrArgContextList(Records, OS);
  emitClangAttrIdentifierArgList(Records, OS);
  emitClangAttrTypeArgList(Records, OS);
  emitClangAttrLateParsedList(Records, OS);
}

class DocumentationData {
public:
  const Record *Documentation;
  const Record *Attribute;

  DocumentationData(const Record &Documentation, const Record &Attribute)
      : Documentation(&Documentation), Attribute(&Attribute) {}
};

static void WriteCategoryHeader(const Record *DocCategory,
                                raw_ostream &OS) {
  const std::string &Name = DocCategory->getValueAsString("Name");
  OS << Name << "\n" << std::string(Name.length(), '=') << "\n";

  // If there is content, print that as well.
  std::string ContentStr = DocCategory->getValueAsString("Content");
  if (!ContentStr.empty()) {
    // Trim leading and trailing newlines and spaces.
    StringRef Content(ContentStr);
    while (Content.startswith("\r") || Content.startswith("\n") ||
           Content.startswith(" ") || Content.startswith("\t"))
           Content = Content.substr(1);
    while (Content.endswith("\r") || Content.endswith("\n") ||
           Content.endswith(" ") || Content.endswith("\t"))
           Content = Content.substr(0, Content.size() - 1);
    OS << Content;
  }
  OS << "\n\n";
}

enum SpellingKind {
  GNU = 1 << 0,
  CXX11 = 1 << 1,
  Declspec = 1 << 2,
  Keyword = 1 << 3
};

static void WriteDocumentation(const DocumentationData &Doc,
                               raw_ostream &OS) {
  // FIXME: there is no way to have a per-spelling category for the attribute
  // documentation. This may not be a limiting factor since the spellings
  // should generally be consistently applied across the category.

  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);

  // Determine the heading to be used for this attribute.
  std::string Heading = Doc.Documentation->getValueAsString("Heading");
  bool CustomHeading = !Heading.empty();
  if (Heading.empty()) {
    // If there's only one spelling, we can simply use that.
    if (Spellings.size() == 1)
      Heading = Spellings.begin()->name();
    else {
      std::set<std::string> Uniques;
      for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
           E = Spellings.end(); I != E && Uniques.size() <= 1; ++I) {
        std::string Spelling = NormalizeNameForSpellingComparison(I->name());
        Uniques.insert(Spelling);
      }
      // If the semantic map has only one spelling, that is sufficient for our
      // needs.
      if (Uniques.size() == 1)
        Heading = *Uniques.begin();
    }
  }

  // If the heading is still empty, it is an error.
  if (Heading.empty())
    PrintFatalError(Doc.Attribute->getLoc(),
                    "This attribute requires a heading to be specified");

  // Gather a list of unique spellings; this is not the same as the semantic
  // spelling for the attribute. Variations in underscores and other non-
  // semantic characters are still acceptable.
  std::vector<std::string> Names;

  unsigned SupportedSpellings = 0;
  for (std::vector<FlattenedSpelling>::const_iterator I = Spellings.begin(),
       E = Spellings.end(); I != E; ++I) {
    SpellingKind Kind = StringSwitch<SpellingKind>(I->variety())
      .Case("GNU", GNU)
      .Case("CXX11", CXX11)
      .Case("Declspec", Declspec)
      .Case("Keyword", Keyword);

    // Mask in the supported spelling.
    SupportedSpellings |= Kind;

    std::string Name;
    if (Kind == CXX11 && !I->nameSpace().empty())
      Name = I->nameSpace() + "::";
    Name += I->name();

    // If this name is the same as the heading, do not add it.
    if (Name != Heading)
      Names.push_back(Name);
  }

  // Print out the heading for the attribute. If there are alternate spellings,
  // then display those after the heading.
  if (!CustomHeading && !Names.empty()) {
    Heading += " (";
    for (std::vector<std::string>::const_iterator I = Names.begin(),
         E = Names.end(); I != E; ++I) {
      if (I != Names.begin())
        Heading += ", ";
      Heading += *I;
    }
    Heading += ")";
  }
  OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";

  if (!SupportedSpellings)
    PrintFatalError(Doc.Attribute->getLoc(),
                    "Attribute has no supported spellings; cannot be "
                    "documented");

  // List what spelling syntaxes the attribute supports.
  OS << ".. csv-table:: Supported Syntaxes\n";
  OS << "   :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\"\n\n";
  OS << "   \"";
  if (SupportedSpellings & GNU) OS << "X";
  OS << "\",\"";
  if (SupportedSpellings & CXX11) OS << "X";
  OS << "\",\"";
  if (SupportedSpellings & Declspec) OS << "X";
  OS << "\",\"";
  if (SupportedSpellings & Keyword) OS << "X";
  OS << "\"\n\n";

  // If the attribute is deprecated, print a message about it, and possibly
  // provide a replacement attribute.
  if (!Doc.Documentation->isValueUnset("Deprecated")) {
    OS << "This attribute has been deprecated, and may be removed in a future "
       << "version of Clang.";
    const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
    std::string Replacement = Deprecated.getValueAsString("Replacement");
    if (!Replacement.empty())
      OS << "  This attribute has been superseded by ``"
         << Replacement << "``.";
    OS << "\n\n";
  }

  std::string ContentStr = Doc.Documentation->getValueAsString("Content");
  // Trim leading and trailing newlines and spaces.
  StringRef Content(ContentStr);
  while (Content.startswith("\r") || Content.startswith("\n") ||
         Content.startswith(" ") || Content.startswith("\t"))
    Content = Content.substr(1);
  while (Content.endswith("\r") || Content.endswith("\n") ||
         Content.endswith(" ") || Content.endswith("\t"))
    Content = Content.substr(0, Content.size() - 1);
  OS << Content;

  OS << "\n\n\n";
}

void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
  // Get the documentation introduction paragraph.
  const Record *Documentation = Records.getDef("GlobalDocumentation");
  if (!Documentation) {
    PrintFatalError("The Documentation top-level definition is missing, "
                    "no documentation will be generated.");
    return;
  }

  OS << Documentation->getValueAsString("Intro") << "\n";

  typedef std::map<const Record *,
                   std::vector<DocumentationData> > CategoryMap;
  CategoryMap SplitDocs;

  // Gather the Documentation lists from each of the attributes, based on the
  // category provided.
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  for (std::vector<Record *>::const_iterator I = Attrs.begin(),
       E = Attrs.end(); I != E; ++I) {
    const Record &Attr = **I;
    std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
    for (std::vector<Record *>::const_iterator DI = Docs.begin(),
         DE = Docs.end(); DI != DE; ++DI) {
      const Record &Doc = **DI;
      const Record *Category = Doc.getValueAsDef("Category");
      // If the category is "undocumented", then there cannot be any other
      // documentation categories (otherwise, the attribute would become
      // documented).
      std::string Cat = Category->getValueAsString("Name");
      bool Undocumented = Cat == "Undocumented";
      if (Undocumented && Docs.size() > 1)
        PrintFatalError(Doc.getLoc(),
                        "Attribute is \"Undocumented\", but has multiple "
                        "documentation categories");      

      if (!Undocumented)
        SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
    }
  }

  // Having split the attributes out based on what documentation goes where,
  // we can begin to generate sections of documentation.
  for (CategoryMap::const_iterator I = SplitDocs.begin(), E = SplitDocs.end();
       I != E; ++I) {
    WriteCategoryHeader(I->first, OS);

    // Walk over each of the attributes in the category and write out their
    // documentation.
    for (std::vector<DocumentationData>::const_iterator D = I->second.begin(),
         DE = I->second.end(); D != DE; ++D)
      WriteDocumentation(*D, OS);
  }
}

} // end namespace clang
@


