diff --git a/cpp/llvm/.DS_Store b/cpp/llvm/.DS_Store new file mode 100644 index 00000000..db4cc611 Binary files /dev/null and b/cpp/llvm/.DS_Store differ diff --git a/cpp/llvm/Makefile b/cpp/llvm/Makefile new file mode 100644 index 00000000..ec24862a --- /dev/null +++ b/cpp/llvm/Makefile @@ -0,0 +1,268 @@ +#===- ./Makefile -------------------------------------------*- Makefile -*--===# +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +#===------------------------------------------------------------------------===# + +LEVEL := . + +# Top-Level LLVM Build Stages: +# 1. Build lib/Support and lib/TableGen, which are used by utils (tblgen). +# 2. Build utils, which is used by VMCore. +# 3. Build VMCore, which builds the Intrinsics.inc file used by libs. +# 4. Build libs, which are needed by llvm-config. +# 5. Build llvm-config, which determines inter-lib dependencies for tools. +# 6. Build tools, runtime, docs. +# +# When cross-compiling, there are some things (tablegen) that need to +# be build for the build system first. + +# If "RC_ProjectName" exists in the environment, and its value is +# "llvmCore", then this is an "Apple-style" build; search for +# "Apple-style" in the comments for more info. Anything else is a +# normal build. +ifneq ($(findstring llvmCore, $(RC_ProjectName)),llvmCore) # Normal build (not "Apple-style"). + +ifeq ($(BUILD_DIRS_ONLY),1) + DIRS := lib/Support lib/TableGen utils tools/llvm-config + OPTIONAL_DIRS := tools/clang/utils/TableGen +else + DIRS := lib/Support lib/TableGen utils lib/VMCore lib tools/llvm-shlib \ + tools/llvm-config tools runtime docs unittests + OPTIONAL_DIRS := projects bindings +endif + +ifeq ($(BUILD_EXAMPLES),1) + OPTIONAL_DIRS += examples +endif + +EXTRA_DIST := test unittests llvm.spec include win32 Xcode + +include $(LEVEL)/Makefile.config + +ifneq ($(ENABLE_SHARED),1) + DIRS := $(filter-out tools/llvm-shlib, $(DIRS)) +endif + +ifneq ($(ENABLE_DOCS),1) + DIRS := $(filter-out docs, $(DIRS)) +endif + +ifeq ($(MAKECMDGOALS),libs-only) + DIRS := $(filter-out tools runtime docs, $(DIRS)) + OPTIONAL_DIRS := +endif + +ifeq ($(MAKECMDGOALS),install-libs) + DIRS := $(filter-out tools runtime docs, $(DIRS)) + OPTIONAL_DIRS := $(filter bindings, $(OPTIONAL_DIRS)) +endif + +ifeq ($(MAKECMDGOALS),tools-only) + DIRS := $(filter-out runtime docs, $(DIRS)) + OPTIONAL_DIRS := +endif + +ifeq ($(MAKECMDGOALS),install-clang) + DIRS := tools/clang/tools/driver tools/clang/lib/Headers \ + tools/clang/tools/libclang tools/clang/tools/c-index-test \ + tools/clang/include/clang-c \ + tools/clang/runtime tools/clang/docs \ + tools/lto runtime + OPTIONAL_DIRS := + NO_INSTALL = 1 +endif + +ifeq ($(MAKECMDGOALS),clang-only) + DIRS := $(filter-out tools docs unittests, $(DIRS)) \ + tools/clang tools/lto + OPTIONAL_DIRS := +endif + +ifeq ($(MAKECMDGOALS),unittests) + DIRS := $(filter-out tools runtime docs, $(DIRS)) utils unittests + OPTIONAL_DIRS := +endif + +# Use NO_INSTALL define of the Makefile of each directory for deciding +# if the directory is installed or not +ifeq ($(MAKECMDGOALS),install) + OPTIONAL_DIRS := $(filter bindings, $(OPTIONAL_DIRS)) +endif + +# Don't build unittests when ONLY_TOOLS is set. +ifneq ($(ONLY_TOOLS),) + DIRS := $(filter-out unittests, $(DIRS)) +endif + +# If we're cross-compiling, build the build-hosted tools first +ifeq ($(LLVM_CROSS_COMPILING),1) +all:: cross-compile-build-tools + +clean:: + $(Verb) rm -rf BuildTools + +cross-compile-build-tools: + $(Verb) if [ ! -f BuildTools/Makefile ]; then \ + $(MKDIR) BuildTools; \ + cd BuildTools ; \ + unset CFLAGS ; \ + unset CXXFLAGS ; \ + $(PROJ_SRC_DIR)/configure --build=$(BUILD_TRIPLE) \ + --host=$(BUILD_TRIPLE) --target=$(BUILD_TRIPLE) \ + --disable-polly ; \ + cd .. ; \ + fi; \ + (unset SDKROOT; \ + $(MAKE) -C BuildTools \ + BUILD_DIRS_ONLY=1 \ + UNIVERSAL= \ + TARGET_NATIVE_ARCH="$(TARGET_NATIVE_ARCH)" \ + TARGETS_TO_BUILD="$(TARGETS_TO_BUILD)" \ + ENABLE_OPTIMIZED=$(ENABLE_OPTIMIZED) \ + ENABLE_PROFILING=$(ENABLE_PROFILING) \ + ENABLE_COVERAGE=$(ENABLE_COVERAGE) \ + DISABLE_ASSERTIONS=$(DISABLE_ASSERTIONS) \ + ENABLE_EXPENSIVE_CHECKS=$(ENABLE_EXPENSIVE_CHECKS) \ + ENABLE_LIBCPP=$(ENABLE_LIBCPP) \ + CFLAGS= \ + CXXFLAGS= \ + ) || exit 1; +endif + +# Include the main makefile machinery. +include $(LLVM_SRC_ROOT)/Makefile.rules + +# Specify options to pass to configure script when we're +# running the dist-check target +DIST_CHECK_CONFIG_OPTIONS = --with-llvmgccdir=$(LLVMGCCDIR) + +.PHONY: debug-opt-prof +debug-opt-prof: + $(Echo) Building Debug Version + $(Verb) $(MAKE) + $(Echo) + $(Echo) Building Optimized Version + $(Echo) + $(Verb) $(MAKE) ENABLE_OPTIMIZED=1 + $(Echo) + $(Echo) Building Profiling Version + $(Echo) + $(Verb) $(MAKE) ENABLE_PROFILING=1 + +dist-hook:: + $(Echo) Eliminating files constructed by configure + $(Verb) $(RM) -f \ + $(TopDistDir)/include/llvm/Config/config.h \ + $(TopDistDir)/include/llvm/Support/DataTypes.h + +clang-only: all +tools-only: all +libs-only: all +install-clang: install +install-libs: install + +# If SHOW_DIAGNOSTICS is enabled, clear the diagnostics file first. +ifeq ($(SHOW_DIAGNOSTICS),1) +clean-diagnostics: + $(Verb) rm -f $(LLVM_OBJ_ROOT)/$(BuildMode)/diags +.PHONY: clean-diagnostics + +all-local:: clean-diagnostics +endif + +#------------------------------------------------------------------------ +# Make sure the generated files are up-to-date. This must be kept in +# sync with the AC_CONFIG_HEADER and AC_CONFIG_FILE invocations in +# autoconf/configure.ac. +# Note that Makefile.config is covered by its own separate rule +# in Makefile.rules where it can be reused by sub-projects. +#------------------------------------------------------------------------ +FilesToConfig := \ + bindings/ocaml/llvm/META.llvm \ + docs/doxygen.cfg \ + llvm.spec \ + include/llvm/Config/config.h \ + include/llvm/Config/llvm-config.h \ + include/llvm/Config/Targets.def \ + include/llvm/Config/AsmPrinters.def \ + include/llvm/Config/AsmParsers.def \ + include/llvm/Config/Disassemblers.def \ + include/llvm/Support/DataTypes.h +FilesToConfigPATH := $(addprefix $(LLVM_OBJ_ROOT)/,$(FilesToConfig)) + +all-local:: $(FilesToConfigPATH) +$(FilesToConfigPATH) : $(LLVM_OBJ_ROOT)/% : $(LLVM_SRC_ROOT)/%.in + $(Echo) Regenerating $* + $(Verb) cd $(LLVM_OBJ_ROOT) && $(ConfigStatusScript) $* +.PRECIOUS: $(FilesToConfigPATH) + +# NOTE: This needs to remain as the last target definition in this file so +# that it gets executed last. +ifneq ($(BUILD_DIRS_ONLY),1) +all:: + $(Echo) '*****' Completed $(BuildMode) Build +ifneq ($(ENABLE_OPTIMIZED),1) + $(Echo) '*****' Note: Debug build can be 10 times slower than an + $(Echo) '*****' optimized build. Use 'make ENABLE_OPTIMIZED=1' to + $(Echo) '*****' make an optimized build. Alternatively you can + $(Echo) '*****' configure with --enable-optimized. +ifeq ($(SHOW_DIAGNOSTICS),1) + $(Verb) if test -s $(LLVM_OBJ_ROOT)/$(BuildMode)/diags; then \ + $(LLVM_SRC_ROOT)/utils/clang-parse-diagnostics-file -a \ + $(LLVM_OBJ_ROOT)/$(BuildMode)/diags; \ + fi +endif +endif +endif + +check-llvm2cpp: + $(Verb)$(MAKE) check TESTSUITE=Feature RUNLLVM2CPP=1 + +srpm: $(LLVM_OBJ_ROOT)/llvm.spec + rpmbuild -bs $(LLVM_OBJ_ROOT)/llvm.spec + +rpm: $(LLVM_OBJ_ROOT)/llvm.spec + rpmbuild -bb --target $(TARGET_TRIPLE) $(LLVM_OBJ_ROOT)/llvm.spec + +show-footprint: + $(Verb) du -sk $(LibDir) + $(Verb) du -sk $(ToolDir) + $(Verb) du -sk $(ExmplDir) + $(Verb) du -sk $(ObjDir) + +build-for-llvm-top: + $(Verb) if test ! -f ./config.status ; then \ + ./configure --prefix="$(LLVM_TOP)/install" \ + --with-llvm-gcc="$(LLVM_TOP)/llvm-gcc" ; \ + fi + $(Verb) $(MAKE) tools-only + +SVN = svn +SVN-UPDATE-OPTIONS = +AWK = awk +SUB-SVN-DIRS = $(AWK) '/\?\ \ \ \ \ \ / {print $$2}' \ + | LC_ALL=C xargs $(SVN) info 2>/dev/null \ + | $(AWK) '/^Path:\ / {print $$2}' + +update: + $(SVN) $(SVN-UPDATE-OPTIONS) update $(LLVM_SRC_ROOT) + @ $(SVN) status $(LLVM_SRC_ROOT) | $(SUB-SVN-DIRS) | xargs $(SVN) $(SVN-UPDATE-OPTIONS) update + +happiness: update all check-all + +.PHONY: srpm rpm update happiness + +# declare all targets at this level to be serial: + +.NOTPARALLEL: + +else # Building "Apple-style." +# In an Apple-style build, once configuration is done, lines marked +# "Apple-style" are removed with sed! Please don't remove these! +# Look for the string "Apple-style" in utils/buildit/build_llvm. +include $(shell find . -name GNUmakefile) # Building "Apple-style." +endif # Building "Apple-style." diff --git a/cpp/llvm/bindings/Makefile b/cpp/llvm/bindings/Makefile new file mode 100644 index 00000000..c545b288 --- /dev/null +++ b/cpp/llvm/bindings/Makefile @@ -0,0 +1,16 @@ +##===- bindings/Makefile -----------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := .. + +include $(LEVEL)/Makefile.config + +PARALLEL_DIRS = $(BINDINGS_TO_BUILD) + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/bindings/ocaml/Makefile b/cpp/llvm/bindings/ocaml/Makefile new file mode 100644 index 00000000..a89caefb --- /dev/null +++ b/cpp/llvm/bindings/ocaml/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/Makefile -----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../.. +DIRS = llvm bitreader bitwriter analysis target executionengine transforms +ExtraMakefiles = $(PROJ_OBJ_DIR)/Makefile.ocaml + +ocamldoc: + $(Verb) for i in $(DIRS) ; do \ + $(MAKE) -C $$i ocamldoc; \ + done + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/bindings/ocaml/analysis/Makefile b/cpp/llvm/bindings/ocaml/analysis/Makefile new file mode 100644 index 00000000..cbfcb246 --- /dev/null +++ b/cpp/llvm/bindings/ocaml/analysis/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/analysis/Makefile --------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_analysis interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_analysis +UsedComponents := analysis +UsedOcamlInterfaces := llvm + +include ../Makefile.ocaml diff --git a/cpp/llvm/bindings/ocaml/bitreader/Makefile b/cpp/llvm/bindings/ocaml/bitreader/Makefile new file mode 100644 index 00000000..a1c7de89 --- /dev/null +++ b/cpp/llvm/bindings/ocaml/bitreader/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/bitreader/Makefile -------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_bitreader interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_bitreader +UsedComponents := bitreader +UsedOcamlInterfaces := llvm + +include ../Makefile.ocaml diff --git a/cpp/llvm/bindings/ocaml/bitwriter/Makefile b/cpp/llvm/bindings/ocaml/bitwriter/Makefile new file mode 100644 index 00000000..cec0a59c --- /dev/null +++ b/cpp/llvm/bindings/ocaml/bitwriter/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/bitwriter/Makefile -------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_bitwriter interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_bitwriter +UsedComponents := bitwriter +UsedOcamlInterfaces := llvm + +include ../Makefile.ocaml diff --git a/cpp/llvm/bindings/ocaml/executionengine/Makefile b/cpp/llvm/bindings/ocaml/executionengine/Makefile new file mode 100644 index 00000000..5fa3f220 --- /dev/null +++ b/cpp/llvm/bindings/ocaml/executionengine/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/executionengine/Makefile --------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_executionengine interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_executionengine +UsedComponents := executionengine jit interpreter native +UsedOcamlInterfaces := llvm llvm_target + +include ../Makefile.ocaml diff --git a/cpp/llvm/bindings/ocaml/llvm/Makefile b/cpp/llvm/bindings/ocaml/llvm/Makefile new file mode 100644 index 00000000..203075a9 --- /dev/null +++ b/cpp/llvm/bindings/ocaml/llvm/Makefile @@ -0,0 +1,42 @@ +##===- bindings/ocaml/llvm/Makefile ------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm +UsedComponents := core +UsedOcamLibs := llvm + +include ../Makefile.ocaml + +all-local:: copy-meta +install-local:: install-meta +uninstall-local:: uninstall-meta + +DestMETA := $(PROJ_libocamldir)/META.llvm + +# Easy way of generating META in the objdir +copy-meta: $(OcamlDir)/META.llvm + +$(OcamlDir)/META.llvm: META.llvm + $(Verb) $(CP) -f $< $@ + +install-meta:: $(OcamlDir)/META.llvm + $(Echo) "Install $(BuildMode) $(DestMETA)" + $(Verb) $(MKDIR) $(PROJ_libocamldir) + $(Verb) $(DataInstall) $< "$(DestMETA)" + +uninstall-meta:: + $(Echo) "Uninstalling $(DestMETA)" + -$(Verb) $(RM) -f "$(DestMETA)" + +.PHONY: copy-meta install-meta uninstall-meta diff --git a/cpp/llvm/bindings/ocaml/target/Makefile b/cpp/llvm/bindings/ocaml/target/Makefile new file mode 100644 index 00000000..3c48cd8f --- /dev/null +++ b/cpp/llvm/bindings/ocaml/target/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/target/Makefile ----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_target interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_target +UsedComponents := target +UsedOcamlInterfaces := llvm + +include ../Makefile.ocaml diff --git a/cpp/llvm/bindings/ocaml/transforms/Makefile b/cpp/llvm/bindings/ocaml/transforms/Makefile new file mode 100644 index 00000000..05fcd900 --- /dev/null +++ b/cpp/llvm/bindings/ocaml/transforms/Makefile @@ -0,0 +1,18 @@ +##===- bindings/ocaml/transforms/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +DIRS = scalar ipo + +ocamldoc: + $(Verb) for i in $(DIRS) ; do \ + $(MAKE) -C $$i ocamldoc; \ + done + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/bindings/ocaml/transforms/ipo/Makefile b/cpp/llvm/bindings/ocaml/transforms/ipo/Makefile new file mode 100644 index 00000000..130d74c9 --- /dev/null +++ b/cpp/llvm/bindings/ocaml/transforms/ipo/Makefile @@ -0,0 +1,20 @@ +##===- bindings/ocaml/transforms/scalar/Makefile -----------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_scalar_opts interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../../.. +LIBRARYNAME := llvm_ipo +DONT_BUILD_RELINKED := 1 +UsedComponents := ipo +UsedOcamlInterfaces := llvm + +include ../../Makefile.ocaml diff --git a/cpp/llvm/bindings/ocaml/transforms/scalar/Makefile b/cpp/llvm/bindings/ocaml/transforms/scalar/Makefile new file mode 100644 index 00000000..cbaffa4e --- /dev/null +++ b/cpp/llvm/bindings/ocaml/transforms/scalar/Makefile @@ -0,0 +1,20 @@ +##===- bindings/ocaml/transforms/scalar/Makefile -----------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_scalar_opts interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../../.. +LIBRARYNAME := llvm_scalar_opts +DONT_BUILD_RELINKED := 1 +UsedComponents := scalaropts +UsedOcamlInterfaces := llvm + +include ../../Makefile.ocaml diff --git a/cpp/llvm/docs/CommandGuide/Makefile b/cpp/llvm/docs/CommandGuide/Makefile new file mode 100644 index 00000000..3f9f60b8 --- /dev/null +++ b/cpp/llvm/docs/CommandGuide/Makefile @@ -0,0 +1,103 @@ +##===- docs/CommandGuide/Makefile --------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +ifdef BUILD_FOR_WEBSITE +# This special case is for keeping the CommandGuide on the LLVM web site +# up to date automatically as the documents are checked in. It must build +# the POD files to HTML only and keep them in the src directories. It must also +# build in an unconfigured tree, hence the ifdef. To use this, run +# make -s BUILD_FOR_WEBSITE=1 inside the cvs commit script. +SRC_DOC_DIR= +DST_HTML_DIR=html/ +DST_MAN_DIR=man/man1/ +DST_PS_DIR=ps/ + +# If we are in BUILD_FOR_WEBSITE mode, default to the all target. +all:: html man ps + +clean: + rm -f pod2htm*.*~~ $(HTML) $(MAN) $(PS) + +# To create other directories, as needed, and timestamp their creation +%/.dir: + -mkdir $* > /dev/null + date > $@ + +else + +# Otherwise, if not in BUILD_FOR_WEBSITE mode, use the project info. +LEVEL := ../.. +include $(LEVEL)/Makefile.common + +SRC_DOC_DIR=$(PROJ_SRC_DIR)/ +DST_HTML_DIR=$(PROJ_OBJ_DIR)/ +DST_MAN_DIR=$(PROJ_OBJ_DIR)/ +DST_PS_DIR=$(PROJ_OBJ_DIR)/ + +endif + + +POD := $(wildcard $(SRC_DOC_DIR)*.pod) +HTML := $(patsubst $(SRC_DOC_DIR)%.pod, $(DST_HTML_DIR)%.html, $(POD)) +MAN := $(patsubst $(SRC_DOC_DIR)%.pod, $(DST_MAN_DIR)%.1, $(POD)) +PS := $(patsubst $(SRC_DOC_DIR)%.pod, $(DST_PS_DIR)%.ps, $(POD)) + +# The set of man pages we will not install +NO_INSTALL_MANS = $(DST_MAN_DIR)FileCheck.1 $(DST_MAN_DIR)llvm-build.1 + +# The set of man pages that we will install +INSTALL_MANS = $(filter-out $(NO_INSTALL_MANS), $(MAN)) + +.SUFFIXES: +.SUFFIXES: .html .pod .1 .ps + +$(DST_HTML_DIR)%.html: %.pod $(DST_HTML_DIR)/.dir + pod2html --css=manpage.css --htmlroot=. \ + --podpath=. --noindex --infile=$< --outfile=$@ --title=$* + +$(DST_MAN_DIR)%.1: %.pod $(DST_MAN_DIR)/.dir + pod2man --release=CVS --center="LLVM Command Guide" $< $@ + +$(DST_PS_DIR)%.ps: $(DST_MAN_DIR)%.1 $(DST_PS_DIR)/.dir + groff -Tps -man $< > $@ + + +html: $(HTML) +man: $(MAN) +ps: $(PS) + +EXTRA_DIST := $(POD) index.html + +clean-local:: + $(Verb) $(RM) -f pod2htm*.*~~ $(HTML) $(MAN) $(PS) + +HTML_DIR := $(DESTDIR)$(PROJ_docsdir)/html/CommandGuide +MAN_DIR := $(DESTDIR)$(PROJ_mandir)/man1 +PS_DIR := $(DESTDIR)$(PROJ_docsdir)/ps + +install-local:: $(HTML) $(INSTALL_MANS) $(PS) + $(Echo) Installing HTML CommandGuide Documentation + $(Verb) $(MKDIR) $(HTML_DIR) + $(Verb) $(DataInstall) $(HTML) $(HTML_DIR) + $(Verb) $(DataInstall) $(PROJ_SRC_DIR)/index.html $(HTML_DIR) + $(Verb) $(DataInstall) $(PROJ_SRC_DIR)/manpage.css $(HTML_DIR) + $(Echo) Installing MAN CommandGuide Documentation + $(Verb) $(MKDIR) $(MAN_DIR) + $(Verb) $(DataInstall) $(INSTALL_MANS) $(MAN_DIR) + $(Echo) Installing PS CommandGuide Documentation + $(Verb) $(MKDIR) $(PS_DIR) + $(Verb) $(DataInstall) $(PS) $(PS_DIR) + +uninstall-local:: + $(Echo) Uninstalling CommandGuide Documentation + $(Verb) $(RM) -rf $(HTML_DIR) $(MAN_DIR) $(PS_DIR) + +printvars:: + $(Echo) "POD : " '$(POD)' + $(Echo) "HTML : " '$(HTML)' diff --git a/cpp/llvm/docs/Makefile b/cpp/llvm/docs/Makefile new file mode 100644 index 00000000..389fd90a --- /dev/null +++ b/cpp/llvm/docs/Makefile @@ -0,0 +1,130 @@ +##===- docs/Makefile ---------------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := .. +DIRS := CommandGuide tutorial + +ifdef BUILD_FOR_WEBSITE +PROJ_OBJ_DIR = . +DOXYGEN = doxygen + +$(PROJ_OBJ_DIR)/doxygen.cfg: doxygen.cfg.in + cat $< | sed \ + -e 's/@abs_top_srcdir@/../g' \ + -e 's/@DOT@/dot/g' \ + -e 's/@PACKAGE_VERSION@/mainline/' \ + -e 's/@abs_top_builddir@/../g' > $@ +endif + +include $(LEVEL)/Makefile.common + +HTML := $(wildcard $(PROJ_SRC_DIR)/*.html) \ + $(wildcard $(PROJ_SRC_DIR)/*.css) +IMAGES := $(wildcard $(PROJ_SRC_DIR)/img/*.*) +DOXYFILES := doxygen.cfg.in doxygen.css doxygen.footer doxygen.header \ + doxygen.intro +EXTRA_DIST := $(HTML) $(DOXYFILES) llvm.css CommandGuide img + +.PHONY: install-html install-doxygen doxygen install-ocamldoc ocamldoc generated + +install_targets := install-html +ifeq ($(ENABLE_DOXYGEN),1) +install_targets += install-doxygen +endif +ifdef OCAMLDOC +ifneq (,$(filter ocaml,$(BINDINGS_TO_BUILD))) +install_targets += install-ocamldoc +endif +endif +install-local:: $(install_targets) + +generated_targets := doxygen +ifdef OCAMLDOC +generated_targets += ocamldoc +endif + +# Live documentation is generated for the web site using this target: +# 'make generated BUILD_FOR_WEBSITE=1' +generated:: $(generated_targets) + +install-html: $(PROJ_OBJ_DIR)/html.tar.gz + $(Echo) Installing HTML documentation + $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/html + $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/html/img + $(Verb) $(DataInstall) $(HTML) $(DESTDIR)$(PROJ_docsdir)/html + $(Verb) $(DataInstall) $(IMAGES) $(DESTDIR)$(PROJ_docsdir)/html/img + $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/html.tar.gz $(DESTDIR)$(PROJ_docsdir) + +$(PROJ_OBJ_DIR)/html.tar.gz: $(HTML) + $(Echo) Packaging HTML documentation + $(Verb) $(RM) -rf $@ $(PROJ_OBJ_DIR)/html.tar + $(Verb) cd $(PROJ_SRC_DIR) && \ + $(TAR) cf $(PROJ_OBJ_DIR)/html.tar *.html + $(Verb) $(GZIPBIN) $(PROJ_OBJ_DIR)/html.tar + +install-doxygen: doxygen + $(Echo) Installing doxygen documentation + $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/html/doxygen + $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/doxygen.tar.gz $(DESTDIR)$(PROJ_docsdir) + $(Verb) cd $(PROJ_OBJ_DIR)/doxygen && \ + $(FIND) . -type f -exec \ + $(DataInstall) {} $(DESTDIR)$(PROJ_docsdir)/html/doxygen \; + +doxygen: regendoc $(PROJ_OBJ_DIR)/doxygen.tar.gz + +regendoc: + $(Echo) Building doxygen documentation + $(Verb) if test -e $(PROJ_OBJ_DIR)/doxygen ; then \ + $(RM) -rf $(PROJ_OBJ_DIR)/doxygen ; \ + fi + $(Verb) $(DOXYGEN) $(PROJ_OBJ_DIR)/doxygen.cfg + +$(PROJ_OBJ_DIR)/doxygen.tar.gz: $(DOXYFILES) $(PROJ_OBJ_DIR)/doxygen.cfg + $(Echo) Packaging doxygen documentation + $(Verb) $(RM) -rf $@ $(PROJ_OBJ_DIR)/doxygen.tar + $(Verb) $(TAR) cf $(PROJ_OBJ_DIR)/doxygen.tar doxygen + $(Verb) $(GZIPBIN) $(PROJ_OBJ_DIR)/doxygen.tar + $(Verb) $(CP) $(PROJ_OBJ_DIR)/doxygen.tar.gz $(PROJ_OBJ_DIR)/doxygen/html/ + +userloc: $(LLVM_SRC_ROOT)/docs/userloc.html + +$(LLVM_SRC_ROOT)/docs/userloc.html: + $(Echo) Making User LOC Table + $(Verb) cd $(LLVM_SRC_ROOT) ; ./utils/userloc.pl -details -recurse \ + -html lib include tools runtime utils examples autoconf test > docs/userloc.html + +install-ocamldoc: ocamldoc + $(Echo) Installing ocamldoc documentation + $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/ocamldoc/html + $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/ocamldoc.tar.gz $(DESTDIR)$(PROJ_docsdir) + $(Verb) cd $(PROJ_OBJ_DIR)/ocamldoc && \ + $(FIND) . -type f -exec \ + $(DataInstall) {} $(DESTDIR)$(PROJ_docsdir)/ocamldoc/html \; + +ocamldoc: regen-ocamldoc + $(Echo) Packaging ocamldoc documentation + $(Verb) $(RM) -rf $(PROJ_OBJ_DIR)/ocamldoc.tar* + $(Verb) $(TAR) cf $(PROJ_OBJ_DIR)/ocamldoc.tar ocamldoc + $(Verb) $(GZIPBIN) $(PROJ_OBJ_DIR)/ocamldoc.tar + $(Verb) $(CP) $(PROJ_OBJ_DIR)/ocamldoc.tar.gz $(PROJ_OBJ_DIR)/ocamldoc/html/ + +regen-ocamldoc: + $(Echo) Building ocamldoc documentation + $(Verb) if test -e $(PROJ_OBJ_DIR)/ocamldoc ; then \ + $(RM) -rf $(PROJ_OBJ_DIR)/ocamldoc ; \ + fi + $(Verb) $(MAKE) -C $(LEVEL)/bindings/ocaml ocamldoc + $(Verb) $(MKDIR) $(PROJ_OBJ_DIR)/ocamldoc/html + $(Verb) \ + $(OCAMLDOC) -d $(PROJ_OBJ_DIR)/ocamldoc/html -sort -colorize-code -html \ + `$(FIND) $(LEVEL)/bindings/ocaml -name "*.odoc" -exec echo -load '{}' ';'` + +uninstall-local:: + $(Echo) Uninstalling Documentation + $(Verb) $(RM) -rf $(DESTDIR)$(PROJ_docsdir) diff --git a/cpp/llvm/docs/tutorial/Makefile b/cpp/llvm/docs/tutorial/Makefile new file mode 100644 index 00000000..fdf1bb68 --- /dev/null +++ b/cpp/llvm/docs/tutorial/Makefile @@ -0,0 +1,30 @@ +##===- docs/tutorial/Makefile ------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../.. +include $(LEVEL)/Makefile.common + +HTML := $(wildcard $(PROJ_SRC_DIR)/*.html) +PNG := $(wildcard $(PROJ_SRC_DIR)/*.png) +EXTRA_DIST := $(HTML) index.html +HTML_DIR := $(DESTDIR)$(PROJ_docsdir)/html/tutorial + +install-local:: $(HTML) + $(Echo) Installing HTML Tutorial Documentation + $(Verb) $(MKDIR) $(HTML_DIR) + $(Verb) $(DataInstall) $(HTML) $(HTML_DIR) + $(Verb) $(DataInstall) $(PNG) $(HTML_DIR) + $(Verb) $(DataInstall) $(PROJ_SRC_DIR)/index.html $(HTML_DIR) + +uninstall-local:: + $(Echo) Uninstalling Tutorial Documentation + $(Verb) $(RM) -rf $(HTML_DIR) + +printvars:: + $(Echo) "HTML : " '$(HTML)' diff --git a/cpp/llvm/examples/BrainF/Makefile b/cpp/llvm/examples/BrainF/Makefile new file mode 100644 index 00000000..2c3e0662 --- /dev/null +++ b/cpp/llvm/examples/BrainF/Makefile @@ -0,0 +1,15 @@ +##===- examples/BrainF/Makefile ----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../.. +TOOLNAME = BrainF +EXAMPLE_TOOL = 1 + +LINK_COMPONENTS := jit bitwriter nativecodegen interpreter + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/ExceptionDemo/Makefile b/cpp/llvm/examples/ExceptionDemo/Makefile new file mode 100644 index 00000000..48074473 --- /dev/null +++ b/cpp/llvm/examples/ExceptionDemo/Makefile @@ -0,0 +1,16 @@ +##===- examples/ExceptionDemo/Makefile --------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===---------------------------------------------------------------------===## +LEVEL = ../.. +TOOLNAME = ExceptionDemo +EXAMPLE_TOOL = 1 +REQUIRES_EH = 1 + +LINK_COMPONENTS := jit interpreter nativecodegen + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/Fibonacci/Makefile b/cpp/llvm/examples/Fibonacci/Makefile new file mode 100644 index 00000000..71f6ba0e --- /dev/null +++ b/cpp/llvm/examples/Fibonacci/Makefile @@ -0,0 +1,17 @@ +##===- examples/Fibonacci/Makefile -------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +TOOLNAME = Fibonacci +EXAMPLE_TOOL = 1 + +# Link in JIT support +LINK_COMPONENTS := jit interpreter nativecodegen + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/HowToUseJIT/Makefile b/cpp/llvm/examples/HowToUseJIT/Makefile new file mode 100644 index 00000000..c8919db9 --- /dev/null +++ b/cpp/llvm/examples/HowToUseJIT/Makefile @@ -0,0 +1,15 @@ +##===- examples/HowToUseJIT/Makefile -----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../.. +TOOLNAME = HowToUseJIT +EXAMPLE_TOOL = 1 + +LINK_COMPONENTS := jit interpreter nativecodegen + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/Kaleidoscope/Chapter2/Makefile b/cpp/llvm/examples/Kaleidoscope/Chapter2/Makefile new file mode 100644 index 00000000..1a9b94ce --- /dev/null +++ b/cpp/llvm/examples/Kaleidoscope/Chapter2/Makefile @@ -0,0 +1,13 @@ +##===- examples/Kaleidoscope/Chapter2/Makefile -------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +TOOLNAME = Kaleidoscope-Ch2 +EXAMPLE_TOOL = 1 + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/Kaleidoscope/Chapter3/Makefile b/cpp/llvm/examples/Kaleidoscope/Chapter3/Makefile new file mode 100644 index 00000000..4cc6948d --- /dev/null +++ b/cpp/llvm/examples/Kaleidoscope/Chapter3/Makefile @@ -0,0 +1,15 @@ +##===- examples/Kaleidoscope/Chapter3/Makefile -------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +TOOLNAME = Kaleidoscope-Ch3 +EXAMPLE_TOOL = 1 + +LINK_COMPONENTS := core + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/Kaleidoscope/Chapter4/Makefile b/cpp/llvm/examples/Kaleidoscope/Chapter4/Makefile new file mode 100644 index 00000000..30162d94 --- /dev/null +++ b/cpp/llvm/examples/Kaleidoscope/Chapter4/Makefile @@ -0,0 +1,15 @@ +##===- examples/Kaleidoscope/Chapter4/Makefile -------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +TOOLNAME = Kaleidoscope-Ch4 +EXAMPLE_TOOL = 1 + +LINK_COMPONENTS := core jit native + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/Kaleidoscope/Chapter5/Makefile b/cpp/llvm/examples/Kaleidoscope/Chapter5/Makefile new file mode 100644 index 00000000..d1f5e203 --- /dev/null +++ b/cpp/llvm/examples/Kaleidoscope/Chapter5/Makefile @@ -0,0 +1,15 @@ +##===- examples/Kaleidoscope/Chapter5/Makefile -------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +TOOLNAME = Kaleidoscope-Ch5 +EXAMPLE_TOOL = 1 + +LINK_COMPONENTS := core jit native + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/Kaleidoscope/Chapter6/Makefile b/cpp/llvm/examples/Kaleidoscope/Chapter6/Makefile new file mode 100644 index 00000000..a5fbcbdf --- /dev/null +++ b/cpp/llvm/examples/Kaleidoscope/Chapter6/Makefile @@ -0,0 +1,15 @@ +##===- examples/Kaleidoscope/Chapter6/Makefile -------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +TOOLNAME = Kaleidoscope-Ch6 +EXAMPLE_TOOL = 1 + +LINK_COMPONENTS := core jit native + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/Kaleidoscope/Chapter7/Makefile b/cpp/llvm/examples/Kaleidoscope/Chapter7/Makefile new file mode 100644 index 00000000..6cec323e --- /dev/null +++ b/cpp/llvm/examples/Kaleidoscope/Chapter7/Makefile @@ -0,0 +1,16 @@ +##===- examples/Kaleidoscope/Chapter7/Makefile -------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +TOOLNAME = Kaleidoscope-Ch7 +EXAMPLE_TOOL = 1 +REQUIRES_RTTI := 1 + +LINK_COMPONENTS := core jit native + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/Kaleidoscope/Makefile b/cpp/llvm/examples/Kaleidoscope/Makefile new file mode 100644 index 00000000..bd0c252c --- /dev/null +++ b/cpp/llvm/examples/Kaleidoscope/Makefile @@ -0,0 +1,15 @@ +##===- examples/Kaleidoscope/Makefile ----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL=../.. + +include $(LEVEL)/Makefile.config + +PARALLEL_DIRS:= Chapter2 Chapter3 Chapter4 Chapter5 Chapter6 Chapter7 + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/Makefile b/cpp/llvm/examples/Makefile new file mode 100644 index 00000000..50a6db76 --- /dev/null +++ b/cpp/llvm/examples/Makefile @@ -0,0 +1,32 @@ +##===- examples/Makefile -----------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL=.. + +include $(LEVEL)/Makefile.config + +PARALLEL_DIRS:= BrainF Fibonacci HowToUseJIT Kaleidoscope ModuleMaker + +ifeq ($(HAVE_PTHREAD),1) +PARALLEL_DIRS += ParallelJIT +endif + +ifeq ($(LLVM_ON_UNIX),1) + ifeq ($(ARCH),x86) + PARALLEL_DIRS += ExceptionDemo + endif + ifeq ($(ARCH),x86_64) + PARALLEL_DIRS += ExceptionDemo + endif +endif + +ifeq ($(filter $(BINDINGS_TO_BUILD),ocaml),ocaml) + PARALLEL_DIRS += OCaml-Kaleidoscope +endif + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/ModuleMaker/Makefile b/cpp/llvm/examples/ModuleMaker/Makefile new file mode 100644 index 00000000..9454cf51 --- /dev/null +++ b/cpp/llvm/examples/ModuleMaker/Makefile @@ -0,0 +1,14 @@ +##===- examples/ModuleMaker/Makefile -----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL=../.. +TOOLNAME=ModuleMaker +EXAMPLE_TOOL = 1 +LINK_COMPONENTS := bitwriter + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter2/Makefile b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter2/Makefile new file mode 100644 index 00000000..8fc03da0 --- /dev/null +++ b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter2/Makefile @@ -0,0 +1,22 @@ +##===- examples/OCaml-Kaleidoscope/Chapter2/Makefile -------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 2. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +TOOLNAME := OCaml-Kaleidoscope-Ch2 +EXAMPLE_TOOL := 1 +UsedComponents := core +UsedOcamLibs := llvm + +OCAMLCFLAGS += -pp camlp4of + +include $(LEVEL)/bindings/ocaml/Makefile.ocaml diff --git a/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter3/Makefile b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter3/Makefile new file mode 100644 index 00000000..fdbcd519 --- /dev/null +++ b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter3/Makefile @@ -0,0 +1,24 @@ +##===- examples/OCaml-Kaleidoscope/Chapter3/Makefile -------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 3. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +TOOLNAME := OCaml-Kaleidoscope-Ch3 +EXAMPLE_TOOL := 1 +UsedComponents := core +UsedOcamLibs := llvm llvm_analysis + +OCAMLCFLAGS += -pp camlp4of + +ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml + +include $(LEVEL)/bindings/ocaml/Makefile.ocaml diff --git a/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter4/Makefile b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter4/Makefile new file mode 100644 index 00000000..d9c3f49b --- /dev/null +++ b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter4/Makefile @@ -0,0 +1,25 @@ +##===- examples/OCaml-Kaleidoscope/Chapter4/Makefile -------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 4. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +TOOLNAME := OCaml-Kaleidoscope-Ch4 +EXAMPLE_TOOL := 1 +UsedComponents := core +UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \ + llvm_scalar_opts + +OCAMLCFLAGS += -pp camlp4of + +ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml + +include $(LEVEL)/bindings/ocaml/Makefile.ocaml diff --git a/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter5/Makefile b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter5/Makefile new file mode 100644 index 00000000..f31c10d3 --- /dev/null +++ b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter5/Makefile @@ -0,0 +1,25 @@ +##===- examples/OCaml-Kaleidoscope/Chapter5/Makefile -------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 5. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +TOOLNAME := OCaml-Kaleidoscope-Ch5 +EXAMPLE_TOOL := 1 +UsedComponents := core +UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \ + llvm_scalar_opts + +OCAMLCFLAGS += -pp camlp4of + +ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml + +include $(LEVEL)/bindings/ocaml/Makefile.ocaml diff --git a/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter6/Makefile b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter6/Makefile new file mode 100644 index 00000000..21f0c53d --- /dev/null +++ b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter6/Makefile @@ -0,0 +1,34 @@ +##===- examples/OCaml-Kaleidoscope/Chapter6/Makefile -------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 6. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +TOOLNAME := OCaml-Kaleidoscope-Ch6 +EXAMPLE_TOOL := 1 +UsedComponents := core +UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \ + llvm_scalar_opts + +OCAMLCFLAGS += -pp camlp4of + +OcamlSources1 = \ + $(PROJ_SRC_DIR)/ast.ml \ + $(PROJ_SRC_DIR)/parser.ml \ + $(PROJ_SRC_DIR)/codegen.ml \ + $(PROJ_SRC_DIR)/lexer.ml \ + $(PROJ_SRC_DIR)/token.ml \ + $(PROJ_SRC_DIR)/toplevel.ml \ + $(PROJ_SRC_DIR)/toy.ml + +ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml + +include $(LEVEL)/bindings/ocaml/Makefile.ocaml diff --git a/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter7/Makefile b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter7/Makefile new file mode 100644 index 00000000..99686e17 --- /dev/null +++ b/cpp/llvm/examples/OCaml-Kaleidoscope/Chapter7/Makefile @@ -0,0 +1,34 @@ +##===- examples/OCaml-Kaleidoscope/Chapter7/Makefile -------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 7. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +TOOLNAME := OCaml-Kaleidoscope-Ch7 +EXAMPLE_TOOL := 1 +UsedComponents := core +UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \ + llvm_scalar_opts + +OCAMLCFLAGS += -pp camlp4of + +OcamlSources1 = \ + $(PROJ_SRC_DIR)/ast.ml \ + $(PROJ_SRC_DIR)/parser.ml \ + $(PROJ_SRC_DIR)/codegen.ml \ + $(PROJ_SRC_DIR)/lexer.ml \ + $(PROJ_SRC_DIR)/token.ml \ + $(PROJ_SRC_DIR)/toplevel.ml \ + $(PROJ_SRC_DIR)/toy.ml + +ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml + +include $(LEVEL)/bindings/ocaml/Makefile.ocaml diff --git a/cpp/llvm/examples/OCaml-Kaleidoscope/Makefile b/cpp/llvm/examples/OCaml-Kaleidoscope/Makefile new file mode 100644 index 00000000..5342b940 --- /dev/null +++ b/cpp/llvm/examples/OCaml-Kaleidoscope/Makefile @@ -0,0 +1,15 @@ +##===- examples/OCaml-Kaleidoscope/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL=../.. + +include $(LEVEL)/Makefile.config + +PARALLEL_DIRS:= Chapter2 Chapter3 Chapter4 Chapter5 Chapter6 Chapter7 + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/examples/ParallelJIT/Makefile b/cpp/llvm/examples/ParallelJIT/Makefile new file mode 100644 index 00000000..8a49d427 --- /dev/null +++ b/cpp/llvm/examples/ParallelJIT/Makefile @@ -0,0 +1,17 @@ +##===- examples/ParallelJIT/Makefile -----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../.. +TOOLNAME = ParallelJIT +EXAMPLE_TOOL = 1 + +LINK_COMPONENTS := jit interpreter nativecodegen + +include $(LEVEL)/Makefile.common + +LIBS += -lpthread diff --git a/cpp/llvm/lib/Analysis/IPA/Makefile b/cpp/llvm/lib/Analysis/IPA/Makefile new file mode 100644 index 00000000..b850c9ff --- /dev/null +++ b/cpp/llvm/lib/Analysis/IPA/Makefile @@ -0,0 +1,15 @@ +##===- lib/Analysis/IPA/Makefile ---------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMipa +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Analysis/Makefile b/cpp/llvm/lib/Analysis/Makefile new file mode 100644 index 00000000..4af6d350 --- /dev/null +++ b/cpp/llvm/lib/Analysis/Makefile @@ -0,0 +1,16 @@ +##===- lib/Analysis/Makefile -------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMAnalysis +DIRS = IPA +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Archive/Makefile b/cpp/llvm/lib/Archive/Makefile new file mode 100644 index 00000000..da978040 --- /dev/null +++ b/cpp/llvm/lib/Archive/Makefile @@ -0,0 +1,17 @@ +##===- lib/Archive/Makefile --------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMArchive + +# We only want an archive so only those modules actually used by a tool are +# included. +BUILD_ARCHIVE := 1 + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/AsmParser/Makefile b/cpp/llvm/lib/AsmParser/Makefile new file mode 100644 index 00000000..995bb0e1 --- /dev/null +++ b/cpp/llvm/lib/AsmParser/Makefile @@ -0,0 +1,14 @@ +##===- lib/AsmParser/Makefile ------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME := LLVMAsmParser +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Bitcode/Makefile b/cpp/llvm/lib/Bitcode/Makefile new file mode 100644 index 00000000..2d6b5ad1 --- /dev/null +++ b/cpp/llvm/lib/Bitcode/Makefile @@ -0,0 +1,14 @@ +##===- lib/Bitcode/Makefile --------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +PARALLEL_DIRS = Reader Writer + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Bitcode/Reader/Makefile b/cpp/llvm/lib/Bitcode/Reader/Makefile new file mode 100644 index 00000000..59af8d53 --- /dev/null +++ b/cpp/llvm/lib/Bitcode/Reader/Makefile @@ -0,0 +1,15 @@ +##===- lib/Bitcode/Reader/Makefile -------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMBitReader +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Bitcode/Writer/Makefile b/cpp/llvm/lib/Bitcode/Writer/Makefile new file mode 100644 index 00000000..7b0bd721 --- /dev/null +++ b/cpp/llvm/lib/Bitcode/Writer/Makefile @@ -0,0 +1,15 @@ +##===- lib/Bitcode/Reader/Makefile -------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMBitWriter +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/CodeGen/AsmPrinter/Makefile b/cpp/llvm/lib/CodeGen/AsmPrinter/Makefile new file mode 100644 index 00000000..60aa6cbc --- /dev/null +++ b/cpp/llvm/lib/CodeGen/AsmPrinter/Makefile @@ -0,0 +1,13 @@ +##===- lib/CodeGen/AsmPrinter/Makefile ---------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMAsmPrinter + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/CodeGen/Makefile b/cpp/llvm/lib/CodeGen/Makefile new file mode 100644 index 00000000..4ab3e3c0 --- /dev/null +++ b/cpp/llvm/lib/CodeGen/Makefile @@ -0,0 +1,22 @@ +##===- lib/CodeGen/Makefile --------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMCodeGen +PARALLEL_DIRS = SelectionDAG AsmPrinter +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + +# Xcode prior to 2.4 generates an error in -pedantic mode with use of HUGE_VAL +# in this directory. Disable -pedantic for this broken compiler. +ifneq ($(HUGE_VAL_SANITY),yes) +CompileCommonOpts := $(filter-out -pedantic, $(CompileCommonOpts)) +endif + diff --git a/cpp/llvm/lib/CodeGen/SelectionDAG/Makefile b/cpp/llvm/lib/CodeGen/SelectionDAG/Makefile new file mode 100644 index 00000000..ea716fda --- /dev/null +++ b/cpp/llvm/lib/CodeGen/SelectionDAG/Makefile @@ -0,0 +1,13 @@ +##===- lib/CodeGen/SelectionDAG/Makefile -------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMSelectionDAG + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/DebugInfo/Makefile b/cpp/llvm/lib/DebugInfo/Makefile new file mode 100644 index 00000000..1292b572 --- /dev/null +++ b/cpp/llvm/lib/DebugInfo/Makefile @@ -0,0 +1,14 @@ +##===- lib/DebugInfo/Makefile ------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMDebugInfo +BUILD_ARCHIVE := 1 + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/ExecutionEngine/IntelJITEvents/Makefile b/cpp/llvm/lib/ExecutionEngine/IntelJITEvents/Makefile new file mode 100644 index 00000000..ba75ac6f --- /dev/null +++ b/cpp/llvm/lib/ExecutionEngine/IntelJITEvents/Makefile @@ -0,0 +1,17 @@ +##===- lib/ExecutionEngine/JITProfile/Makefile -------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +LIBRARYNAME = LLVMIntelJITEvents + +include $(LEVEL)/Makefile.config + +SOURCES := IntelJITEventListener.cpp +CPPFLAGS += -I$(INTEL_JITEVENTS_INCDIR) -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LLVM_SRC_ROOT)/Makefile.rules diff --git a/cpp/llvm/lib/ExecutionEngine/Interpreter/Makefile b/cpp/llvm/lib/ExecutionEngine/Interpreter/Makefile new file mode 100644 index 00000000..5def1365 --- /dev/null +++ b/cpp/llvm/lib/ExecutionEngine/Interpreter/Makefile @@ -0,0 +1,13 @@ +##===- lib/ExecutionEngine/Interpreter/Makefile ------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMInterpreter + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/ExecutionEngine/JIT/Makefile b/cpp/llvm/lib/ExecutionEngine/JIT/Makefile new file mode 100644 index 00000000..aafa3d9d --- /dev/null +++ b/cpp/llvm/lib/ExecutionEngine/JIT/Makefile @@ -0,0 +1,38 @@ +##===- lib/ExecutionEngine/JIT/Makefile --------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMJIT + +# Get the $(ARCH) setting +include $(LEVEL)/Makefile.config + +# Enable the X86 JIT if compiling on X86 +ifeq ($(ARCH), x86) + ENABLE_X86_JIT = 1 +endif + +# This flag can also be used on the command line to force inclusion +# of the X86 JIT on non-X86 hosts +ifdef ENABLE_X86_JIT + CPPFLAGS += -DENABLE_X86_JIT +endif + +# Enable the Sparc JIT if compiling on Sparc +ifeq ($(ARCH), Sparc) + ENABLE_SPARC_JIT = 1 +endif + +# This flag can also be used on the command line to force inclusion +# of the Sparc JIT on non-Sparc hosts +ifdef ENABLE_SPARC_JIT + CPPFLAGS += -DENABLE_SPARC_JIT +endif + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/ExecutionEngine/MCJIT/Makefile b/cpp/llvm/lib/ExecutionEngine/MCJIT/Makefile new file mode 100644 index 00000000..967efbc0 --- /dev/null +++ b/cpp/llvm/lib/ExecutionEngine/MCJIT/Makefile @@ -0,0 +1,13 @@ +##===- lib/ExecutionEngine/MCJIT/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMMCJIT + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/ExecutionEngine/Makefile b/cpp/llvm/lib/ExecutionEngine/Makefile new file mode 100644 index 00000000..c26e0ada --- /dev/null +++ b/cpp/llvm/lib/ExecutionEngine/Makefile @@ -0,0 +1,24 @@ +##===- lib/ExecutionEngine/Makefile ------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../.. +LIBRARYNAME = LLVMExecutionEngine + +include $(LEVEL)/Makefile.config + +PARALLEL_DIRS = Interpreter JIT MCJIT RuntimeDyld + +ifeq ($(USE_INTEL_JITEVENTS), 1) +PARALLEL_DIRS += IntelJITEvents +endif + +ifeq ($(USE_OPROFILE), 1) +PARALLEL_DIRS += OProfileJIT +endif + +include $(LLVM_SRC_ROOT)/Makefile.rules diff --git a/cpp/llvm/lib/ExecutionEngine/OProfileJIT/Makefile b/cpp/llvm/lib/ExecutionEngine/OProfileJIT/Makefile new file mode 100644 index 00000000..fd3adce2 --- /dev/null +++ b/cpp/llvm/lib/ExecutionEngine/OProfileJIT/Makefile @@ -0,0 +1,18 @@ +##===- lib/ExecutionEngine/OProfileJIT/Makefile ------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +LIBRARYNAME = LLVMOProfileJIT + +include $(LEVEL)/Makefile.config + +SOURCES += OProfileJITEventListener.cpp \ + OProfileWrapper.cpp +CPPFLAGS += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LLVM_SRC_ROOT)/Makefile.rules diff --git a/cpp/llvm/lib/ExecutionEngine/RuntimeDyld/Makefile b/cpp/llvm/lib/ExecutionEngine/RuntimeDyld/Makefile new file mode 100644 index 00000000..5d6f26d9 --- /dev/null +++ b/cpp/llvm/lib/ExecutionEngine/RuntimeDyld/Makefile @@ -0,0 +1,13 @@ +##===- lib/ExecutionEngine/MCJIT/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMRuntimeDyld + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Linker/Makefile b/cpp/llvm/lib/Linker/Makefile new file mode 100644 index 00000000..19e646b7 --- /dev/null +++ b/cpp/llvm/lib/Linker/Makefile @@ -0,0 +1,15 @@ +##===- lib/Linker/Makefile ---------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMLinker +BUILD_ARCHIVE := 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/MC/MCDisassembler/Makefile b/cpp/llvm/lib/MC/MCDisassembler/Makefile new file mode 100644 index 00000000..7d71cd38 --- /dev/null +++ b/cpp/llvm/lib/MC/MCDisassembler/Makefile @@ -0,0 +1,14 @@ +##===- lib/MC/MCDisassembler/Makefile ----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMMCDisassembler + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/MC/MCParser/Makefile b/cpp/llvm/lib/MC/MCParser/Makefile new file mode 100644 index 00000000..44777576 --- /dev/null +++ b/cpp/llvm/lib/MC/MCParser/Makefile @@ -0,0 +1,15 @@ +##===- lib/MC/MCParser/Makefile ----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMMCParser +BUILD_ARCHIVE := 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/MC/Makefile b/cpp/llvm/lib/MC/Makefile new file mode 100644 index 00000000..bf8b7c0e --- /dev/null +++ b/cpp/llvm/lib/MC/Makefile @@ -0,0 +1,16 @@ +##===- lib/MC/Makefile -------------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMMC +BUILD_ARCHIVE := 1 +PARALLEL_DIRS := MCParser MCDisassembler + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Makefile b/cpp/llvm/lib/Makefile new file mode 100644 index 00000000..fd575cd1 --- /dev/null +++ b/cpp/llvm/lib/Makefile @@ -0,0 +1,17 @@ +##===- lib/Makefile ----------------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = .. + +include $(LEVEL)/Makefile.config + +PARALLEL_DIRS := VMCore AsmParser Bitcode Archive Analysis Transforms CodeGen \ + Target ExecutionEngine Linker MC Object DebugInfo + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Object/Makefile b/cpp/llvm/lib/Object/Makefile new file mode 100644 index 00000000..79388dc9 --- /dev/null +++ b/cpp/llvm/lib/Object/Makefile @@ -0,0 +1,14 @@ +##===- lib/Object/Makefile ---------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMObject +BUILD_ARCHIVE := 1 + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Support/Makefile b/cpp/llvm/lib/Support/Makefile new file mode 100644 index 00000000..d68e500c --- /dev/null +++ b/cpp/llvm/lib/Support/Makefile @@ -0,0 +1,22 @@ +##===- lib/Support/Makefile --------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMSupport +BUILD_ARCHIVE = 1 + +## FIXME: This only requires RTTI because tblgen uses it. Fix that. +REQUIRES_RTTI = 1 + +EXTRA_DIST = Unix Win32 README.txt + +include $(LEVEL)/Makefile.common + +CompileCommonOpts := $(filter-out -pedantic,$(CompileCommonOpts)) +CompileCommonOpts := $(filter-out -Wno-long-long,$(CompileCommonOpts)) diff --git a/cpp/llvm/lib/TableGen/Makefile b/cpp/llvm/lib/TableGen/Makefile new file mode 100644 index 00000000..44724389 --- /dev/null +++ b/cpp/llvm/lib/TableGen/Makefile @@ -0,0 +1,18 @@ +##===- lib/TableGen/Makefile -------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMTableGen +BUILD_ARCHIVE = 1 + +## FIXME: This only requires RTTI because tblgen uses it. Fix that. +REQUIRES_RTTI = 1 +REQUIRES_EH = 1 + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/ARM/AsmParser/Makefile b/cpp/llvm/lib/Target/ARM/AsmParser/Makefile new file mode 100644 index 00000000..841516ff --- /dev/null +++ b/cpp/llvm/lib/Target/ARM/AsmParser/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/ARM/AsmParser/Makefile -------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMARMAsmParser + +# Hack: we need to include 'main' ARM target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/ARM/Disassembler/Makefile b/cpp/llvm/lib/Target/ARM/Disassembler/Makefile new file mode 100644 index 00000000..031b6aca --- /dev/null +++ b/cpp/llvm/lib/Target/ARM/Disassembler/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/ARM/Disassembler/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMARMDisassembler + +# Hack: we need to include 'main' arm target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/ARM/InstPrinter/Makefile b/cpp/llvm/lib/Target/ARM/InstPrinter/Makefile new file mode 100644 index 00000000..65d372e4 --- /dev/null +++ b/cpp/llvm/lib/Target/ARM/InstPrinter/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/ARM/AsmPrinter/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMARMAsmPrinter + +# Hack: we need to include 'main' arm target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/ARM/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/ARM/MCTargetDesc/Makefile new file mode 100644 index 00000000..448ed9df --- /dev/null +++ b/cpp/llvm/lib/Target/ARM/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/ARM/TargetDesc/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMARMDesc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/ARM/Makefile b/cpp/llvm/lib/Target/ARM/Makefile new file mode 100644 index 00000000..3e48ed11 --- /dev/null +++ b/cpp/llvm/lib/Target/ARM/Makefile @@ -0,0 +1,24 @@ +##===- lib/Target/ARM/Makefile -----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMARMCodeGen +TARGET = ARM + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = ARMGenRegisterInfo.inc ARMGenInstrInfo.inc \ + ARMGenAsmWriter.inc ARMGenAsmMatcher.inc \ + ARMGenDAGISel.inc ARMGenSubtargetInfo.inc \ + ARMGenCodeEmitter.inc ARMGenCallingConv.inc \ + ARMGenEDInfo.inc ARMGenFastISel.inc ARMGenMCCodeEmitter.inc \ + ARMGenMCPseudoLowering.inc ARMGenDisassemblerTables.inc + +DIRS = InstPrinter AsmParser Disassembler TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/ARM/TargetInfo/Makefile b/cpp/llvm/lib/Target/ARM/TargetInfo/Makefile new file mode 100644 index 00000000..6292ab14 --- /dev/null +++ b/cpp/llvm/lib/Target/ARM/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/ARM/TargetInfo/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMARMInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/CellSPU/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/CellSPU/MCTargetDesc/Makefile new file mode 100644 index 00000000..10d9a422 --- /dev/null +++ b/cpp/llvm/lib/Target/CellSPU/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/CellSPU/TargetDesc/Makefile --------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMCellSPUDesc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/CellSPU/Makefile b/cpp/llvm/lib/Target/CellSPU/Makefile new file mode 100644 index 00000000..d7a8247f --- /dev/null +++ b/cpp/llvm/lib/Target/CellSPU/Makefile @@ -0,0 +1,20 @@ +##===- lib/Target/CellSPU/Makefile -------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMCellSPUCodeGen +TARGET = SPU +BUILT_SOURCES = SPUGenInstrInfo.inc SPUGenRegisterInfo.inc \ + SPUGenAsmWriter.inc SPUGenCodeEmitter.inc \ + SPUGenDAGISel.inc \ + SPUGenSubtargetInfo.inc SPUGenCallingConv.inc + +DIRS = TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/CellSPU/TargetInfo/Makefile b/cpp/llvm/lib/Target/CellSPU/TargetInfo/Makefile new file mode 100644 index 00000000..9cb6827b --- /dev/null +++ b/cpp/llvm/lib/Target/CellSPU/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/CellSPU/TargetInfo/Makefile --------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMCellSPUInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/CppBackend/Makefile b/cpp/llvm/lib/Target/CppBackend/Makefile new file mode 100644 index 00000000..efc7463f --- /dev/null +++ b/cpp/llvm/lib/Target/CppBackend/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/CppBackend/Makefile --- ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMCppBackendCodeGen +DIRS = TargetInfo + +include $(LEVEL)/Makefile.common + +CompileCommonOpts += -Wno-format diff --git a/cpp/llvm/lib/Target/CppBackend/TargetInfo/Makefile b/cpp/llvm/lib/Target/CppBackend/TargetInfo/Makefile new file mode 100644 index 00000000..6e682838 --- /dev/null +++ b/cpp/llvm/lib/Target/CppBackend/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/CppBackend/TargetInfo/Makefile -----------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMCppBackendInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Hexagon/InstPrinter/Makefile b/cpp/llvm/lib/Target/Hexagon/InstPrinter/Makefile new file mode 100644 index 00000000..20331d88 --- /dev/null +++ b/cpp/llvm/lib/Target/Hexagon/InstPrinter/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/Hexagon/InstPrinter/Makefile ----------------------------===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMHexagonAsmPrinter + +# Hack: we need to include 'main' Hexagon target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Hexagon/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/Hexagon/MCTargetDesc/Makefile new file mode 100644 index 00000000..885be2dd --- /dev/null +++ b/cpp/llvm/lib/Target/Hexagon/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/Hexagon/TargetDesc/Makefile --------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMHexagonDesc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Hexagon/Makefile b/cpp/llvm/lib/Target/Hexagon/Makefile new file mode 100644 index 00000000..dc387c54 --- /dev/null +++ b/cpp/llvm/lib/Target/Hexagon/Makefile @@ -0,0 +1,23 @@ +##===- lib/Target/Hexagon/Makefile -------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +LIBRARYNAME = LLVMHexagonCodeGen +TARGET = Hexagon + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = HexagonGenRegisterInfo.inc \ + HexagonGenInstrInfo.inc \ + HexagonGenAsmWriter.inc \ + HexagonGenDAGISel.inc HexagonGenSubtargetInfo.inc \ + HexagonGenCallingConv.inc \ + HexagonGenDFAPacketizer.inc + +DIRS = InstPrinter TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Hexagon/TargetInfo/Makefile b/cpp/llvm/lib/Target/Hexagon/TargetInfo/Makefile new file mode 100644 index 00000000..494cca11 --- /dev/null +++ b/cpp/llvm/lib/Target/Hexagon/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/Hexagon/TargetInfo/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMHexagonInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/MBlaze/AsmParser/Makefile b/cpp/llvm/lib/Target/MBlaze/AsmParser/Makefile new file mode 100644 index 00000000..1e68766a --- /dev/null +++ b/cpp/llvm/lib/Target/MBlaze/AsmParser/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/MBlaze/AsmParser/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMMBlazeAsmParser + +# Hack: we need to include 'main' MBlaze target directory for private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/MBlaze/Disassembler/Makefile b/cpp/llvm/lib/Target/MBlaze/Disassembler/Makefile new file mode 100644 index 00000000..0530b328 --- /dev/null +++ b/cpp/llvm/lib/Target/MBlaze/Disassembler/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/MBlaze/Disassembler/Makefile -------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMMBlazeDisassembler + +# Hack: we need to include 'main' MBlaze target directory to grab headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/MBlaze/InstPrinter/Makefile b/cpp/llvm/lib/Target/MBlaze/InstPrinter/Makefile new file mode 100644 index 00000000..9fb6e869 --- /dev/null +++ b/cpp/llvm/lib/Target/MBlaze/InstPrinter/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/MBlaze/AsmPrinter/Makefile ---------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMMBlazeAsmPrinter + +# Hack: we need to include 'main' MBlaze target directory to grab +# private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/MBlaze/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/MBlaze/MCTargetDesc/Makefile new file mode 100644 index 00000000..71075ffb --- /dev/null +++ b/cpp/llvm/lib/Target/MBlaze/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/MBlaze/TargetDesc/Makefile ---------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMMBlazeDesc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/MBlaze/Makefile b/cpp/llvm/lib/Target/MBlaze/Makefile new file mode 100644 index 00000000..83c2a7d3 --- /dev/null +++ b/cpp/llvm/lib/Target/MBlaze/Makefile @@ -0,0 +1,24 @@ +##===- lib/Target/MBlaze/Makefile --------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../.. +LIBRARYNAME = LLVMMBlazeCodeGen +TARGET = MBlaze + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = MBlazeGenRegisterInfo.inc MBlazeGenInstrInfo.inc \ + MBlazeGenAsmWriter.inc \ + MBlazeGenDAGISel.inc MBlazeGenAsmMatcher.inc \ + MBlazeGenCodeEmitter.inc MBlazeGenCallingConv.inc \ + MBlazeGenSubtargetInfo.inc MBlazeGenIntrinsics.inc \ + MBlazeGenEDInfo.inc + +DIRS = InstPrinter AsmParser Disassembler TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Target/MBlaze/TargetInfo/Makefile b/cpp/llvm/lib/Target/MBlaze/TargetInfo/Makefile new file mode 100644 index 00000000..fb7ea118 --- /dev/null +++ b/cpp/llvm/lib/Target/MBlaze/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/MBlaze/TargetInfo/Makefile ---------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMMBlazeInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/MSP430/InstPrinter/Makefile b/cpp/llvm/lib/Target/MSP430/InstPrinter/Makefile new file mode 100644 index 00000000..a5293ab8 --- /dev/null +++ b/cpp/llvm/lib/Target/MSP430/InstPrinter/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/MSP430/AsmPrinter/Makefile ---------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMMSP430AsmPrinter + +# Hack: we need to include 'main' MSP430 target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/MSP430/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/MSP430/MCTargetDesc/Makefile new file mode 100644 index 00000000..bb857998 --- /dev/null +++ b/cpp/llvm/lib/Target/MSP430/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/MSP430/TargetDesc/Makefile ---------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMMSP430Desc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/MSP430/Makefile b/cpp/llvm/lib/Target/MSP430/Makefile new file mode 100644 index 00000000..82216edd --- /dev/null +++ b/cpp/llvm/lib/Target/MSP430/Makefile @@ -0,0 +1,23 @@ +##===- lib/Target/MSP430/Makefile --------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMMSP430CodeGen +TARGET = MSP430 + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = MSP430GenRegisterInfo.inc MSP430GenInstrInfo.inc \ + MSP430GenAsmWriter.inc \ + MSP430GenDAGISel.inc MSP430GenCallingConv.inc \ + MSP430GenSubtargetInfo.inc + +DIRS = InstPrinter TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Target/MSP430/TargetInfo/Makefile b/cpp/llvm/lib/Target/MSP430/TargetInfo/Makefile new file mode 100644 index 00000000..abb08f25 --- /dev/null +++ b/cpp/llvm/lib/Target/MSP430/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/MSP430/TargetInfo/Makefile ---------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMMSP430Info + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Makefile b/cpp/llvm/lib/Target/Makefile new file mode 100644 index 00000000..50a360f1 --- /dev/null +++ b/cpp/llvm/lib/Target/Makefile @@ -0,0 +1,20 @@ +#===- lib/Target/Makefile ----------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +LIBRARYNAME = LLVMTarget +BUILD_ARCHIVE = 1 + +# We include this early so we can access the value of TARGETS_TO_BUILD as the +# value for PARALLEL_DIRS which must be set before Makefile.rules is included +include $(LEVEL)/Makefile.config + +PARALLEL_DIRS := $(TARGETS_TO_BUILD) + +include $(LLVM_SRC_ROOT)/Makefile.rules diff --git a/cpp/llvm/lib/Target/Mips/AsmParser/Makefile b/cpp/llvm/lib/Target/Mips/AsmParser/Makefile new file mode 100644 index 00000000..679acee9 --- /dev/null +++ b/cpp/llvm/lib/Target/Mips/AsmParser/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/Mips/AsmParser/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMMipsAsmParser + +# Hack: we need to include 'main' mips target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Mips/Disassembler/Makefile b/cpp/llvm/lib/Target/Mips/Disassembler/Makefile new file mode 100644 index 00000000..a78feba1 --- /dev/null +++ b/cpp/llvm/lib/Target/Mips/Disassembler/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/Mips/Disassembler/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMMipsDisassembler + +# Hack: we need to include 'main' Mips target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Mips/InstPrinter/Makefile b/cpp/llvm/lib/Target/Mips/InstPrinter/Makefile new file mode 100644 index 00000000..f07f3ed3 --- /dev/null +++ b/cpp/llvm/lib/Target/Mips/InstPrinter/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/Mips/AsmPrinter/Makefile -----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMMipsAsmPrinter + +# Hack: we need to include 'main' mips target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Mips/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/Mips/MCTargetDesc/Makefile new file mode 100644 index 00000000..7fe2086a --- /dev/null +++ b/cpp/llvm/lib/Target/Mips/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/Mips/TargetDesc/Makefile -----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMMipsDesc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Mips/Makefile b/cpp/llvm/lib/Target/Mips/Makefile new file mode 100644 index 00000000..596f0714 --- /dev/null +++ b/cpp/llvm/lib/Target/Mips/Makefile @@ -0,0 +1,23 @@ +##===- lib/Target/Mips/Makefile ----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMMipsCodeGen +TARGET = Mips + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = MipsGenRegisterInfo.inc MipsGenInstrInfo.inc \ + MipsGenAsmWriter.inc MipsGenCodeEmitter.inc \ + MipsGenDAGISel.inc MipsGenCallingConv.inc \ + MipsGenSubtargetInfo.inc MipsGenMCCodeEmitter.inc \ + MipsGenEDInfo.inc MipsGenDisassemblerTables.inc +DIRS = InstPrinter Disassembler AsmParser TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Target/Mips/TargetInfo/Makefile b/cpp/llvm/lib/Target/Mips/TargetInfo/Makefile new file mode 100644 index 00000000..32f4e169 --- /dev/null +++ b/cpp/llvm/lib/Target/Mips/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/Mips/TargetInfo/Makefile -----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMMipsInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/PTX/InstPrinter/Makefile b/cpp/llvm/lib/Target/PTX/InstPrinter/Makefile new file mode 100644 index 00000000..0ccfe440 --- /dev/null +++ b/cpp/llvm/lib/Target/PTX/InstPrinter/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/PTX/AsmPrinter/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMPTXAsmPrinter + +# Hack: we need to include 'main' ptx target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Target/PTX/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/PTX/MCTargetDesc/Makefile new file mode 100644 index 00000000..35f5a7b2 --- /dev/null +++ b/cpp/llvm/lib/Target/PTX/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/PTX/TargetDesc/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMPTXDesc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/PTX/Makefile b/cpp/llvm/lib/Target/PTX/Makefile new file mode 100644 index 00000000..fa096349 --- /dev/null +++ b/cpp/llvm/lib/Target/PTX/Makefile @@ -0,0 +1,23 @@ +##===- lib/Target/PTX/Makefile -----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMPTXCodeGen +TARGET = PTX + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = PTXGenAsmWriter.inc \ + PTXGenDAGISel.inc \ + PTXGenInstrInfo.inc \ + PTXGenRegisterInfo.inc \ + PTXGenSubtargetInfo.inc + +DIRS = InstPrinter TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/PTX/TargetInfo/Makefile b/cpp/llvm/lib/Target/PTX/TargetInfo/Makefile new file mode 100644 index 00000000..86197858 --- /dev/null +++ b/cpp/llvm/lib/Target/PTX/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/PTX/TargetInfo/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMPTXInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/PowerPC/InstPrinter/Makefile b/cpp/llvm/lib/Target/PowerPC/InstPrinter/Makefile new file mode 100644 index 00000000..f097e842 --- /dev/null +++ b/cpp/llvm/lib/Target/PowerPC/InstPrinter/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/PowerPC/AsmPrinter/Makefile --------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMPowerPCAsmPrinter + +# Hack: we need to include 'main' powerpc target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/PowerPC/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/PowerPC/MCTargetDesc/Makefile new file mode 100644 index 00000000..9db66622 --- /dev/null +++ b/cpp/llvm/lib/Target/PowerPC/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/PowerPC/TargetDesc/Makefile --------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMPowerPCDesc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/PowerPC/Makefile b/cpp/llvm/lib/Target/PowerPC/Makefile new file mode 100644 index 00000000..1617b26c --- /dev/null +++ b/cpp/llvm/lib/Target/PowerPC/Makefile @@ -0,0 +1,23 @@ +##===- lib/Target/PowerPC/Makefile -------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMPowerPCCodeGen +TARGET = PPC + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = PPCGenRegisterInfo.inc \ + PPCGenAsmWriter.inc PPCGenCodeEmitter.inc \ + PPCGenInstrInfo.inc PPCGenDAGISel.inc \ + PPCGenSubtargetInfo.inc PPCGenCallingConv.inc \ + PPCGenMCCodeEmitter.inc + +DIRS = InstPrinter TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/PowerPC/TargetInfo/Makefile b/cpp/llvm/lib/Target/PowerPC/TargetInfo/Makefile new file mode 100644 index 00000000..a101aa4a --- /dev/null +++ b/cpp/llvm/lib/Target/PowerPC/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/PowerPC/TargetInfo/Makefile --------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMPowerPCInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Sparc/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/Sparc/MCTargetDesc/Makefile new file mode 100644 index 00000000..abcbe2da --- /dev/null +++ b/cpp/llvm/lib/Target/Sparc/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/Sparc/TargetDesc/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMSparcDesc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/Sparc/Makefile b/cpp/llvm/lib/Target/Sparc/Makefile new file mode 100644 index 00000000..4b81ada9 --- /dev/null +++ b/cpp/llvm/lib/Target/Sparc/Makefile @@ -0,0 +1,22 @@ +##===- lib/Target/Sparc/Makefile ---------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMSparcCodeGen +TARGET = Sparc + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = SparcGenRegisterInfo.inc SparcGenInstrInfo.inc \ + SparcGenAsmWriter.inc SparcGenDAGISel.inc \ + SparcGenSubtargetInfo.inc SparcGenCallingConv.inc + +DIRS = TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Target/Sparc/TargetInfo/Makefile b/cpp/llvm/lib/Target/Sparc/TargetInfo/Makefile new file mode 100644 index 00000000..641ed871 --- /dev/null +++ b/cpp/llvm/lib/Target/Sparc/TargetInfo/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/Sparc/TargetInfo/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMSparcInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/X86/AsmParser/Makefile b/cpp/llvm/lib/Target/X86/AsmParser/Makefile new file mode 100644 index 00000000..fb976079 --- /dev/null +++ b/cpp/llvm/lib/Target/X86/AsmParser/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/X86/AsmParser/Makefile -------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMX86AsmParser + +# Hack: we need to include 'main' x86 target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/X86/Disassembler/Makefile b/cpp/llvm/lib/Target/X86/Disassembler/Makefile new file mode 100644 index 00000000..8669fd8f --- /dev/null +++ b/cpp/llvm/lib/Target/X86/Disassembler/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/X86/Disassembler/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMX86Disassembler + +# Hack: we need to include 'main' x86 target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/X86/InstPrinter/Makefile b/cpp/llvm/lib/Target/X86/InstPrinter/Makefile new file mode 100644 index 00000000..c82aa330 --- /dev/null +++ b/cpp/llvm/lib/Target/X86/InstPrinter/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/X86/AsmPrinter/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMX86AsmPrinter + +# Hack: we need to include 'main' x86 target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/X86/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/X86/MCTargetDesc/Makefile new file mode 100644 index 00000000..b19774ee --- /dev/null +++ b/cpp/llvm/lib/Target/X86/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/X86/TargetDesc/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMX86Desc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/X86/Makefile b/cpp/llvm/lib/Target/X86/Makefile new file mode 100644 index 00000000..949661eb --- /dev/null +++ b/cpp/llvm/lib/Target/X86/Makefile @@ -0,0 +1,24 @@ +##===- lib/Target/X86/Makefile -----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMX86CodeGen +TARGET = X86 + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = X86GenRegisterInfo.inc X86GenInstrInfo.inc \ + X86GenAsmWriter.inc X86GenAsmMatcher.inc \ + X86GenAsmWriter1.inc X86GenDAGISel.inc \ + X86GenDisassemblerTables.inc X86GenFastISel.inc \ + X86GenCallingConv.inc X86GenSubtargetInfo.inc \ + X86GenEDInfo.inc + +DIRS = InstPrinter AsmParser Disassembler TargetInfo MCTargetDesc Utils + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/X86/TargetInfo/Makefile b/cpp/llvm/lib/Target/X86/TargetInfo/Makefile new file mode 100644 index 00000000..ee91982d --- /dev/null +++ b/cpp/llvm/lib/Target/X86/TargetInfo/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/X86/TargetInfo/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMX86Info + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/X86/Utils/Makefile b/cpp/llvm/lib/Target/X86/Utils/Makefile new file mode 100644 index 00000000..1df6f0f5 --- /dev/null +++ b/cpp/llvm/lib/Target/X86/Utils/Makefile @@ -0,0 +1,15 @@ +##===- lib/Target/X86/Utils/Makefile -----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../../../.. +LIBRARYNAME = LLVMX86Utils + +# Hack: we need to include 'main' x86 target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/XCore/MCTargetDesc/Makefile b/cpp/llvm/lib/Target/XCore/MCTargetDesc/Makefile new file mode 100644 index 00000000..de61543b --- /dev/null +++ b/cpp/llvm/lib/Target/XCore/MCTargetDesc/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/XCore/TargetDesc/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMXCoreDesc + +# Hack: we need to include 'main' target directory to grab private headers +CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Target/XCore/Makefile b/cpp/llvm/lib/Target/XCore/Makefile new file mode 100644 index 00000000..b823c4ed --- /dev/null +++ b/cpp/llvm/lib/Target/XCore/Makefile @@ -0,0 +1,23 @@ +##===- lib/Target/XCore/Makefile ---------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMXCoreCodeGen +TARGET = XCore + +# Make sure that tblgen is run, first thing. +BUILT_SOURCES = XCoreGenRegisterInfo.inc XCoreGenInstrInfo.inc \ + XCoreGenAsmWriter.inc \ + XCoreGenDAGISel.inc XCoreGenCallingConv.inc \ + XCoreGenSubtargetInfo.inc + +DIRS = TargetInfo MCTargetDesc + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Target/XCore/TargetInfo/Makefile b/cpp/llvm/lib/Target/XCore/TargetInfo/Makefile new file mode 100644 index 00000000..f8a40951 --- /dev/null +++ b/cpp/llvm/lib/Target/XCore/TargetInfo/Makefile @@ -0,0 +1,16 @@ +##===- lib/Target/XCore/TargetInfo/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../../.. +LIBRARYNAME = LLVMXCoreInfo + +# Hack: we need to include 'main' target directory to grab private headers +CPPFLAGS = -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/.. + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Transforms/Hello/Makefile b/cpp/llvm/lib/Transforms/Hello/Makefile new file mode 100644 index 00000000..f1e31489 --- /dev/null +++ b/cpp/llvm/lib/Transforms/Hello/Makefile @@ -0,0 +1,24 @@ +##===- lib/Transforms/Hello/Makefile -----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMHello +LOADABLE_MODULE = 1 +USEDLIBS = + +# If we don't need RTTI or EH, there's no reason to export anything +# from the hello plugin. +ifneq ($(REQUIRES_RTTI), 1) +ifneq ($(REQUIRES_EH), 1) +EXPORTED_SYMBOL_FILE = $(PROJ_SRC_DIR)/Hello.exports +endif +endif + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Transforms/IPO/Makefile b/cpp/llvm/lib/Transforms/IPO/Makefile new file mode 100644 index 00000000..5c423741 --- /dev/null +++ b/cpp/llvm/lib/Transforms/IPO/Makefile @@ -0,0 +1,15 @@ +##===- lib/Transforms/IPO/Makefile -------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMipo +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Transforms/InstCombine/Makefile b/cpp/llvm/lib/Transforms/InstCombine/Makefile new file mode 100644 index 00000000..0c488e78 --- /dev/null +++ b/cpp/llvm/lib/Transforms/InstCombine/Makefile @@ -0,0 +1,15 @@ +##===- lib/Transforms/InstCombine/Makefile -----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMInstCombine +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Transforms/Instrumentation/Makefile b/cpp/llvm/lib/Transforms/Instrumentation/Makefile new file mode 100644 index 00000000..6cbc7a9c --- /dev/null +++ b/cpp/llvm/lib/Transforms/Instrumentation/Makefile @@ -0,0 +1,15 @@ +##===- lib/Transforms/Instrumentation/Makefile -------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMInstrumentation +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Transforms/Makefile b/cpp/llvm/lib/Transforms/Makefile new file mode 100644 index 00000000..8b1df92f --- /dev/null +++ b/cpp/llvm/lib/Transforms/Makefile @@ -0,0 +1,20 @@ +##===- lib/Transforms/Makefile -----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +PARALLEL_DIRS = Utils Instrumentation Scalar InstCombine IPO Vectorize Hello + +include $(LEVEL)/Makefile.config + +# No support for plugins on windows targets +ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW Minix)) + PARALLEL_DIRS := $(filter-out Hello, $(PARALLEL_DIRS)) +endif + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/lib/Transforms/Scalar/Makefile b/cpp/llvm/lib/Transforms/Scalar/Makefile new file mode 100644 index 00000000..cc42fd00 --- /dev/null +++ b/cpp/llvm/lib/Transforms/Scalar/Makefile @@ -0,0 +1,15 @@ +##===- lib/Transforms/Scalar/Makefile ----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMScalarOpts +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Transforms/Utils/Makefile b/cpp/llvm/lib/Transforms/Utils/Makefile new file mode 100644 index 00000000..d1e9336d --- /dev/null +++ b/cpp/llvm/lib/Transforms/Utils/Makefile @@ -0,0 +1,15 @@ +##===- lib/Transforms/Utils/Makefile -----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMTransformUtils +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/Transforms/Vectorize/Makefile b/cpp/llvm/lib/Transforms/Vectorize/Makefile new file mode 100644 index 00000000..86c36585 --- /dev/null +++ b/cpp/llvm/lib/Transforms/Vectorize/Makefile @@ -0,0 +1,15 @@ +##===- lib/Transforms/Vectorize/Makefile -----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../../.. +LIBRARYNAME = LLVMVectorize +BUILD_ARCHIVE = 1 + +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/lib/VMCore/Makefile b/cpp/llvm/lib/VMCore/Makefile new file mode 100644 index 00000000..2b9b0f25 --- /dev/null +++ b/cpp/llvm/lib/VMCore/Makefile @@ -0,0 +1,34 @@ +##===- lib/VMCore/Makefile ---------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +LEVEL = ../.. +LIBRARYNAME = LLVMCore +BUILD_ARCHIVE = 1 +REQUIRES_RTTI = 1 + +BUILT_SOURCES = $(PROJ_OBJ_ROOT)/include/llvm/Intrinsics.gen + +include $(LEVEL)/Makefile.common + +GENFILE:=$(PROJ_OBJ_ROOT)/include/llvm/Intrinsics.gen + +INTRINSICTD := $(PROJ_SRC_ROOT)/include/llvm/Intrinsics.td +INTRINSICTDS := $(wildcard $(PROJ_SRC_ROOT)/include/llvm/Intrinsics*.td) + +$(ObjDir)/Intrinsics.gen.tmp: $(ObjDir)/.dir $(INTRINSICTDS) $(LLVM_TBLGEN) + $(Echo) Building Intrinsics.gen.tmp from Intrinsics.td + $(Verb) $(LLVMTableGen) $(call SYSPATH, $(INTRINSICTD)) -o $(call SYSPATH, $@) -gen-intrinsic + +$(GENFILE): $(ObjDir)/Intrinsics.gen.tmp + $(Verb) $(CMP) -s $@ $< || ( $(CP) $< $@ && \ + $(EchoCmd) Updated Intrinsics.gen because Intrinsics.gen.tmp \ + changed significantly. ) + +install-local:: $(GENFILE) + $(Echo) Installing $(DESTDIR)$(PROJ_includedir)/llvm/Intrinsics.gen + $(Verb) $(DataInstall) $(GENFILE) $(DESTDIR)$(PROJ_includedir)/llvm/Intrinsics.gen diff --git a/cpp/llvm/projects/LLVMBuild.txt b/cpp/llvm/projects/LLVMBuild.txt new file mode 100644 index 00000000..3c24d1a3 --- /dev/null +++ b/cpp/llvm/projects/LLVMBuild.txt @@ -0,0 +1,21 @@ +;===- ./projects/LLVMBuild.txt ---------------------------------*- Conf -*--===; +; +; The LLVM Compiler Infrastructure +; +; This file is distributed under the University of Illinois Open Source +; License. See LICENSE.TXT for details. +; +;===------------------------------------------------------------------------===; +; +; This is an LLVMBuild description file for the components in this subdirectory. +; +; For more information on the LLVMBuild system, please see: +; +; http://llvm.org/docs/LLVMBuild.html +; +;===------------------------------------------------------------------------===; + +[component_0] +type = Group +name = Projects +parent = $ROOT diff --git a/cpp/llvm/projects/sample/Makefile b/cpp/llvm/projects/sample/Makefile new file mode 100644 index 00000000..f96f1aba --- /dev/null +++ b/cpp/llvm/projects/sample/Makefile @@ -0,0 +1,18 @@ +##===- projects/sample/Makefile ----------------------------*- Makefile -*-===## +# +# This is a sample Makefile for a project that uses LLVM. +# +##===----------------------------------------------------------------------===## + +# +# Indicates our relative path to the top of the project's root directory. +# +LEVEL = . +DIRS = lib tools +EXTRA_DIST = include + +# +# Include the Master Makefile that knows how to build all. +# +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/projects/sample/lib/Makefile b/cpp/llvm/projects/sample/lib/Makefile new file mode 100644 index 00000000..959038b7 --- /dev/null +++ b/cpp/llvm/projects/sample/lib/Makefile @@ -0,0 +1,13 @@ +##===- projects/sample/lib/Makefile ------------------------*- Makefile -*-===## + +# +# Relative path to the top of the source tree. +# +LEVEL=.. + +# +# List all of the subdirectories that we will compile. +# +DIRS=sample + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/projects/sample/lib/sample/Makefile b/cpp/llvm/projects/sample/lib/sample/Makefile new file mode 100644 index 00000000..af63399d --- /dev/null +++ b/cpp/llvm/projects/sample/lib/sample/Makefile @@ -0,0 +1,16 @@ +##===- projects/sample/lib/sample/Makefile -----------------*- Makefile -*-===## + +# +# Indicate where we are relative to the top of the source tree. +# +LEVEL=../.. + +# +# Give the name of a library. This will build a dynamic version. +# +LIBRARYNAME=sample + +# +# Include Makefile.common so we know what to do. +# +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/projects/sample/tools/Makefile b/cpp/llvm/projects/sample/tools/Makefile new file mode 100644 index 00000000..00ff52b4 --- /dev/null +++ b/cpp/llvm/projects/sample/tools/Makefile @@ -0,0 +1,13 @@ +##===- projects/sample/tools/Makefile ----------------------*- Makefile -*-===## + +# +# Relative path to the top of the source tree. +# +LEVEL=.. + +# +# List all of the subdirectories that we will compile. +# +DIRS=sample + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/projects/sample/tools/sample/Makefile b/cpp/llvm/projects/sample/tools/sample/Makefile new file mode 100644 index 00000000..324030c5 --- /dev/null +++ b/cpp/llvm/projects/sample/tools/sample/Makefile @@ -0,0 +1,23 @@ +##===- projects/sample/tools/sample/Makefile ---------------*- Makefile -*-===## + +# +# Indicate where we are relative to the top of the source tree. +# +LEVEL=../.. + +# +# Give the name of the tool. +# +TOOLNAME=Sample + +# +# List libraries that we'll need +# We use LIBS because sample is a dynamic library. +# +USEDLIBS = sample.a + +# +# Include Makefile.common so we know what to do. +# +include $(LEVEL)/Makefile.common + diff --git a/cpp/llvm/runtime/Makefile b/cpp/llvm/runtime/Makefile new file mode 100644 index 00000000..d0e85d58 --- /dev/null +++ b/cpp/llvm/runtime/Makefile @@ -0,0 +1,31 @@ +##===- runtime/Makefile ------------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = .. +include $(LEVEL)/Makefile.config + +ifndef NO_RUNTIME_LIBS + +PARALLEL_DIRS := libprofile + +# Disable libprofile: a faulty libtool is generated by autoconf which breaks the +# build on Sparc +ifeq ($(ARCH), Sparc) +PARALLEL_DIRS := $(filter-out libprofile, $(PARALLEL_DIRS)) +endif + +ifeq ($(TARGET_OS), $(filter $(TARGET_OS), Cygwin MingW Minix)) +PARALLEL_DIRS := $(filter-out libprofile, $(PARALLEL_DIRS)) +endif + +endif + +include $(LEVEL)/Makefile.common + +install:: diff --git a/cpp/llvm/runtime/libprofile/Makefile b/cpp/llvm/runtime/libprofile/Makefile new file mode 100644 index 00000000..d8511495 --- /dev/null +++ b/cpp/llvm/runtime/libprofile/Makefile @@ -0,0 +1,51 @@ +##===- runtime/libprofile/Makefile -------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL = ../.. +include $(LEVEL)/Makefile.config + +ifneq ($(strip $(LLVMCC)),) +BYTECODE_LIBRARY = 1 +endif +LIBRARYNAME = profile_rt +LINK_LIBS_IN_SHARED = 1 +SHARED_LIBRARY = 1 +EXTRA_DIST = libprofile.exports +EXPORTED_SYMBOL_FILE = $(PROJ_SRC_DIR)/libprofile.exports + +# Build and install this archive. +BUILD_ARCHIVE = 1 +override NO_INSTALL_ARCHIVES = + +include $(LEVEL)/Makefile.common + +ifeq ($(HOST_OS),Darwin) + # Special hack to allow libprofile_rt to have an offset version number. + PROFILE_RT_LIBRARY_VERSION := $(LLVM_SUBMIT_VERSION) + + # Set dylib internal version number to llvmCore submission number. + ifdef LLVM_SUBMIT_VERSION + LLVMLibsOptions := $(LLVMLibsOptions) -Wl,-current_version \ + -Wl,$(PROFILE_RT_LIBRARY_VERSION).$(LLVM_SUBMIT_SUBVERSION) \ + -Wl,-compatibility_version -Wl,1 + endif + # Extra options to override libtool defaults. + LLVMLibsOptions := $(LLVMLibsOptions) \ + -Wl,-dead_strip \ + -Wl,-seg1addr -Wl,0xE0000000 + + # Mac OS X 10.4 and earlier tools do not allow a second -install_name on + # command line. + DARWIN_VERS := $(shell echo $(TARGET_TRIPLE) | sed 's/.*darwin\([0-9]*\).*/\1/') + ifneq ($(DARWIN_VERS),8) + LLVMLibsOptions := $(LLVMLibsOptions) \ + -Wl,-install_name \ + -Wl,"@executable_path/../lib/lib$(LIBRARYNAME)$(SHLIBEXT)" + endif +endif diff --git a/cpp/llvm/test/Archive/GNU.a b/cpp/llvm/test/Archive/GNU.a new file mode 100644 index 00000000..4c09881e Binary files /dev/null and b/cpp/llvm/test/Archive/GNU.a differ diff --git a/cpp/llvm/test/Archive/IsNAN.o b/cpp/llvm/test/Archive/IsNAN.o new file mode 100644 index 00000000..7b3a12a6 Binary files /dev/null and b/cpp/llvm/test/Archive/IsNAN.o differ diff --git a/cpp/llvm/test/Archive/MacOSX.a b/cpp/llvm/test/Archive/MacOSX.a new file mode 100644 index 00000000..8ba1e6d3 Binary files /dev/null and b/cpp/llvm/test/Archive/MacOSX.a differ diff --git a/cpp/llvm/test/Archive/SVR4.a b/cpp/llvm/test/Archive/SVR4.a new file mode 100644 index 00000000..3947813a Binary files /dev/null and b/cpp/llvm/test/Archive/SVR4.a differ diff --git a/cpp/llvm/test/Archive/xpg4.a b/cpp/llvm/test/Archive/xpg4.a new file mode 100644 index 00000000..b2bdb511 Binary files /dev/null and b/cpp/llvm/test/Archive/xpg4.a differ diff --git a/cpp/llvm/test/CodeGen/Generic/Makefile b/cpp/llvm/test/CodeGen/Generic/Makefile new file mode 100644 index 00000000..26ebc316 --- /dev/null +++ b/cpp/llvm/test/CodeGen/Generic/Makefile @@ -0,0 +1,23 @@ +# Makefile for running ad-hoc custom LLVM tests +# +%.bc: %.ll + llvm-as $< + +%.llc.s: %.bc + llc $< -o $@ + +%.gcc.s: %.c + gcc -O0 -S $< -o $@ + +%.nat: %.s + gcc -O0 -lm $< -o $@ + +%.cbe.out: %.cbe.nat + ./$< > $@ + +%.out: %.nat + ./$< > $@ + +%.clean: + rm -f $(patsubst %.clean,%.bc,$@) $(patsubst %.clean,%.*.s,$@) \ + $(patsubst %.clean,%.*.nat,$@) $(patsubst %.clean,%.*.out,$@) diff --git a/cpp/llvm/test/Makefile b/cpp/llvm/test/Makefile new file mode 100644 index 00000000..a4e53f8d --- /dev/null +++ b/cpp/llvm/test/Makefile @@ -0,0 +1,188 @@ +#===- test/Makefile ----------------------------------------*- Makefile -*--===# +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +#===------------------------------------------------------------------------===# + +LEVEL = .. +DIRS = + +all:: check-local + +# 'lit' is the default test runner. +check-local:: check-local-lit + +# Include other test rules +include Makefile.tests + +#===------------------------------------------------------------------------===# +# DejaGNU testing support +#===------------------------------------------------------------------------===# + +ifneq ($(GREP_OPTIONS),) +$(warning GREP_OPTIONS environment variable may interfere with test results) +endif + +ifdef VERBOSE +RUNTESTFLAGS := $(VERBOSE) +LIT_ARGS := -v +else +LIT_ARGS := -s -v +endif + +# -jN causes crash on Cygwin's python. +ifneq (,$(filter $(HOST_OS),Cygwin)) + LIT_ARGS += -j1 +endif + +ifdef TESTSUITE +LIT_TESTSUITE := $(TESTSUITE) +CLEANED_TESTSUITE := $(patsubst %/,%,$(TESTSUITE)) +CLEANED_TESTSUITE := $(patsubst test/%,%,$(CLEANED_TESTSUITE)) +RUNTESTFLAGS += --tool $(CLEANED_TESTSUITE) +else +LIT_TESTSUITE := . +endif + +ifdef VG +VALGRIND := valgrind --tool=memcheck --quiet --trace-children=yes --error-exitcode=3 --leak-check=full $(VALGRIND_EXTRA_ARGS) +endif + +# Check what to run for -all. +LIT_ALL_TESTSUITES := $(LIT_TESTSUITE) + +extra-lit-site-cfgs:: +.PHONY: extra-lit-site-cfgs + +ifneq ($(strip $(filter check-local-all,$(MAKECMDGOALS))),) +ifndef TESTSUITE +ifeq ($(shell test -f $(PROJ_OBJ_DIR)/../tools/clang/Makefile && echo OK), OK) +LIT_ALL_TESTSUITES += $(PROJ_OBJ_DIR)/../tools/clang/test + +# Force creation of Clang's lit.site.cfg. +clang-lit-site-cfg: FORCE + $(MAKE) -C $(PROJ_OBJ_DIR)/../tools/clang/test lit.site.cfg Unit/lit.site.cfg +extra-lit-site-cfgs:: clang-lit-site-cfg +endif +endif +endif + +IGNORE_TESTS := + +ifndef RUNLLVM2CPP +IGNORE_TESTS += llvm2cpp.exp +endif + +ifdef IGNORE_TESTS +RUNTESTFLAGS += --ignore "$(strip $(IGNORE_TESTS))" +endif + +# ulimits like these are redundantly enforced by the buildbots, so +# just removing them here won't work. +# Both AuroraUX & Solaris do not have the -m flag for ulimit +ifeq ($(HOST_OS),SunOS) +ULIMIT=ulimit -t 600 ; ulimit -d 512000 ; ulimit -v 512000 ; +else # !SunOS +ifeq ($(HOST_OS),AuroraUX) +ULIMIT=ulimit -t 600 ; ulimit -d 512000 ; ulimit -v 512000 ; +else # !AuroraUX +# Fedora 13 x86-64 python fails with -v 76800 +ULIMIT=ulimit -t 600 ; ulimit -d 512000 ; ulimit -m 512000 ; ulimit -v 1024000 ; +endif # AuroraUX +endif # SunOS + +ifneq ($(RUNTEST),) +check-local-dg:: site.exp + ( $(ULIMIT) \ + PATH="$(LLVMToolDir):$(LLVM_SRC_ROOT)/test/Scripts:$(LLVMGCCDIR)/bin:$(PATH)" \ + $(RUNTEST) $(RUNTESTFLAGS) ) +else +check-local-dg:: site.exp + @echo "*** dejagnu not found. Make sure 'runtest' is in your PATH, then reconfigure LLVM." +endif + +check-local-lit:: lit.site.cfg Unit/lit.site.cfg + ( $(ULIMIT) \ + $(LLVM_SRC_ROOT)/utils/lit/lit.py $(LIT_ARGS) $(LIT_TESTSUITE) ) + +check-local-all:: lit.site.cfg Unit/lit.site.cfg extra-lit-site-cfgs + ( $(ULIMIT) \ + $(LLVM_SRC_ROOT)/utils/lit/lit.py $(LIT_ARGS) $(LIT_ALL_TESTSUITES) ) + +clean:: + $(RM) -rf `find $(LLVM_OBJ_ROOT)/test -name Output -type d -print` + +# dsymutil is used on the Darwin to manipulate DWARF debugging information. +ifeq ($(TARGET_OS),Darwin) +DSYMUTIL=dsymutil +else +DSYMUTIL=true +endif + +ifneq ($(OCAMLOPT),) +CC_FOR_OCAMLOPT := $(shell $(OCAMLOPT) -config | grep native_c_compiler | sed -e 's/native_c_compiler: //') +CXX_FOR_OCAMLOPT := $(subst gcc,g++,$(CC_FOR_OCAMLOPT)) +endif + +FORCE: + +site.exp: FORCE + @echo 'Making a new site.exp file...' + @echo '## Autogenerated by LLVM configuration.' > site.tmp + @echo '# Do not edit!' >> site.tmp + @echo 'set target_triplet "$(TARGET_TRIPLE)"' >> site.tmp + @echo 'set TARGETS_TO_BUILD "$(TARGETS_TO_BUILD)"' >> site.tmp + @echo 'set llvmshlibdir "$(SharedLibDir)"' >>site.tmp + @echo 'set llvm_bindings "$(BINDINGS_TO_BUILD)"' >> site.tmp + @echo 'set srcroot "$(LLVM_SRC_ROOT)"' >>site.tmp + @echo 'set objroot "$(LLVM_OBJ_ROOT)"' >>site.tmp + @echo 'set srcdir "$(LLVM_SRC_ROOT)/test"' >>site.tmp + @echo 'set objdir "$(LLVM_OBJ_ROOT)/test"' >>site.tmp + @echo 'set link "' $(CXX) $(CPP.Flags) $(CXX.Flags) $(TargetCommonOpts) $(CompileCommonOpts) $(LD.Flags) '"' >>site.tmp + @echo 'set shlibext "$(SHLIBEXT)"' >> site.tmp + @echo 'set ocamlopt "$(OCAMLOPT) -cc \"$(CXX_FOR_OCAMLOPT)\" -I $(LibDir)/ocaml"' >> site.tmp + @echo 'set valgrind "$(VALGRIND)"' >> site.tmp + @echo 'set grep "$(GREP)"' >>site.tmp + @echo 'set gas "$(GAS)"' >>site.tmp + @echo '## All variables above are generated by configure. Do Not Edit ## ' >>site.tmp + @test ! -f site.exp || \ + sed '1,/^## All variables above are.*##/ d' site.exp >> site.tmp + @-rm -f site.bak + @test ! -f site.exp || mv site.exp site.bak + @mv site.tmp site.exp + +ifeq ($(DISABLE_ASSERTIONS),1) +ENABLE_ASSERTIONS=0 +else +ENABLE_ASSERTIONS=1 +endif + +lit.site.cfg: site.exp + @echo "Making LLVM 'lit.site.cfg' file..." + @$(ECHOPATH) s=@LLVM_SOURCE_DIR@=$(LLVM_SRC_ROOT)=g > lit.tmp + @$(ECHOPATH) s=@LLVM_BINARY_DIR@=$(LLVM_OBJ_ROOT)=g >> lit.tmp + @$(ECHOPATH) s=@LLVM_TOOLS_DIR@=$(ToolDir)=g >> lit.tmp + @$(ECHOPATH) s=@LLVMGCCDIR@=$(LLVMGCCDIR)=g >> lit.tmp + @$(ECHOPATH) s=@PYTHON_EXECUTABLE@=python=g >> lit.tmp + @$(ECHOPATH) s=@ENABLE_SHARED@=$(ENABLE_SHARED)=g >> lit.tmp + @$(ECHOPATH) s=@ENABLE_ASSERTIONS@=$(ENABLE_ASSERTIONS)=g >> lit.tmp + @$(ECHOPATH) s=@TARGETS_TO_BUILD@=$(TARGETS_TO_BUILD)=g >> lit.tmp + @$(ECHOPATH) s=@LLVM_BINDINGS@=$(BINDINGS_TO_BUILD)=g >> lit.tmp + @sed -f lit.tmp $(PROJ_SRC_DIR)/lit.site.cfg.in > $@ + @-rm -f lit.tmp + +Unit/lit.site.cfg: $(PROJ_OBJ_DIR)/Unit/.dir FORCE + @echo "Making LLVM unittest 'lit.site.cfg' file..." + @$(ECHOPATH) s=@LLVM_SOURCE_DIR@=$(LLVM_SRC_ROOT)=g > unit.tmp + @$(ECHOPATH) s=@LLVM_BINARY_DIR@=$(LLVM_OBJ_ROOT)=g >> unit.tmp + @$(ECHOPATH) s=@LLVM_TOOLS_DIR@=$(ToolDir)=g >> unit.tmp + @$(ECHOPATH) s=@LLVMGCCDIR@=$(LLVMGCCDIR)=g >> unit.tmp + @$(ECHOPATH) s=@LLVM_BUILD_MODE@=$(BuildMode)=g >> unit.tmp + @$(ECHOPATH) s=@ENABLE_SHARED@=$(ENABLE_SHARED)=g >> unit.tmp + @$(ECHOPATH) s=@SHLIBDIR@=$(SharedLibDir)=g >> unit.tmp + @$(ECHOPATH) s=@SHLIBPATH_VAR@=$(SHLIBPATH_VAR)=g >> unit.tmp + @sed -f unit.tmp $(PROJ_SRC_DIR)/Unit/lit.site.cfg.in > $@ + @-rm -f unit.tmp diff --git a/cpp/llvm/tools/.DS_Store b/cpp/llvm/tools/.DS_Store new file mode 100644 index 00000000..a5ea25f9 Binary files /dev/null and b/cpp/llvm/tools/.DS_Store differ diff --git a/cpp/llvm/tools/Makefile b/cpp/llvm/tools/Makefile new file mode 100644 index 00000000..8bf091a7 --- /dev/null +++ b/cpp/llvm/tools/Makefile @@ -0,0 +1,74 @@ +##===- tools/Makefile --------------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := .. + +include $(LEVEL)/Makefile.config + +# Build clang if present. + +ifneq ($(CLANG_SRC_ROOT),) + OPTIONAL_PARALLEL_DIRS := $(CLANG_SRC_ROOT) +else + OPTIONAL_PARALLEL_DIRS := clang +endif + +# Build LLDB if present. Note LLDB must be built last as it depends on the +# wider LLVM infrastructure (including Clang). +OPTIONAL_DIRS := lldb + +# NOTE: The tools are organized into five groups of four consisting of one +# large and three small executables. This is done to minimize memory load +# in parallel builds. Please retain this ordering. +DIRS := llvm-config +PARALLEL_DIRS := opt llvm-as llvm-dis \ + llc llvm-ranlib llvm-ar llvm-nm \ + llvm-ld llvm-prof llvm-link \ + lli llvm-extract llvm-mc \ + bugpoint llvm-bcanalyzer llvm-stub \ + llvm-diff macho-dump llvm-objdump llvm-readobj \ + llvm-rtdyld llvm-dwarfdump llvm-cov \ + llvm-size llvm-stress + +# Let users override the set of tools to build from the command line. +ifdef ONLY_TOOLS + OPTIONAL_PARALLEL_DIRS := + OPTIONAL_DIRS := $(findstring lldb,$(ONLY_TOOLS)) + PARALLEL_DIRS := $(filter-out lldb,$(ONLY_TOOLS)) +endif + +# These libraries build as dynamic libraries (.dylib /.so), they can only be +# built if ENABLE_PIC is set. +ifndef ONLY_TOOLS +ifeq ($(ENABLE_PIC),1) + # gold only builds if binutils is around. It requires "lto" to build before + # it so it is added to DIRS. + ifdef BINUTILS_INCDIR + DIRS += lto gold + else + PARALLEL_DIRS += lto + endif + + PARALLEL_DIRS += bugpoint-passes +endif + +ifdef LLVM_HAS_POLLY + PARALLEL_DIRS += polly +endif +endif + +# On Win32, loadable modules can be built with ENABLE_SHARED. +ifneq ($(ENABLE_SHARED),1) + ifneq (,$(filter $(HOST_OS), Cygwin MingW)) + PARALLEL_DIRS := $(filter-out bugpoint-passes, \ + $(PARALLEL_DIRS)) + endif +endif + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/tools/bugpoint-passes/Makefile b/cpp/llvm/tools/bugpoint-passes/Makefile new file mode 100644 index 00000000..61f96bc3 --- /dev/null +++ b/cpp/llvm/tools/bugpoint-passes/Makefile @@ -0,0 +1,23 @@ +##===- tools/bugpoint-passes/Makefile -- -------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../.. +LIBRARYNAME := BugpointPasses +LOADABLE_MODULE := 1 +USEDLIBS := + +# If we don't need RTTI or EH, there's no reason to export anything +# from this plugin. +ifneq ($(REQUIRES_RTTI), 1) +ifneq ($(REQUIRES_EH), 1) +EXPORTED_SYMBOL_FILE = $(PROJ_SRC_DIR)/bugpoint.exports +endif +endif + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/tools/bugpoint/Makefile b/cpp/llvm/tools/bugpoint/Makefile new file mode 100644 index 00000000..34f4bddb --- /dev/null +++ b/cpp/llvm/tools/bugpoint/Makefile @@ -0,0 +1,15 @@ +##===- tools/bugpoint/Makefile -----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../.. +TOOLNAME := bugpoint +LINK_COMPONENTS := asmparser instrumentation scalaropts ipo linker bitreader \ + bitwriter vectorize + +include $(LEVEL)/Makefile.common diff --git a/cpp/llvm/tools/clang/.DS_Store b/cpp/llvm/tools/clang/.DS_Store new file mode 100644 index 00000000..56550439 Binary files /dev/null and b/cpp/llvm/tools/clang/.DS_Store differ diff --git a/cpp/llvm/tools/clang/.gitignore b/cpp/llvm/tools/clang/.gitignore new file mode 100644 index 00000000..ddd66380 --- /dev/null +++ b/cpp/llvm/tools/clang/.gitignore @@ -0,0 +1,25 @@ +#==============================================================================# +# This file specifies intentionally untracked files that git should ignore. +# See: http://www.kernel.org/pub/software/scm/git/docs/gitignore.html +# +# This file is intentionally different from the output of `git svn show-ignore`, +# as most of those are useless. +#==============================================================================# + +#==============================================================================# +# File extensions to be ignored anywhere in the tree. +#==============================================================================# +# Temp files created by most text editors. +*~ +# Merge files created by git. +*.orig +# Byte compiled python modules. +*.pyc +# vim swap files +.*.swp + +#==============================================================================# +# Explicit files to ignore (only matches one). +#==============================================================================# +cscope.files +cscope.out diff --git a/cpp/llvm/tools/clang/CMakeLists.txt b/cpp/llvm/tools/clang/CMakeLists.txt new file mode 100644 index 00000000..c828482a --- /dev/null +++ b/cpp/llvm/tools/clang/CMakeLists.txt @@ -0,0 +1,282 @@ +# If we are not building as a part of LLVM, build Clang as an +# standalone project, using LLVM as an external library: +if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR ) + project(Clang) + cmake_minimum_required(VERSION 2.8) + + set(CLANG_PATH_TO_LLVM_SOURCE "" CACHE PATH + "Path to LLVM source code. Not necessary if using an installed LLVM.") + set(CLANG_PATH_TO_LLVM_BUILD "" CACHE PATH + "Path to the directory where LLVM was built or installed.") + + if( CLANG_PATH_TO_LLVM_SOURCE ) + if( NOT EXISTS "${CLANG_PATH_TO_LLVM_SOURCE}/cmake/config-ix.cmake" ) + message(FATAL_ERROR "Please set CLANG_PATH_TO_LLVM_SOURCE to the root directory of LLVM source code.") + else() + get_filename_component(LLVM_MAIN_SRC_DIR ${CLANG_PATH_TO_LLVM_SOURCE} + ABSOLUTE) + list(APPEND CMAKE_MODULE_PATH "${LLVM_MAIN_SRC_DIR}/cmake/modules") + endif() + endif() + + if( NOT EXISTS "${CLANG_PATH_TO_LLVM_BUILD}/bin/llvm-tblgen${CMAKE_EXECUTABLE_SUFFIX}" ) + # Looking for bin/Debug/llvm-tblgen is a complete hack. How can we get + # around this? + if( NOT EXISTS "${CLANG_PATH_TO_LLVM_BUILD}/bin/Debug/llvm-tblgen${CMAKE_EXECUTABLE_SUFFIX}" ) + message(FATAL_ERROR "Please set CLANG_PATH_TO_LLVM_BUILD to a directory containing a LLVM build.") + endif() + endif() + + list(APPEND CMAKE_MODULE_PATH "${CLANG_PATH_TO_LLVM_BUILD}/share/llvm/cmake") + + get_filename_component(PATH_TO_LLVM_BUILD ${CLANG_PATH_TO_LLVM_BUILD} + ABSOLUTE) + + include(AddLLVM) + include(TableGen) + include("${CLANG_PATH_TO_LLVM_BUILD}/share/llvm/cmake/LLVMConfig.cmake") + include(HandleLLVMOptions) + + set(PACKAGE_VERSION "${LLVM_PACKAGE_VERSION}") + + set(LLVM_MAIN_INCLUDE_DIR "${LLVM_MAIN_SRC_DIR}/include") + set(LLVM_BINARY_DIR ${CMAKE_BINARY_DIR}) + + set(CMAKE_INCLUDE_CURRENT_DIR ON) + include_directories("${PATH_TO_LLVM_BUILD}/include" "${LLVM_MAIN_INCLUDE_DIR}") + link_directories("${PATH_TO_LLVM_BUILD}/lib") + + if( EXISTS "${CLANG_PATH_TO_LLVM_BUILD}/bin/llvm-tblgen${CMAKE_EXECUTABLE_SUFFIX}" ) + set(LLVM_TABLEGEN_EXE "${PATH_TO_LLVM_BUILD}/bin/llvm-tblgen${CMAKE_EXECUTABLE_SUFFIX}") + else() + # FIXME: This is an utter hack. + set(LLVM_TABLEGEN_EXE "${PATH_TO_LLVM_BUILD}/bin/Debug/llvm-tblgen${CMAKE_EXECUTABLE_SUFFIX}") + endif() + + set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin ) + set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib ) + set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib ) + + set( CLANG_BUILT_STANDALONE 1 ) +endif() + +set(CLANG_RESOURCE_DIR "" CACHE STRING + "Relative directory from the Clang binary to its resource files.") + +set(C_INCLUDE_DIRS "" CACHE STRING + "Colon separated list of directories clang will search for headers.") + +set(GCC_INSTALL_PREFIX "" CACHE PATH "Directory where gcc is installed." ) +set(DEFAULT_SYSROOT "" CACHE PATH + "Default to all compiler invocations for --sysroot=." ) + +set(CLANG_VENDOR "" CACHE STRING + "Vendor-specific text for showing with version information.") + +if( CLANG_VENDOR ) + add_definitions( -DCLANG_VENDOR="${CLANG_VENDOR} " ) +endif() + +set(CLANG_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) +set(CLANG_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}) + +if( CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR AND NOT MSVC_IDE ) + message(FATAL_ERROR "In-source builds are not allowed. CMake would overwrite " +"the makefiles distributed with LLVM. Please create a directory and run cmake " +"from there, passing the path to this source directory as the last argument. " +"This process created the file `CMakeCache.txt' and the directory " +"`CMakeFiles'. Please delete them.") +endif() + +if( NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR ) + file(GLOB_RECURSE + tablegenned_files_on_include_dir + "${CLANG_SOURCE_DIR}/include/clang/*.inc") + if( tablegenned_files_on_include_dir ) + message(FATAL_ERROR "Apparently there is a previous in-source build, " +"probably as the result of running `configure' and `make' on " +"${CLANG_SOURCE_DIR}. This may cause problems. The suspicious files are:\n" +"${tablegenned_files_on_include_dir}\nPlease clean the source directory.") + endif() +endif() + +# Compute the Clang version from the LLVM version. +string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION + ${PACKAGE_VERSION}) +message(STATUS "Clang version: ${CLANG_VERSION}") + +string(REGEX REPLACE "([0-9]+)\\.[0-9]+(\\.[0-9]+)?" "\\1" CLANG_VERSION_MAJOR + ${CLANG_VERSION}) +string(REGEX REPLACE "[0-9]+\\.([0-9]+)(\\.[0-9]+)?" "\\1" CLANG_VERSION_MINOR + ${CLANG_VERSION}) +if (${CLANG_VERSION} MATCHES "[0-9]+\\.[0-9]+\\.[0-9]+") + set(CLANG_HAS_VERSION_PATCHLEVEL 1) + string(REGEX REPLACE "[0-9]+\\.[0-9]+\\.([0-9]+)" "\\1" CLANG_VERSION_PATCHLEVEL + ${CLANG_VERSION}) +else() + set(CLANG_HAS_VERSION_PATCHLEVEL 0) +endif() + +# Configure the Version.inc file. +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/include/clang/Basic/Version.inc.in + ${CMAKE_CURRENT_BINARY_DIR}/include/clang/Basic/Version.inc) + +# Add appropriate flags for GCC +if (LLVM_COMPILER_IS_GCC_COMPATIBLE) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-common -Woverloaded-virtual -Wcast-qual -fno-strict-aliasing -pedantic -Wno-long-long -Wall -W -Wno-unused-parameter -Wwrite-strings") +endif () + +if (APPLE) + set(CMAKE_MODULE_LINKER_FLAGS "-Wl,-flat_namespace -Wl,-undefined -Wl,suppress") +endif () + +configure_file( + ${CLANG_SOURCE_DIR}/include/clang/Config/config.h.cmake + ${CLANG_BINARY_DIR}/include/clang/Config/config.h) + +include(LLVMParseArguments) + +function(clang_tablegen) + # Syntax: + # clang_tablegen output-file [tablegen-arg ...] SOURCE source-file + # [[TARGET cmake-target-name] [DEPENDS extra-dependency ...]] + # + # Generates a custom command for invoking tblgen as + # + # tblgen source-file -o=output-file tablegen-arg ... + # + # and, if cmake-target-name is provided, creates a custom target for + # executing the custom command depending on output-file. It is + # possible to list more files to depend after DEPENDS. + + parse_arguments( CTG "SOURCE;TARGET;DEPENDS" "" ${ARGN} ) + + if( NOT CTG_SOURCE ) + message(FATAL_ERROR "SOURCE source-file required by clang_tablegen") + endif() + + set( LLVM_TARGET_DEFINITIONS ${CTG_SOURCE} ) + tablegen( CLANG ${CTG_DEFAULT_ARGS} ) + + list( GET CTG_DEFAULT_ARGS 0 output_file ) + if( CTG_TARGET ) + add_custom_target( ${CTG_TARGET} DEPENDS ${output_file} ${CTG_DEPENDS} ) + set_target_properties( ${CTG_TARGET} PROPERTIES FOLDER "Clang tablegenning") + endif() +endfunction(clang_tablegen) + +macro(add_clang_library name) + llvm_process_sources(srcs ${ARGN}) + if(MSVC_IDE OR XCODE) + string( REGEX MATCHALL "/[^/]+" split_path ${CMAKE_CURRENT_SOURCE_DIR}) + list( GET split_path -1 dir) + file( GLOB_RECURSE headers + ../../../include/clang/StaticAnalyzer${dir}/*.h + ../../../include/clang/StaticAnalyzer${dir}/*.td + ../../../include/clang/StaticAnalyzer${dir}/*.def + ../../include/clang${dir}/*.h + ../../include/clang${dir}/*.td + ../../include/clang${dir}/*.def) + set(srcs ${srcs} ${headers}) + endif(MSVC_IDE OR XCODE) + if (MODULE) + set(libkind MODULE) + elseif (SHARED_LIBRARY) + set(libkind SHARED) + else() + set(libkind) + endif() + add_library( ${name} ${libkind} ${srcs} ) + if( LLVM_COMMON_DEPENDS ) + add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} ) + endif( LLVM_COMMON_DEPENDS ) + + target_link_libraries( ${name} ${LLVM_USED_LIBS} ) + llvm_config( ${name} ${LLVM_LINK_COMPONENTS} ) + target_link_libraries( ${name} ${LLVM_COMMON_LIBS} ) + link_system_libs( ${name} ) + + add_dependencies(${name} ClangDiagnosticCommon) + if(MSVC) + get_target_property(cflag ${name} COMPILE_FLAGS) + if(NOT cflag) + set(cflag "") + endif(NOT cflag) + set(cflag "${cflag} /Za") + set_target_properties(${name} PROPERTIES COMPILE_FLAGS ${cflag}) + endif(MSVC) + install(TARGETS ${name} + LIBRARY DESTINATION lib${LLVM_LIBDIR_SUFFIX} + ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX} + RUNTIME DESTINATION bin) + set_target_properties(${name} PROPERTIES FOLDER "Clang libraries") +endmacro(add_clang_library) + +macro(add_clang_executable name) + add_llvm_executable( ${name} ${ARGN} ) + set_target_properties(${name} PROPERTIES FOLDER "Clang executables") +endmacro(add_clang_executable) + +include_directories(BEFORE + ${CMAKE_CURRENT_BINARY_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + +install(DIRECTORY include/ + DESTINATION include + FILES_MATCHING + PATTERN "*.def" + PATTERN "*.h" + PATTERN "config.h" EXCLUDE + PATTERN ".svn" EXCLUDE + ) + +install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/include/ + DESTINATION include + FILES_MATCHING + PATTERN "CMakeFiles" EXCLUDE + PATTERN "*.inc" + ) + +add_definitions( -D_GNU_SOURCE ) + +# Clang version information +set(CLANG_EXECUTABLE_VERSION + "${CLANG_VERSION_MAJOR}.${CLANG_VERSION_MINOR}" CACHE STRING + "Version number that will be placed into the clang executable, in the form XX.YY") +set(LIBCLANG_LIBRARY_VERSION + "${CLANG_VERSION_MAJOR}.${CLANG_VERSION_MINOR}" CACHE STRING + "Version number that will be placed into the libclang library , in the form XX.YY") +mark_as_advanced(CLANG_EXECUTABLE_VERSION LIBCLANG_LIBRARY_VERSION) + +add_subdirectory(utils/TableGen) + +option(CLANG_BUILD_EXAMPLES "Build CLANG example programs by default." OFF) +add_subdirectory(examples) + +add_subdirectory(include) +add_subdirectory(lib) +add_subdirectory(tools) +add_subdirectory(runtime) + +# TODO: docs. +add_subdirectory(test) + +if( LLVM_INCLUDE_TESTS ) + if( NOT CLANG_BUILT_STANDALONE ) + add_subdirectory(unittests) + endif() +endif() + +# Workaround for MSVS10 to avoid the Dialog Hell +# FIXME: This could be removed with future version of CMake. +if( CLANG_BUILT_STANDALONE AND MSVC_VERSION EQUAL 1600 ) + set(CLANG_SLN_FILENAME "${CMAKE_CURRENT_BINARY_DIR}/Clang.sln") + if( EXISTS "${CLANG_SLN_FILENAME}" ) + file(APPEND "${CLANG_SLN_FILENAME}" "\n# This should be regenerated!\n") + endif() +endif() + +set(BUG_REPORT_URL "http://llvm.org/bugs/" CACHE STRING + "Default URL where bug reports are to be submitted.") diff --git a/cpp/llvm/tools/clang/INPUTS/Cocoa_h.m b/cpp/llvm/tools/clang/INPUTS/Cocoa_h.m new file mode 100644 index 00000000..e6ba5992 --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/Cocoa_h.m @@ -0,0 +1,2 @@ + +#import diff --git a/cpp/llvm/tools/clang/INPUTS/all-std-headers.cpp b/cpp/llvm/tools/clang/INPUTS/all-std-headers.cpp new file mode 100644 index 00000000..5b5f4eca --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/all-std-headers.cpp @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if __has_include() +#include +#endif +#include +#include +#include +#include + +#if __cplusplus >= 201103 || defined(__GXX_EXPERIMENTAL_CXX0X__) +#include +#if __has_include() +#include +#endif +#include +#if __has_include() +#include +#endif +#include +#include +#if __has_include() +#include +#endif +#include +#include +#include +#include +#include +#if __has_include() +#include +#endif +#include +#include +#include +#include +#if __has_include() +#include +#endif +#include +#include +#endif diff --git a/cpp/llvm/tools/clang/INPUTS/c99-intconst-1.c b/cpp/llvm/tools/clang/INPUTS/c99-intconst-1.c new file mode 100644 index 00000000..629b0bca --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/c99-intconst-1.c @@ -0,0 +1,639 @@ +/* Test for integer constant types. */ + +/* Origin: Joseph Myers . */ +/* { dg-do compile } */ +/* { dg-options "-std=iso9899:1999 -pedantic-errors" } */ + +#include + +/* Assertion that constant C is of type T. */ +#define ASSERT_CONST_TYPE(C, T) \ + do { \ + typedef T type; \ + typedef type **typepp; \ + typedef __typeof__((C)) ctype; \ + typedef ctype **ctypepp; \ + typepp x = 0; \ + ctypepp y = 0; \ + x = y; \ + y = x; \ + } while (0) + +/* (T *) if E is zero, (void *) otherwise. */ +#define type_if_not(T, E) __typeof__(0 ? (T *)0 : (void *)(E)) + +/* (T *) if E is nonzero, (void *) otherwise. */ +#define type_if(T, E) type_if_not(T, !(E)) + +/* Combine pointer types, all but one (void *). */ +#define type_comb2(T1, T2) __typeof__(0 ? (T1)0 : (T2)0) +#define type_comb3(T1, T2, T3) type_comb2(T1, type_comb2(T2, T3)) +#define type_comb4(T1, T2, T3, T4) \ + type_comb2(T1, type_comb2(T2, type_comb2(T3, T4))) +#define type_comb6(T1, T2, T3, T4, T5, T6) \ + type_comb2(T1, \ + type_comb2(T2, \ + type_comb2(T3, \ + type_comb2(T4, \ + type_comb2(T5, T6))))) + +/* (T1 *) if E1, otherwise (T2 *) if E2. */ +#define first_of2p(T1, E1, T2, E2) type_comb2(type_if(T1, (E1)), \ + type_if(T2, (!(E1) && (E2)))) +/* (T1 *) if E1, otherwise (T2 *) if E2, otherwise (T3 *) if E3. */ +#define first_of3p(T1, E1, T2, E2, T3, E3) \ + type_comb3(type_if(T1, (E1)), \ + type_if(T2, (!(E1) && (E2))), \ + type_if(T3, (!(E1) && !(E2) && (E3)))) +/* (T1 *) if E1, otherwise (T2 *) if E2, otherwise (T3 *) if E3, otherwise + (T4 *) if E4. */ +#define first_of4p(T1, E1, T2, E2, T3, E3, T4, E4) \ + type_comb4(type_if(T1, (E1)), \ + type_if(T2, (!(E1) && (E2))), \ + type_if(T3, (!(E1) && !(E2) && (E3))), \ + type_if(T4, (!(E1) && !(E2) && !(E3) && (E4)))) +/* (T1 *) if E1, otherwise (T2 *) if E2, otherwise (T3 *) if E3, otherwise + (T4 *) if E4, otherwise (T5 *) if E5, otherwise (T6 *) if E6. */ +#define first_of6p(T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6) \ + type_comb6(type_if(T1, (E1)), \ + type_if(T2, (!(E1) && (E2))), \ + type_if(T3, (!(E1) && !(E2) && (E3))), \ + type_if(T4, (!(E1) && !(E2) && !(E3) && (E4))), \ + type_if(T5, (!(E1) && !(E2) && !(E3) && !(E4) && (E5))), \ + type_if(T6, (!(E1) && !(E2) && !(E3) \ + && !(E4) && !(E5) && (E6)))) + +/* Likewise, but return the original type rather than a pointer type. */ +#define first_of2(T1, E1, T2, E2) \ + __typeof__(*((first_of2p(T1, (E1), T2, (E2)))0)) +#define first_of3(T1, E1, T2, E2, T3, E3) \ + __typeof__(*((first_of3p(T1, (E1), T2, (E2), T3, (E3)))0)) +#define first_of4(T1, E1, T2, E2, T3, E3, T4, E4) \ + __typeof__(*((first_of4p(T1, (E1), T2, (E2), T3, (E3), T4, (E4)))0)) +#define first_of6(T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6) \ + __typeof__(*((first_of6p(T1, (E1), T2, (E2), T3, (E3), \ + T4, (E4), T5, (E5), T6, (E6)))0)) + +/* Types of constants according to the C99 rules. */ +#define C99_UNSUF_DEC_TYPE(C) \ + first_of3(int, (C) <= INT_MAX, \ + long int, (C) <= LONG_MAX, \ + long long int, (C) <= LLONG_MAX) +#define C99_UNSUF_OCTHEX_TYPE(C) \ + first_of6(int, (C) <= INT_MAX, \ + unsigned int, (C) <= UINT_MAX, \ + long int, (C) <= LONG_MAX, \ + unsigned long int, (C) <= ULONG_MAX, \ + long long int, (C) <= LLONG_MAX, \ + unsigned long long int, (C) <= ULLONG_MAX) +#define C99_SUFu_TYPE(C) \ + first_of3(unsigned int, (C) <= UINT_MAX, \ + unsigned long int, (C) <= ULONG_MAX, \ + unsigned long long int, (C) <= ULLONG_MAX) +#define C99_SUFl_DEC_TYPE(C) \ + first_of2(long int, (C) <= LONG_MAX, \ + long long int, (C) <= LLONG_MAX) +#define C99_SUFl_OCTHEX_TYPE(C) \ + first_of4(long int, (C) <= LONG_MAX, \ + unsigned long int, (C) <= ULONG_MAX, \ + long long int, (C) <= LLONG_MAX, \ + unsigned long long int, (C) <= ULLONG_MAX) +#define C99_SUFul_TYPE(C) \ + first_of2(unsigned long int, (C) <= ULONG_MAX, \ + unsigned long long int, (C) <= ULLONG_MAX) +#define C99_SUFll_OCTHEX_TYPE(C) \ + first_of2(long long int, (C) <= LLONG_MAX, \ + unsigned long long int, (C) <= ULLONG_MAX) + +/* Checks that constants have correct type. */ +#define CHECK_UNSUF_DEC_TYPE(C) ASSERT_CONST_TYPE((C), C99_UNSUF_DEC_TYPE((C))) +#define CHECK_UNSUF_OCTHEX_TYPE(C) \ + ASSERT_CONST_TYPE((C), C99_UNSUF_OCTHEX_TYPE((C))) +#define CHECK_SUFu_TYPE(C) ASSERT_CONST_TYPE((C), C99_SUFu_TYPE((C))) +#define CHECK_SUFl_DEC_TYPE(C) ASSERT_CONST_TYPE((C), C99_SUFl_DEC_TYPE((C))) +#define CHECK_SUFl_OCTHEX_TYPE(C) \ + ASSERT_CONST_TYPE((C), C99_SUFl_OCTHEX_TYPE((C))) +#define CHECK_SUFul_TYPE(C) ASSERT_CONST_TYPE((C), C99_SUFul_TYPE((C))) +#define CHECK_SUFll_DEC_TYPE(C) ASSERT_CONST_TYPE((C), long long int) +#define CHECK_SUFll_OCTHEX_TYPE(C) \ + ASSERT_CONST_TYPE((C), C99_SUFll_OCTHEX_TYPE((C))) +#define CHECK_SUFull_TYPE(C) ASSERT_CONST_TYPE((C), unsigned long long int) + +/* Check a decimal value, with all suffixes. */ +#define CHECK_DEC_CONST(C) \ + CHECK_UNSUF_DEC_TYPE(C); \ + CHECK_SUFu_TYPE(C##u); \ + CHECK_SUFu_TYPE(C##U); \ + CHECK_SUFl_DEC_TYPE(C##l); \ + CHECK_SUFl_DEC_TYPE(C##L); \ + CHECK_SUFul_TYPE(C##ul); \ + CHECK_SUFul_TYPE(C##uL); \ + CHECK_SUFul_TYPE(C##Ul); \ + CHECK_SUFul_TYPE(C##UL); \ + CHECK_SUFll_DEC_TYPE(C##ll); \ + CHECK_SUFll_DEC_TYPE(C##LL); \ + CHECK_SUFull_TYPE(C##ull); \ + CHECK_SUFull_TYPE(C##uLL); \ + CHECK_SUFull_TYPE(C##Ull); \ + CHECK_SUFull_TYPE(C##ULL); + +/* Check an octal or hexadecimal value, with all suffixes. */ +#define CHECK_OCTHEX_CONST(C) \ + CHECK_UNSUF_OCTHEX_TYPE(C); \ + CHECK_SUFu_TYPE(C##u); \ + CHECK_SUFu_TYPE(C##U); \ + CHECK_SUFl_OCTHEX_TYPE(C##l); \ + CHECK_SUFl_OCTHEX_TYPE(C##L); \ + CHECK_SUFul_TYPE(C##ul); \ + CHECK_SUFul_TYPE(C##uL); \ + CHECK_SUFul_TYPE(C##Ul); \ + CHECK_SUFul_TYPE(C##UL); \ + CHECK_SUFll_OCTHEX_TYPE(C##ll); \ + CHECK_SUFll_OCTHEX_TYPE(C##LL); \ + CHECK_SUFull_TYPE(C##ull); \ + CHECK_SUFull_TYPE(C##uLL); \ + CHECK_SUFull_TYPE(C##Ull); \ + CHECK_SUFull_TYPE(C##ULL); + +#define CHECK_OCT_CONST(C) CHECK_OCTHEX_CONST(C) +#define CHECK_HEX_CONST(C) \ + CHECK_OCTHEX_CONST(0x##C); \ + CHECK_OCTHEX_CONST(0X##C); + +/* True iff "long long" is at least B bits. This presumes that (B-2)/3 is at + most 63. */ +#define LLONG_AT_LEAST(B) \ + (LLONG_MAX >> ((B)-2)/3 >> ((B)-2)/3 \ + >> ((B)-2 - ((B)-2)/3 - ((B)-2)/3)) + +#define LLONG_HAS_BITS(B) (LLONG_AT_LEAST((B)) && !LLONG_AT_LEAST((B) + 1)) + +void +foo (void) +{ + /* Decimal. */ + /* Check all 2^n and 2^n - 1 up to 2^71 - 1. */ + CHECK_DEC_CONST(1); + CHECK_DEC_CONST(2); + CHECK_DEC_CONST(3); + CHECK_DEC_CONST(4); + CHECK_DEC_CONST(7); + CHECK_DEC_CONST(8); + CHECK_DEC_CONST(15); + CHECK_DEC_CONST(16); + CHECK_DEC_CONST(31); + CHECK_DEC_CONST(32); + CHECK_DEC_CONST(63); + CHECK_DEC_CONST(64); + CHECK_DEC_CONST(127); + CHECK_DEC_CONST(128); + CHECK_DEC_CONST(255); + CHECK_DEC_CONST(256); + CHECK_DEC_CONST(511); + CHECK_DEC_CONST(512); + CHECK_DEC_CONST(1023); + CHECK_DEC_CONST(1024); + CHECK_DEC_CONST(2047); + CHECK_DEC_CONST(2048); + CHECK_DEC_CONST(4095); + CHECK_DEC_CONST(4096); + CHECK_DEC_CONST(8191); + CHECK_DEC_CONST(8192); + CHECK_DEC_CONST(16383); + CHECK_DEC_CONST(16384); + CHECK_DEC_CONST(32767); + CHECK_DEC_CONST(32768); + CHECK_DEC_CONST(65535); + CHECK_DEC_CONST(65536); + CHECK_DEC_CONST(131071); + CHECK_DEC_CONST(131072); + CHECK_DEC_CONST(262143); + CHECK_DEC_CONST(262144); + CHECK_DEC_CONST(524287); + CHECK_DEC_CONST(524288); + CHECK_DEC_CONST(1048575); + CHECK_DEC_CONST(1048576); + CHECK_DEC_CONST(2097151); + CHECK_DEC_CONST(2097152); + CHECK_DEC_CONST(4194303); + CHECK_DEC_CONST(4194304); + CHECK_DEC_CONST(8388607); + CHECK_DEC_CONST(8388608); + CHECK_DEC_CONST(16777215); + CHECK_DEC_CONST(16777216); + CHECK_DEC_CONST(33554431); + CHECK_DEC_CONST(33554432); + CHECK_DEC_CONST(67108863); + CHECK_DEC_CONST(67108864); + CHECK_DEC_CONST(134217727); + CHECK_DEC_CONST(134217728); + CHECK_DEC_CONST(268435455); + CHECK_DEC_CONST(268435456); + CHECK_DEC_CONST(536870911); + CHECK_DEC_CONST(536870912); + CHECK_DEC_CONST(1073741823); + CHECK_DEC_CONST(1073741824); + CHECK_DEC_CONST(2147483647); + CHECK_DEC_CONST(2147483648); + CHECK_DEC_CONST(4294967295); + CHECK_DEC_CONST(4294967296); + CHECK_DEC_CONST(8589934591); + CHECK_DEC_CONST(8589934592); + CHECK_DEC_CONST(17179869183); + CHECK_DEC_CONST(17179869184); + CHECK_DEC_CONST(34359738367); + CHECK_DEC_CONST(34359738368); + CHECK_DEC_CONST(68719476735); + CHECK_DEC_CONST(68719476736); + CHECK_DEC_CONST(137438953471); + CHECK_DEC_CONST(137438953472); + CHECK_DEC_CONST(274877906943); + CHECK_DEC_CONST(274877906944); + CHECK_DEC_CONST(549755813887); + CHECK_DEC_CONST(549755813888); + CHECK_DEC_CONST(1099511627775); + CHECK_DEC_CONST(1099511627776); + CHECK_DEC_CONST(2199023255551); + CHECK_DEC_CONST(2199023255552); + CHECK_DEC_CONST(4398046511103); + CHECK_DEC_CONST(4398046511104); + CHECK_DEC_CONST(8796093022207); + CHECK_DEC_CONST(8796093022208); + CHECK_DEC_CONST(17592186044415); + CHECK_DEC_CONST(17592186044416); + CHECK_DEC_CONST(35184372088831); + CHECK_DEC_CONST(35184372088832); + CHECK_DEC_CONST(70368744177663); + CHECK_DEC_CONST(70368744177664); + CHECK_DEC_CONST(140737488355327); + CHECK_DEC_CONST(140737488355328); + CHECK_DEC_CONST(281474976710655); + CHECK_DEC_CONST(281474976710656); + CHECK_DEC_CONST(562949953421311); + CHECK_DEC_CONST(562949953421312); + CHECK_DEC_CONST(1125899906842623); + CHECK_DEC_CONST(1125899906842624); + CHECK_DEC_CONST(2251799813685247); + CHECK_DEC_CONST(2251799813685248); + CHECK_DEC_CONST(4503599627370495); + CHECK_DEC_CONST(4503599627370496); + CHECK_DEC_CONST(9007199254740991); + CHECK_DEC_CONST(9007199254740992); + CHECK_DEC_CONST(18014398509481983); + CHECK_DEC_CONST(18014398509481984); + CHECK_DEC_CONST(36028797018963967); + CHECK_DEC_CONST(36028797018963968); + CHECK_DEC_CONST(72057594037927935); + CHECK_DEC_CONST(72057594037927936); + CHECK_DEC_CONST(144115188075855871); + CHECK_DEC_CONST(144115188075855872); + CHECK_DEC_CONST(288230376151711743); + CHECK_DEC_CONST(288230376151711744); + CHECK_DEC_CONST(576460752303423487); + CHECK_DEC_CONST(576460752303423488); + CHECK_DEC_CONST(1152921504606846975); + CHECK_DEC_CONST(1152921504606846976); + CHECK_DEC_CONST(2305843009213693951); + CHECK_DEC_CONST(2305843009213693952); + CHECK_DEC_CONST(4611686018427387903); + CHECK_DEC_CONST(4611686018427387904); + CHECK_DEC_CONST(9223372036854775807); +#if LLONG_AT_LEAST(65) + CHECK_DEC_CONST(9223372036854775808); + CHECK_DEC_CONST(18446744073709551615); +#endif +#if LLONG_AT_LEAST(66) + CHECK_DEC_CONST(18446744073709551616); + CHECK_DEC_CONST(36893488147419103231); +#endif +#if LLONG_AT_LEAST(67) + CHECK_DEC_CONST(36893488147419103232); + CHECK_DEC_CONST(73786976294838206463); +#endif +#if LLONG_AT_LEAST(68) + CHECK_DEC_CONST(73786976294838206464); + CHECK_DEC_CONST(147573952589676412927); +#endif +#if LLONG_AT_LEAST(69) + CHECK_DEC_CONST(147573952589676412928); + CHECK_DEC_CONST(295147905179352825855); +#endif +#if LLONG_AT_LEAST(70) + CHECK_DEC_CONST(295147905179352825856); + CHECK_DEC_CONST(590295810358705651711); +#endif +#if LLONG_AT_LEAST(71) + CHECK_DEC_CONST(590295810358705651712); + CHECK_DEC_CONST(1180591620717411303423); +#endif +#if LLONG_AT_LEAST(72) + CHECK_DEC_CONST(1180591620717411303424); + CHECK_DEC_CONST(2361183241434822606847); +#endif + /* Octal and hexadecimal. */ + /* Check all 2^n and 2^n - 1 up to 2^72 - 1. */ + CHECK_OCT_CONST(0); + CHECK_HEX_CONST(0); + CHECK_OCT_CONST(01); + CHECK_HEX_CONST(1); + CHECK_OCT_CONST(02); + CHECK_HEX_CONST(2); + CHECK_OCT_CONST(03); + CHECK_HEX_CONST(3); + CHECK_OCT_CONST(04); + CHECK_HEX_CONST(4); + CHECK_OCT_CONST(07); + CHECK_HEX_CONST(7); + CHECK_OCT_CONST(010); + CHECK_HEX_CONST(8); + CHECK_OCT_CONST(017); + CHECK_HEX_CONST(f); + CHECK_OCT_CONST(020); + CHECK_HEX_CONST(10); + CHECK_OCT_CONST(037); + CHECK_HEX_CONST(1f); + CHECK_OCT_CONST(040); + CHECK_HEX_CONST(20); + CHECK_OCT_CONST(077); + CHECK_HEX_CONST(3f); + CHECK_OCT_CONST(0100); + CHECK_HEX_CONST(40); + CHECK_OCT_CONST(0177); + CHECK_HEX_CONST(7f); + CHECK_OCT_CONST(0200); + CHECK_HEX_CONST(80); + CHECK_OCT_CONST(0377); + CHECK_HEX_CONST(ff); + CHECK_OCT_CONST(0400); + CHECK_HEX_CONST(100); + CHECK_OCT_CONST(0777); + CHECK_HEX_CONST(1ff); + CHECK_OCT_CONST(01000); + CHECK_HEX_CONST(200); + CHECK_OCT_CONST(01777); + CHECK_HEX_CONST(3ff); + CHECK_OCT_CONST(02000); + CHECK_HEX_CONST(400); + CHECK_OCT_CONST(03777); + CHECK_HEX_CONST(7ff); + CHECK_OCT_CONST(04000); + CHECK_HEX_CONST(800); + CHECK_OCT_CONST(07777); + CHECK_HEX_CONST(fff); + CHECK_OCT_CONST(010000); + CHECK_HEX_CONST(1000); + CHECK_OCT_CONST(017777); + CHECK_HEX_CONST(1fff); + CHECK_OCT_CONST(020000); + CHECK_HEX_CONST(2000); + CHECK_OCT_CONST(037777); + CHECK_HEX_CONST(3fff); + CHECK_OCT_CONST(040000); + CHECK_HEX_CONST(4000); + CHECK_OCT_CONST(077777); + CHECK_HEX_CONST(7fff); + CHECK_OCT_CONST(0100000); + CHECK_HEX_CONST(8000); + CHECK_OCT_CONST(0177777); + CHECK_HEX_CONST(ffff); + CHECK_OCT_CONST(0200000); + CHECK_HEX_CONST(10000); + CHECK_OCT_CONST(0377777); + CHECK_HEX_CONST(1ffff); + CHECK_OCT_CONST(0400000); + CHECK_HEX_CONST(20000); + CHECK_OCT_CONST(0777777); + CHECK_HEX_CONST(3ffff); + CHECK_OCT_CONST(01000000); + CHECK_HEX_CONST(40000); + CHECK_OCT_CONST(01777777); + CHECK_HEX_CONST(7ffff); + CHECK_OCT_CONST(02000000); + CHECK_HEX_CONST(80000); + CHECK_OCT_CONST(03777777); + CHECK_HEX_CONST(fffff); + CHECK_OCT_CONST(04000000); + CHECK_HEX_CONST(100000); + CHECK_OCT_CONST(07777777); + CHECK_HEX_CONST(1fffff); + CHECK_OCT_CONST(010000000); + CHECK_HEX_CONST(200000); + CHECK_OCT_CONST(017777777); + CHECK_HEX_CONST(3fffff); + CHECK_OCT_CONST(020000000); + CHECK_HEX_CONST(400000); + CHECK_OCT_CONST(037777777); + CHECK_HEX_CONST(7fffff); + CHECK_OCT_CONST(040000000); + CHECK_HEX_CONST(800000); + CHECK_OCT_CONST(077777777); + CHECK_HEX_CONST(ffffff); + CHECK_OCT_CONST(0100000000); + CHECK_HEX_CONST(1000000); + CHECK_OCT_CONST(0177777777); + CHECK_HEX_CONST(1ffffff); + CHECK_OCT_CONST(0200000000); + CHECK_HEX_CONST(2000000); + CHECK_OCT_CONST(0377777777); + CHECK_HEX_CONST(3ffffff); + CHECK_OCT_CONST(0400000000); + CHECK_HEX_CONST(4000000); + CHECK_OCT_CONST(0777777777); + CHECK_HEX_CONST(7ffffff); + CHECK_OCT_CONST(01000000000); + CHECK_HEX_CONST(8000000); + CHECK_OCT_CONST(01777777777); + CHECK_HEX_CONST(fffffff); + CHECK_OCT_CONST(02000000000); + CHECK_HEX_CONST(10000000); + CHECK_OCT_CONST(03777777777); + CHECK_HEX_CONST(1fffffff); + CHECK_OCT_CONST(04000000000); + CHECK_HEX_CONST(20000000); + CHECK_OCT_CONST(07777777777); + CHECK_HEX_CONST(3fffffff); + CHECK_OCT_CONST(010000000000); + CHECK_HEX_CONST(40000000); + CHECK_OCT_CONST(017777777777); + CHECK_HEX_CONST(7fffffff); + CHECK_OCT_CONST(020000000000); + CHECK_HEX_CONST(80000000); + CHECK_OCT_CONST(037777777777); + CHECK_HEX_CONST(ffffffff); + CHECK_OCT_CONST(040000000000); + CHECK_HEX_CONST(100000000); + CHECK_OCT_CONST(077777777777); + CHECK_HEX_CONST(1ffffffff); + CHECK_OCT_CONST(0100000000000); + CHECK_HEX_CONST(200000000); + CHECK_OCT_CONST(0177777777777); + CHECK_HEX_CONST(3ffffffff); + CHECK_OCT_CONST(0200000000000); + CHECK_HEX_CONST(400000000); + CHECK_OCT_CONST(0377777777777); + CHECK_HEX_CONST(7ffffffff); + CHECK_OCT_CONST(0400000000000); + CHECK_HEX_CONST(800000000); + CHECK_OCT_CONST(0777777777777); + CHECK_HEX_CONST(fffffffff); + CHECK_OCT_CONST(01000000000000); + CHECK_HEX_CONST(1000000000); + CHECK_OCT_CONST(01777777777777); + CHECK_HEX_CONST(1fffffffff); + CHECK_OCT_CONST(02000000000000); + CHECK_HEX_CONST(2000000000); + CHECK_OCT_CONST(03777777777777); + CHECK_HEX_CONST(3fffffffff); + CHECK_OCT_CONST(04000000000000); + CHECK_HEX_CONST(4000000000); + CHECK_OCT_CONST(07777777777777); + CHECK_HEX_CONST(7fffffffff); + CHECK_OCT_CONST(010000000000000); + CHECK_HEX_CONST(8000000000); + CHECK_OCT_CONST(017777777777777); + CHECK_HEX_CONST(ffffffffff); + CHECK_OCT_CONST(020000000000000); + CHECK_HEX_CONST(10000000000); + CHECK_OCT_CONST(037777777777777); + CHECK_HEX_CONST(1ffffffffff); + CHECK_OCT_CONST(040000000000000); + CHECK_HEX_CONST(20000000000); + CHECK_OCT_CONST(077777777777777); + CHECK_HEX_CONST(3ffffffffff); + CHECK_OCT_CONST(0100000000000000); + CHECK_HEX_CONST(40000000000); + CHECK_OCT_CONST(0177777777777777); + CHECK_HEX_CONST(7ffffffffff); + CHECK_OCT_CONST(0200000000000000); + CHECK_HEX_CONST(80000000000); + CHECK_OCT_CONST(0377777777777777); + CHECK_HEX_CONST(fffffffffff); + CHECK_OCT_CONST(0400000000000000); + CHECK_HEX_CONST(100000000000); + CHECK_OCT_CONST(0777777777777777); + CHECK_HEX_CONST(1fffffffffff); + CHECK_OCT_CONST(01000000000000000); + CHECK_HEX_CONST(200000000000); + CHECK_OCT_CONST(01777777777777777); + CHECK_HEX_CONST(3fffffffffff); + CHECK_OCT_CONST(02000000000000000); + CHECK_HEX_CONST(400000000000); + CHECK_OCT_CONST(03777777777777777); + CHECK_HEX_CONST(7fffffffffff); + CHECK_OCT_CONST(04000000000000000); + CHECK_HEX_CONST(800000000000); + CHECK_OCT_CONST(07777777777777777); + CHECK_HEX_CONST(ffffffffffff); + CHECK_OCT_CONST(010000000000000000); + CHECK_HEX_CONST(1000000000000); + CHECK_OCT_CONST(017777777777777777); + CHECK_HEX_CONST(1ffffffffffff); + CHECK_OCT_CONST(020000000000000000); + CHECK_HEX_CONST(2000000000000); + CHECK_OCT_CONST(037777777777777777); + CHECK_HEX_CONST(3ffffffffffff); + CHECK_OCT_CONST(040000000000000000); + CHECK_HEX_CONST(4000000000000); + CHECK_OCT_CONST(077777777777777777); + CHECK_HEX_CONST(7ffffffffffff); + CHECK_OCT_CONST(0100000000000000000); + CHECK_HEX_CONST(8000000000000); + CHECK_OCT_CONST(0177777777777777777); + CHECK_HEX_CONST(fffffffffffff); + CHECK_OCT_CONST(0200000000000000000); + CHECK_HEX_CONST(10000000000000); + CHECK_OCT_CONST(0377777777777777777); + CHECK_HEX_CONST(1fffffffffffff); + CHECK_OCT_CONST(0400000000000000000); + CHECK_HEX_CONST(20000000000000); + CHECK_OCT_CONST(0777777777777777777); + CHECK_HEX_CONST(3fffffffffffff); + CHECK_OCT_CONST(01000000000000000000); + CHECK_HEX_CONST(40000000000000); + CHECK_OCT_CONST(01777777777777777777); + CHECK_HEX_CONST(7fffffffffffff); + CHECK_OCT_CONST(02000000000000000000); + CHECK_HEX_CONST(80000000000000); + CHECK_OCT_CONST(03777777777777777777); + CHECK_HEX_CONST(ffffffffffffff); + CHECK_OCT_CONST(04000000000000000000); + CHECK_HEX_CONST(100000000000000); + CHECK_OCT_CONST(07777777777777777777); + CHECK_HEX_CONST(1ffffffffffffff); + CHECK_OCT_CONST(010000000000000000000); + CHECK_HEX_CONST(200000000000000); + CHECK_OCT_CONST(017777777777777777777); + CHECK_HEX_CONST(3ffffffffffffff); + CHECK_OCT_CONST(020000000000000000000); + CHECK_HEX_CONST(400000000000000); + CHECK_OCT_CONST(037777777777777777777); + CHECK_HEX_CONST(7ffffffffffffff); + CHECK_OCT_CONST(040000000000000000000); + CHECK_HEX_CONST(800000000000000); + CHECK_OCT_CONST(077777777777777777777); + CHECK_HEX_CONST(fffffffffffffff); + CHECK_OCT_CONST(0100000000000000000000); + CHECK_HEX_CONST(1000000000000000); + CHECK_OCT_CONST(0177777777777777777777); + CHECK_HEX_CONST(1fffffffffffffff); + CHECK_OCT_CONST(0200000000000000000000); + CHECK_HEX_CONST(2000000000000000); + CHECK_OCT_CONST(0377777777777777777777); + CHECK_HEX_CONST(3fffffffffffffff); + CHECK_OCT_CONST(0400000000000000000000); + CHECK_HEX_CONST(4000000000000000); + CHECK_OCT_CONST(0777777777777777777777); + CHECK_HEX_CONST(7fffffffffffffff); + CHECK_OCT_CONST(01000000000000000000000); + CHECK_HEX_CONST(8000000000000000); + CHECK_OCT_CONST(01777777777777777777777); + CHECK_HEX_CONST(ffffffffffffffff); +#if LLONG_AT_LEAST(65) + CHECK_OCT_CONST(02000000000000000000000); + CHECK_HEX_CONST(10000000000000000); + CHECK_OCT_CONST(03777777777777777777777); + CHECK_HEX_CONST(1ffffffffffffffff); +#endif +#if LLONG_AT_LEAST(66) + CHECK_OCT_CONST(04000000000000000000000); + CHECK_HEX_CONST(20000000000000000); + CHECK_OCT_CONST(07777777777777777777777); + CHECK_HEX_CONST(3ffffffffffffffff); +#endif +#if LLONG_AT_LEAST(67) + CHECK_OCT_CONST(010000000000000000000000); + CHECK_HEX_CONST(40000000000000000); + CHECK_OCT_CONST(017777777777777777777777); + CHECK_HEX_CONST(7ffffffffffffffff); +#endif +#if LLONG_AT_LEAST(68) + CHECK_OCT_CONST(020000000000000000000000); + CHECK_HEX_CONST(80000000000000000); + CHECK_OCT_CONST(037777777777777777777777); + CHECK_HEX_CONST(fffffffffffffffff); +#endif +#if LLONG_AT_LEAST(69) + CHECK_OCT_CONST(040000000000000000000000); + CHECK_HEX_CONST(100000000000000000); + CHECK_OCT_CONST(077777777777777777777777); + CHECK_HEX_CONST(1fffffffffffffffff); +#endif +#if LLONG_AT_LEAST(70) + CHECK_OCT_CONST(0100000000000000000000000); + CHECK_HEX_CONST(200000000000000000); + CHECK_OCT_CONST(0177777777777777777777777); + CHECK_HEX_CONST(3fffffffffffffffff); +#endif +#if LLONG_AT_LEAST(71) + CHECK_OCT_CONST(0200000000000000000000000); + CHECK_HEX_CONST(400000000000000000); + CHECK_OCT_CONST(0377777777777777777777777); + CHECK_HEX_CONST(7fffffffffffffffff); +#endif +#if LLONG_AT_LEAST(72) + CHECK_OCT_CONST(0400000000000000000000000); + CHECK_HEX_CONST(800000000000000000); + CHECK_OCT_CONST(0777777777777777777777777); + CHECK_HEX_CONST(ffffffffffffffffff); +#endif +} diff --git a/cpp/llvm/tools/clang/INPUTS/carbon_h.c b/cpp/llvm/tools/clang/INPUTS/carbon_h.c new file mode 100644 index 00000000..599f123a --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/carbon_h.c @@ -0,0 +1,4 @@ + +#include + +//#import diff --git a/cpp/llvm/tools/clang/INPUTS/cfg-big-switch.c b/cpp/llvm/tools/clang/INPUTS/cfg-big-switch.c new file mode 100644 index 00000000..a48b51a2 --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/cfg-big-switch.c @@ -0,0 +1,27 @@ +#define EXPAND_2_CASES(i, x, y) CASE(i, x, y); CASE(i + 1, x, y); +#define EXPAND_4_CASES(i, x, y) EXPAND_2_CASES(i, x, y) EXPAND_2_CASES(i + 2, x, y) +#define EXPAND_8_CASES(i, x, y) EXPAND_4_CASES(i, x, y) EXPAND_4_CASES(i + 4, x, y) +#define EXPAND_16_CASES(i, x, y) EXPAND_8_CASES(i, x, y) EXPAND_8_CASES(i + 8, x, y) +#define EXPAND_32_CASES(i, x, y) EXPAND_16_CASES(i, x, y) EXPAND_16_CASES(i + 16, x, y) +#define EXPAND_64_CASES(i, x, y) EXPAND_32_CASES(i, x, y) EXPAND_32_CASES(i + 32, x, y) +#define EXPAND_128_CASES(i, x, y) EXPAND_64_CASES(i, x, y) EXPAND_64_CASES(i + 64, x, y) +#define EXPAND_256_CASES(i, x, y) EXPAND_128_CASES(i, x, y) EXPAND_128_CASES(i + 128, x, y) +#define EXPAND_512_CASES(i, x, y) EXPAND_256_CASES(i, x, y) EXPAND_256_CASES(i + 256, x, y) +#define EXPAND_1024_CASES(i, x, y) EXPAND_512_CASES(i, x, y) EXPAND_512_CASES(i + 512, x, y) +#define EXPAND_2048_CASES(i, x, y) EXPAND_1024_CASES(i, x, y) EXPAND_1024_CASES(i + 1024, x, y) +#define EXPAND_4096_CASES(i, x, y) EXPAND_2048_CASES(i, x, y) EXPAND_2048_CASES(i + 2048, x, y) + +// This has a *monstrous* single fan-out in the CFG, across 8000 blocks inside +// the while loop. +unsigned cfg_big_switch(int x) { + unsigned y = 0; + while (x > 0) { + switch(x) { +#define CASE(i, x, y) \ + case i: { int case_var = 3*x + i; y += case_var - 1; break; } +EXPAND_4096_CASES(0, x, y); + } + --x; + } + return y; +} diff --git a/cpp/llvm/tools/clang/INPUTS/cfg-long-chain1.c b/cpp/llvm/tools/clang/INPUTS/cfg-long-chain1.c new file mode 100644 index 00000000..2f55b2ad --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/cfg-long-chain1.c @@ -0,0 +1,20 @@ +#define EXPAND_2_BRANCHES(i, x, y) BRANCH(i, x, y); BRANCH(i + 1, x, y); +#define EXPAND_4_BRANCHES(i, x, y) EXPAND_2_BRANCHES(i, x, y) EXPAND_2_BRANCHES(i + 2, x, y) +#define EXPAND_8_BRANCHES(i, x, y) EXPAND_4_BRANCHES(i, x, y) EXPAND_4_BRANCHES(i + 4, x, y) +#define EXPAND_16_BRANCHES(i, x, y) EXPAND_8_BRANCHES(i, x, y) EXPAND_8_BRANCHES(i + 8, x, y) +#define EXPAND_32_BRANCHES(i, x, y) EXPAND_16_BRANCHES(i, x, y) EXPAND_16_BRANCHES(i + 16, x, y) +#define EXPAND_64_BRANCHES(i, x, y) EXPAND_32_BRANCHES(i, x, y) EXPAND_32_BRANCHES(i + 32, x, y) +#define EXPAND_128_BRANCHES(i, x, y) EXPAND_64_BRANCHES(i, x, y) EXPAND_64_BRANCHES(i + 64, x, y) +#define EXPAND_256_BRANCHES(i, x, y) EXPAND_128_BRANCHES(i, x, y) EXPAND_128_BRANCHES(i + 128, x, y) +#define EXPAND_512_BRANCHES(i, x, y) EXPAND_256_BRANCHES(i, x, y) EXPAND_256_BRANCHES(i + 256, x, y) +#define EXPAND_1024_BRANCHES(i, x, y) EXPAND_512_BRANCHES(i, x, y) EXPAND_512_BRANCHES(i + 512, x, y) +#define EXPAND_2048_BRANCHES(i, x, y) EXPAND_1024_BRANCHES(i, x, y) EXPAND_1024_BRANCHES(i + 1024, x, y) +#define EXPAND_4096_BRANCHES(i, x, y) EXPAND_2048_BRANCHES(i, x, y) EXPAND_2048_BRANCHES(i + 2048, x, y) + +unsigned cfg_long_chain_single_exit(unsigned x) { + unsigned y = 0; +#define BRANCH(i, x, y) if ((x % 13171) < i) { int var = x / 13171; y ^= var; } + EXPAND_4096_BRANCHES(1, x, y); +#undef BRANCH + return y; +} diff --git a/cpp/llvm/tools/clang/INPUTS/cfg-long-chain2.c b/cpp/llvm/tools/clang/INPUTS/cfg-long-chain2.c new file mode 100644 index 00000000..150a084e --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/cfg-long-chain2.c @@ -0,0 +1,20 @@ +#define EXPAND_2_BRANCHES(i, x, y) BRANCH(i, x, y); BRANCH(i + 1, x, y); +#define EXPAND_4_BRANCHES(i, x, y) EXPAND_2_BRANCHES(i, x, y) EXPAND_2_BRANCHES(i + 2, x, y) +#define EXPAND_8_BRANCHES(i, x, y) EXPAND_4_BRANCHES(i, x, y) EXPAND_4_BRANCHES(i + 4, x, y) +#define EXPAND_16_BRANCHES(i, x, y) EXPAND_8_BRANCHES(i, x, y) EXPAND_8_BRANCHES(i + 8, x, y) +#define EXPAND_32_BRANCHES(i, x, y) EXPAND_16_BRANCHES(i, x, y) EXPAND_16_BRANCHES(i + 16, x, y) +#define EXPAND_64_BRANCHES(i, x, y) EXPAND_32_BRANCHES(i, x, y) EXPAND_32_BRANCHES(i + 32, x, y) +#define EXPAND_128_BRANCHES(i, x, y) EXPAND_64_BRANCHES(i, x, y) EXPAND_64_BRANCHES(i + 64, x, y) +#define EXPAND_256_BRANCHES(i, x, y) EXPAND_128_BRANCHES(i, x, y) EXPAND_128_BRANCHES(i + 128, x, y) +#define EXPAND_512_BRANCHES(i, x, y) EXPAND_256_BRANCHES(i, x, y) EXPAND_256_BRANCHES(i + 256, x, y) +#define EXPAND_1024_BRANCHES(i, x, y) EXPAND_512_BRANCHES(i, x, y) EXPAND_512_BRANCHES(i + 512, x, y) +#define EXPAND_2048_BRANCHES(i, x, y) EXPAND_1024_BRANCHES(i, x, y) EXPAND_1024_BRANCHES(i + 1024, x, y) +#define EXPAND_4096_BRANCHES(i, x, y) EXPAND_2048_BRANCHES(i, x, y) EXPAND_2048_BRANCHES(i + 2048, x, y) + +unsigned cfg_long_chain_multiple_exit(unsigned x) { + unsigned y = 0; +#define BRANCH(i, x, y) if (((x % 13171) + ++y) < i) { int var = x / 13171 + y; return var; } + EXPAND_4096_BRANCHES(1, x, y); +#undef BRANCH + return 42; +} diff --git a/cpp/llvm/tools/clang/INPUTS/cfg-long-chain3.c b/cpp/llvm/tools/clang/INPUTS/cfg-long-chain3.c new file mode 100644 index 00000000..cca4bdcf --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/cfg-long-chain3.c @@ -0,0 +1,21 @@ +#define EXPAND_2_BRANCHES(i, x, y) BRANCH(i, x, y); BRANCH(i + 1, x, y); +#define EXPAND_4_BRANCHES(i, x, y) EXPAND_2_BRANCHES(i, x, y) EXPAND_2_BRANCHES(i + 2, x, y) +#define EXPAND_8_BRANCHES(i, x, y) EXPAND_4_BRANCHES(i, x, y) EXPAND_4_BRANCHES(i + 4, x, y) +#define EXPAND_16_BRANCHES(i, x, y) EXPAND_8_BRANCHES(i, x, y) EXPAND_8_BRANCHES(i + 8, x, y) +#define EXPAND_32_BRANCHES(i, x, y) EXPAND_16_BRANCHES(i, x, y) EXPAND_16_BRANCHES(i + 16, x, y) +#define EXPAND_64_BRANCHES(i, x, y) EXPAND_32_BRANCHES(i, x, y) EXPAND_32_BRANCHES(i + 32, x, y) +#define EXPAND_128_BRANCHES(i, x, y) EXPAND_64_BRANCHES(i, x, y) EXPAND_64_BRANCHES(i + 64, x, y) +#define EXPAND_256_BRANCHES(i, x, y) EXPAND_128_BRANCHES(i, x, y) EXPAND_128_BRANCHES(i + 128, x, y) +#define EXPAND_512_BRANCHES(i, x, y) EXPAND_256_BRANCHES(i, x, y) EXPAND_256_BRANCHES(i + 256, x, y) +#define EXPAND_1024_BRANCHES(i, x, y) EXPAND_512_BRANCHES(i, x, y) EXPAND_512_BRANCHES(i + 512, x, y) +#define EXPAND_2048_BRANCHES(i, x, y) EXPAND_1024_BRANCHES(i, x, y) EXPAND_1024_BRANCHES(i + 1024, x, y) +#define EXPAND_4096_BRANCHES(i, x, y) EXPAND_2048_BRANCHES(i, x, y) EXPAND_2048_BRANCHES(i + 2048, x, y) + +unsigned cfg_long_chain_many_preds(unsigned x) { + unsigned y = 0; +#define BRANCH(i, x, y) if ((x % 13171) < i) { int var = x / 13171; y ^= var; } else + EXPAND_4096_BRANCHES(1, x, y); +#undef BRANCH + int var = x / 13171; y^= var; + return y; +} diff --git a/cpp/llvm/tools/clang/INPUTS/cfg-nested-switches.c b/cpp/llvm/tools/clang/INPUTS/cfg-nested-switches.c new file mode 100644 index 00000000..3db10b44 --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/cfg-nested-switches.c @@ -0,0 +1,36 @@ +#define EXPAND_2_INNER_CASES(i, x, y) INNER_CASE(i, x, y); INNER_CASE(i + 1, x, y); +#define EXPAND_4_INNER_CASES(i, x, y) EXPAND_2_INNER_CASES(i, x, y) EXPAND_2_INNER_CASES(i + 2, x, y) +#define EXPAND_8_INNER_CASES(i, x, y) EXPAND_4_INNER_CASES(i, x, y) EXPAND_4_INNER_CASES(i + 4, x, y) +#define EXPAND_16_INNER_CASES(i, x, y) EXPAND_8_INNER_CASES(i, x, y) EXPAND_8_INNER_CASES(i + 8, x, y) +#define EXPAND_32_INNER_CASES(i, x, y) EXPAND_16_INNER_CASES(i, x, y) EXPAND_16_INNER_CASES(i + 16, x, y) +#define EXPAND_64_INNER_CASES(i, x, y) EXPAND_32_INNER_CASES(i, x, y) EXPAND_32_INNER_CASES(i + 32, x, y) + +#define EXPAND_2_OUTER_CASES(i, x, y) OUTER_CASE(i, x, y); OUTER_CASE(i + 1, x, y); +#define EXPAND_4_OUTER_CASES(i, x, y) EXPAND_2_OUTER_CASES(i, x, y) EXPAND_2_OUTER_CASES(i + 2, x, y) +#define EXPAND_8_OUTER_CASES(i, x, y) EXPAND_4_OUTER_CASES(i, x, y) EXPAND_4_OUTER_CASES(i + 4, x, y) +#define EXPAND_16_OUTER_CASES(i, x, y) EXPAND_8_OUTER_CASES(i, x, y) EXPAND_8_OUTER_CASES(i + 8, x, y) +#define EXPAND_32_OUTER_CASES(i, x, y) EXPAND_16_OUTER_CASES(i, x, y) EXPAND_16_OUTER_CASES(i + 16, x, y) +#define EXPAND_64_OUTER_CASES(i, x, y) EXPAND_32_OUTER_CASES(i, x, y) EXPAND_32_OUTER_CASES(i + 32, x, y) + +// Rather than a single monstrous fan-out, this fans out in smaller increments, +// but to a similar size. +unsigned cfg_nested_switch(int x) { + unsigned y = 0; + while (x > 0) { + switch (x) { +#define INNER_CASE(i, x, y) \ + case i: { int case_var = 3*x + i; y += case_var - 1; break; } +#define OUTER_CASE(i, x, y) \ + case i: { \ + int case_var = y >> 8; \ + switch (case_var) { \ + EXPAND_64_INNER_CASES(0, x, y); \ + } \ + break; \ + } +EXPAND_64_OUTER_CASES(0, x, y); + } + --x; + } + return y; +} diff --git a/cpp/llvm/tools/clang/INPUTS/cfg-nested-var-scopes.cpp b/cpp/llvm/tools/clang/INPUTS/cfg-nested-var-scopes.cpp new file mode 100644 index 00000000..0944ec26 --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/cfg-nested-var-scopes.cpp @@ -0,0 +1,59 @@ +// Hammer the CFG with large numbers of overlapping variable scopes, which +// implicit destructors triggered at each edge. + +#define EXPAND_BASIC_STRUCT(i) struct X##i { X##i(int); ~X##i(); }; +#define EXPAND_NORET_STRUCT(i) struct X##i { X##i(int); ~X##i() __attribute__((noreturn)); }; +EXPAND_BASIC_STRUCT(0000); EXPAND_NORET_STRUCT(0001); +EXPAND_BASIC_STRUCT(0010); EXPAND_BASIC_STRUCT(0011); +EXPAND_BASIC_STRUCT(0100); EXPAND_NORET_STRUCT(0101); +EXPAND_NORET_STRUCT(0110); EXPAND_BASIC_STRUCT(0111); +EXPAND_BASIC_STRUCT(1000); EXPAND_NORET_STRUCT(1001); +EXPAND_BASIC_STRUCT(1010); EXPAND_BASIC_STRUCT(1011); +EXPAND_NORET_STRUCT(1100); EXPAND_NORET_STRUCT(1101); +EXPAND_BASIC_STRUCT(1110); EXPAND_BASIC_STRUCT(1111); + +#define EXPAND_2_VARS(c, i, x) const X##i var_##c##_##i##0(x), &var_##c##_##i##1 = X##i(x) +#define EXPAND_4_VARS(c, i, x) EXPAND_2_VARS(c, i##0, x); EXPAND_2_VARS(c, i##1, x) +#define EXPAND_8_VARS(c, i, x) EXPAND_4_VARS(c, i##0, x); EXPAND_4_VARS(c, i##1, x) +#define EXPAND_16_VARS(c, i, x) EXPAND_8_VARS(c, i##0, x); EXPAND_8_VARS(c, i##1, x) +#define EXPAND_32_VARS(c, x) EXPAND_16_VARS(c, 0, x); EXPAND_16_VARS(c, 1, x) + +#define EXPAND_2_INNER_CASES(i, x, y) INNER_CASE(i, x, y); INNER_CASE(i + 1, x, y); +#define EXPAND_4_INNER_CASES(i, x, y) EXPAND_2_INNER_CASES(i, x, y) EXPAND_2_INNER_CASES(i + 2, x, y) +#define EXPAND_8_INNER_CASES(i, x, y) EXPAND_4_INNER_CASES(i, x, y) EXPAND_4_INNER_CASES(i + 4, x, y) +#define EXPAND_16_INNER_CASES(i, x, y) EXPAND_8_INNER_CASES(i, x, y) EXPAND_8_INNER_CASES(i + 8, x, y) +#define EXPAND_32_INNER_CASES(i, x, y) EXPAND_16_INNER_CASES(i, x, y) EXPAND_16_INNER_CASES(i + 16, x, y) + +#define EXPAND_2_OUTER_CASES(i, x, y) OUTER_CASE(i, x, y); OUTER_CASE(i + 1, x, y); +#define EXPAND_4_OUTER_CASES(i, x, y) EXPAND_2_OUTER_CASES(i, x, y) EXPAND_2_OUTER_CASES(i + 2, x, y) +#define EXPAND_8_OUTER_CASES(i, x, y) EXPAND_4_OUTER_CASES(i, x, y) EXPAND_4_OUTER_CASES(i + 4, x, y) +#define EXPAND_16_OUTER_CASES(i, x, y) EXPAND_8_OUTER_CASES(i, x, y) EXPAND_8_OUTER_CASES(i + 8, x, y) +#define EXPAND_32_OUTER_CASES(i, x, y) EXPAND_16_OUTER_CASES(i, x, y) EXPAND_16_OUTER_CASES(i + 16, x, y) + +unsigned cfg_nested_vars(int x) { + int y = 0; + while (x > 0) { + EXPAND_32_VARS(a, x); + switch (x) { +#define INNER_CASE(i, x, y) \ + case i: { \ + int case_var = 3*x + i; \ + EXPAND_32_VARS(c, case_var); \ + y += case_var - 1; \ + break; \ + } +#define OUTER_CASE(i, x, y) \ + case i: { \ + int case_var = y >> 8; \ + EXPAND_32_VARS(b, y); \ + switch (case_var) { \ + EXPAND_32_INNER_CASES(0, x, y); \ + } \ + break; \ + } +EXPAND_32_OUTER_CASES(0, x, y); + } + --x; + } + return y; +} diff --git a/cpp/llvm/tools/clang/INPUTS/iostream.cc b/cpp/llvm/tools/clang/INPUTS/iostream.cc new file mode 100644 index 00000000..eb12fc9a --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/iostream.cc @@ -0,0 +1,5 @@ +// clang -I/usr/include/c++/4.0.0 -I/usr/include/c++/4.0.0/powerpc-apple-darwin8 -I/usr/include/c++/4.0.0/backward INPUTS/iostream.cc -Eonly + +#include + +#include diff --git a/cpp/llvm/tools/clang/INPUTS/macro_pounder_fn.c b/cpp/llvm/tools/clang/INPUTS/macro_pounder_fn.c new file mode 100644 index 00000000..73f40a1d --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/macro_pounder_fn.c @@ -0,0 +1,17 @@ + +// This pounds on macro expansion for performance reasons. This is currently +// heavily constrained by darwin's malloc. + +// Function-like macros. +#define A0(A, B) A B +#define A1(A, B) A0(A,B) A0(A,B) A0(A,B) A0(A,B) A0(A,B) A0(A,B) +#define A2(A, B) A1(A,B) A1(A,B) A1(A,B) A1(A,B) A1(A,B) A1(A,B) +#define A3(A, B) A2(A,B) A2(A,B) A2(A,B) A2(A,B) A2(A,B) A2(A,B) +#define A4(A, B) A3(A,B) A3(A,B) A3(A,B) A3(A,B) A3(A,B) A3(A,B) +#define A5(A, B) A4(A,B) A4(A,B) A4(A,B) A4(A,B) A4(A,B) A4(A,B) +#define A6(A, B) A5(A,B) A5(A,B) A5(A,B) A5(A,B) A5(A,B) A5(A,B) +#define A7(A, B) A6(A,B) A6(A,B) A6(A,B) A6(A,B) A6(A,B) A6(A,B) +#define A8(A, B) A7(A,B) A7(A,B) A7(A,B) A7(A,B) A7(A,B) A7(A,B) + +A8(a, b) + diff --git a/cpp/llvm/tools/clang/INPUTS/macro_pounder_obj.c b/cpp/llvm/tools/clang/INPUTS/macro_pounder_obj.c new file mode 100644 index 00000000..d2465f34 --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/macro_pounder_obj.c @@ -0,0 +1,16 @@ + +// This pounds on macro expansion for performance reasons. This is currently +// heavily constrained by darwin's malloc. + +// Object-like expansions +#define A0 a b +#define A1 A0 A0 A0 A0 A0 A0 +#define A2 A1 A1 A1 A1 A1 A1 +#define A3 A2 A2 A2 A2 A2 A2 +#define A4 A3 A3 A3 A3 A3 A3 +#define A5 A4 A4 A4 A4 A4 A4 +#define A6 A5 A5 A5 A5 A5 A5 +#define A7 A6 A6 A6 A6 A6 A6 +#define A8 A7 A7 A7 A7 A7 A7 + +A8 diff --git a/cpp/llvm/tools/clang/INPUTS/stpcpy-test.c b/cpp/llvm/tools/clang/INPUTS/stpcpy-test.c new file mode 100644 index 00000000..b96a8066 --- /dev/null +++ b/cpp/llvm/tools/clang/INPUTS/stpcpy-test.c @@ -0,0 +1,47 @@ +#define __extension__ + +#define __stpcpy(dest, src) (__extension__ (__builtin_constant_p (src) ? (__string2_1bptr_p (src) && strlen (src) + 1 <= 8 ? __stpcpy_small (dest, __stpcpy_args (src), strlen (src) + 1) : ((char *) __mempcpy (dest, src, strlen (src) + 1) - 1)) : __stpcpy (dest, src))) +#define stpcpy(dest, src) __stpcpy (dest, src) +#define __stpcpy_args(src) __extension__ __STRING2_SMALL_GET16 (src, 0), __extension__ __STRING2_SMALL_GET16 (src, 4), __extension__ __STRING2_SMALL_GET32 (src, 0), __extension__ __STRING2_SMALL_GET32 (src, 4) + +#define __mempcpy(dest, src, n) (__extension__ (__builtin_constant_p (src) && __builtin_constant_p (n) && __string2_1bptr_p (src) && n <= 8 ? __mempcpy_small (dest, __mempcpy_args (src), n) : __mempcpy (dest, src, n))) +#define mempcpy(dest, src, n) __mempcpy (dest, src, n) +#define __mempcpy_args(src) ((char *) (src))[0], ((char *) (src))[2], ((char *) (src))[4], ((char *) (src))[6], __extension__ __STRING2_SMALL_GET16 (src, 0), __extension__ __STRING2_SMALL_GET16 (src, 4), __extension__ __STRING2_SMALL_GET32 (src, 0), __extension__ __STRING2_SMALL_GET32 (src, 4) + +#define __STRING2_SMALL_GET16(src, idx) (((__const unsigned char *) (__const char *) (src))[idx + 1] << 8 | ((__const unsigned char *) (__const char *) (src))[idx]) + +#define __STRING2_SMALL_GET32(src, idx) (((((__const unsigned char *) (__const char *) (src))[idx + 3] << 8 | ((__const unsigned char *) (__const char *) (src))[idx + 2]) << 8 | ((__const unsigned char *) (__const char *) (src))[idx + 1]) << 8 | ((__const unsigned char *) (__const char *) (src))[idx]) + +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) +stpcpy (stpcpy (stpcpy (stpcpy (a, b), c), d), e) diff --git a/cpp/llvm/tools/clang/INSTALL.txt b/cpp/llvm/tools/clang/INSTALL.txt new file mode 100644 index 00000000..e8e32096 --- /dev/null +++ b/cpp/llvm/tools/clang/INSTALL.txt @@ -0,0 +1,49 @@ +//===----------------------------------------------------------------------===// +// Clang Installation Instructions +//===----------------------------------------------------------------------===// + +These instructions describe how to build and install Clang. + +//===----------------------------------------------------------------------===// +// Step 1: Organization +//===----------------------------------------------------------------------===// + +Clang is designed to be built as part of an LLVM build. Assuming that the LLVM +source code is located at $LLVM_SRC_ROOT, then the clang source code should be +installed as: + + $LLVM_SRC_ROOT/tools/clang + +The directory is not required to be called clang, but doing so will allow the +LLVM build system to automatically recognize it and build it along with LLVM. + +//===----------------------------------------------------------------------===// +// Step 2: Configure and Build LLVM +//===----------------------------------------------------------------------===// + +Configure and build your copy of LLVM (see $LLVM_SRC_ROOT/GettingStarted.html +for more information). + +Assuming you installed clang at $LLVM_SRC_ROOT/tools/clang then Clang will +automatically be built with LLVM. Otherwise, run 'make' in the Clang source +directory to build Clang. + +//===----------------------------------------------------------------------===// +// Step 3: (Optional) Verify Your Build +//===----------------------------------------------------------------------===// + +It is a good idea to run the Clang tests to make sure your build works +correctly. From inside the Clang build directory, run 'make test' to run the +tests. + +//===----------------------------------------------------------------------===// +// Step 4: Install Clang +//===----------------------------------------------------------------------===// + +From inside the Clang build directory, run 'make install' to install the Clang +compiler and header files into the prefix directory selected when LLVM was +configured. + +The Clang compiler is available as 'clang' and supports a gcc like command line +interface. See the man page for clang (installed into $prefix/share/man/man1) +for more information. diff --git a/cpp/llvm/tools/clang/LICENSE.TXT b/cpp/llvm/tools/clang/LICENSE.TXT new file mode 100644 index 00000000..6c224f84 --- /dev/null +++ b/cpp/llvm/tools/clang/LICENSE.TXT @@ -0,0 +1,63 @@ +============================================================================== +LLVM Release License +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2007-2012 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== +The LLVM software contains code written by third parties. Such software will +have its own individual LICENSE.TXT file in the directory in which it appears. +This file will describe the copyrights, license, and restrictions which apply +to that code. + +The disclaimer of warranty in the University of Illinois Open Source License +applies to all code in the LLVM Distribution, and nothing in any of the +other licenses gives permission to use the names of the LLVM Team or the +University of Illinois to endorse or promote products derived from this +Software. + +The following pieces of software have additional or alternate copyrights, +licenses, and/or restrictions: + +Program Directory +------- --------- + + diff --git a/cpp/llvm/tools/clang/Makefile b/cpp/llvm/tools/clang/Makefile new file mode 100644 index 00000000..bf1a7721 --- /dev/null +++ b/cpp/llvm/tools/clang/Makefile @@ -0,0 +1,111 @@ +##===- Makefile --------------------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +# If CLANG_LEVEL is not set, then we are the top-level Makefile. Otherwise, we +# are being included from a subdirectory makefile. + +ifndef CLANG_LEVEL + +IS_TOP_LEVEL := 1 +CLANG_LEVEL := . +DIRS := utils/TableGen include lib tools runtime docs unittests + +PARALLEL_DIRS := + +ifeq ($(BUILD_EXAMPLES),1) + PARALLEL_DIRS += examples +endif +endif + +ifeq ($(MAKECMDGOALS),libs-only) + DIRS := $(filter-out tools docs, $(DIRS)) + OPTIONAL_DIRS := +endif + +### +# Common Makefile code, shared by all Clang Makefiles. + +# Set LLVM source root level. +LEVEL := $(CLANG_LEVEL)/../.. + +# Include LLVM common makefile. +include $(LEVEL)/Makefile.common + +ifneq ($(ENABLE_DOCS),1) + DIRS := $(filter-out docs, $(DIRS)) +endif + +# Set common Clang build flags. +CPP.Flags += -I$(PROJ_SRC_DIR)/$(CLANG_LEVEL)/include -I$(PROJ_OBJ_DIR)/$(CLANG_LEVEL)/include +ifdef CLANG_VENDOR +CPP.Flags += -DCLANG_VENDOR='"$(CLANG_VENDOR) "' +endif +ifdef CLANG_REPOSITORY_STRING +CPP.Flags += -DCLANG_REPOSITORY_STRING='"$(CLANG_REPOSITORY_STRING)"' +endif + +# Disable -fstrict-aliasing. Darwin disables it by default (and LLVM doesn't +# work with it enabled with GCC), Clang/llvm-gcc don't support it yet, and newer +# GCC's have false positive warnings with it on Linux (which prove a pain to +# fix). For example: +# http://gcc.gnu.org/PR41874 +# http://gcc.gnu.org/PR41838 +# +# We can revisit this when LLVM/Clang support it. +CXX.Flags += -fno-strict-aliasing + +# Set up Clang's tblgen. +ifndef CLANG_TBLGEN + ifeq ($(LLVM_CROSS_COMPILING),1) + CLANG_TBLGEN := $(BuildLLVMToolDir)/clang-tblgen$(BUILD_EXEEXT) + else + CLANG_TBLGEN := $(LLVMToolDir)/clang-tblgen$(EXEEXT) + endif +endif +ClangTableGen = $(CLANG_TBLGEN) $(TableGen.Flags) + +### +# Clang Top Level specific stuff. + +ifeq ($(IS_TOP_LEVEL),1) + +ifneq ($(PROJ_SRC_ROOT),$(PROJ_OBJ_ROOT)) +$(RecursiveTargets):: + $(Verb) for dir in test unittests; do \ + if [ -f $(PROJ_SRC_DIR)/$${dir}/Makefile ] && [ ! -f $${dir}/Makefile ]; then \ + $(MKDIR) $${dir}; \ + $(CP) $(PROJ_SRC_DIR)/$${dir}/Makefile $${dir}/Makefile; \ + fi \ + done +endif + +test:: + @ $(MAKE) -C test + +report:: + @ $(MAKE) -C test report + +clean:: + @ $(MAKE) -C test clean + +libs-only: all + +tags:: + $(Verb) etags `find . -type f -name '*.h' -or -name '*.cpp' | \ + grep -v /lib/Headers | grep -v /test/` + +cscope.files: + find tools lib include -name '*.cpp' \ + -or -name '*.def' \ + -or -name '*.td' \ + -or -name '*.h' > cscope.files + +.PHONY: test report clean cscope.files + +endif diff --git a/cpp/llvm/tools/clang/ModuleInfo.txt b/cpp/llvm/tools/clang/ModuleInfo.txt new file mode 100644 index 00000000..4368ef06 --- /dev/null +++ b/cpp/llvm/tools/clang/ModuleInfo.txt @@ -0,0 +1,5 @@ +# This file provides information for llvm-top +DepModule: llvm +ConfigCmd: +ConfigTest: +BuildCmd: diff --git a/cpp/llvm/tools/clang/NOTES.txt b/cpp/llvm/tools/clang/NOTES.txt new file mode 100644 index 00000000..ca46d1ca --- /dev/null +++ b/cpp/llvm/tools/clang/NOTES.txt @@ -0,0 +1,114 @@ +//===---------------------------------------------------------------------===// +// Random Notes +//===---------------------------------------------------------------------===// + +C90/C99/C++ Comparisons: +http://david.tribble.com/text/cdiffs.htm + +//===---------------------------------------------------------------------===// + +To time GCC preprocessing speed without output, use: + "time gcc -MM file" +This is similar to -Eonly. + +//===---------------------------------------------------------------------===// + +Creating and using a PTH file for performance measurement (use a release build). + +$ clang -ccc-pch-is-pth -x objective-c-header INPUTS/Cocoa_h.m -o /tmp/tokencache +$ clang -cc1 -token-cache /tmp/tokencache INPUTS/Cocoa_h.m + +//===---------------------------------------------------------------------===// + + C++ Template Instantiation benchmark: + http://users.rcn.com/abrahams/instantiation_speed/index.html + +//===---------------------------------------------------------------------===// + +TODO: File Manager Speedup: + + We currently do a lot of stat'ing for files that don't exist, particularly + when lots of -I paths exist (e.g. see the example, check for + failures in stat in FileManager::getFile). It would be far better to make + the following changes: + 1. FileEntry contains a sys::Path instead of a std::string for Name. + 2. sys::Path contains timestamp and size, lazily computed. Eliminate from + FileEntry. + 3. File UIDs are created on request, not when files are opened. + These changes make it possible to efficiently have FileEntry objects for + files that exist on the file system, but have not been used yet. + + Once this is done: + 1. DirectoryEntry gets a boolean value "has read entries". When false, not + all entries in the directory are in the file mgr, when true, they are. + 2. Instead of stat'ing the file in FileManager::getFile, check to see if + the dir has been read. If so, fail immediately, if not, read the dir, + then retry. + 3. Reading the dir uses the getdirentries syscall, creating an FileEntry + for all files found. + +//===---------------------------------------------------------------------===// +// Specifying targets: -triple and -arch +//===---------------------------------------------------------------------===// + +The clang supports "-triple" and "-arch" options. At most one -triple and one +-arch option may be specified. Both are optional. + +The "selection of target" behavior is defined as follows: + +(1) If the user does not specify -triple, we default to the host triple. +(2) If the user specifies a -arch, that overrides the arch in the host or + specified triple. + +//===---------------------------------------------------------------------===// + + +verifyInputConstraint and verifyOutputConstraint should not return bool. + +Instead we should return something like: + +enum VerifyConstraintResult { + Valid, + + // Output only + OutputOperandConstraintLacksEqualsCharacter, + MatchingConstraintNotValidInOutputOperand, + + // Input only + InputOperandConstraintContainsEqualsCharacter, + MatchingConstraintReferencesInvalidOperandNumber, + + // Both + PercentConstraintUsedWithLastOperand +}; + +//===---------------------------------------------------------------------===// + +Blocks should not capture variables that are only used in dead code. + +The rule that we came up with is that blocks are required to capture +variables if they're referenced in evaluated code, even if that code +doesn't actually rely on the value of the captured variable. + +For example, this requires a capture: + (void) var; +But this does not: + if (false) puts(var); + +Summary of : if we implement this, we should +warn about non-POD variables that are referenced but not captured, but +only if the non-reachability is not due to macro or template +metaprogramming. + +//===---------------------------------------------------------------------===// + +We can still apply a modified version of the constructor/destructor +delegation optimization in cases of virtual inheritance where: + - there is no function-try-block, + - the constructor signature is not variadic, and + - the parameter variables can safely be copied and repassed + to the base constructor because either + - they have not had their addresses taken by the vbase initializers or + - they were passed indirectly. + +//===---------------------------------------------------------------------===// diff --git a/cpp/llvm/tools/clang/README.txt b/cpp/llvm/tools/clang/README.txt new file mode 100644 index 00000000..44ce723a --- /dev/null +++ b/cpp/llvm/tools/clang/README.txt @@ -0,0 +1,26 @@ +//===----------------------------------------------------------------------===// +// C Language Family Front-end +//===----------------------------------------------------------------------===// + +Welcome to Clang. This is a compiler front-end for the C family of languages +(C, C++, Objective-C, and Objective-C++) which is built as part of the LLVM +compiler infrastructure project. + +Unlike many other compiler frontends, Clang is useful for a number of things +beyond just compiling code: we intend for Clang to be host to a number of +different source level tools. One example of this is the Clang Static Analyzer. + +If you're interested in more (including how to build Clang) it is best to read +the relevant web sites. Here are some pointers: + +Information on Clang: http://clang.llvm.org/ +Building and using Clang: http://clang.llvm.org/get_started.html +Clang Static Analyzer: http://clang-analyzer.llvm.org/ +Information on the LLVM project: http://llvm.org/ + +If you have questions or comments about Clang, a great place to discuss them is +on the Clang development mailing list: + http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev + +If you find a bug in Clang, please file it in the LLVM bug tracker: + http://llvm.org/bugs/ diff --git a/cpp/llvm/tools/clang/bindings/python/README.txt b/cpp/llvm/tools/clang/bindings/python/README.txt new file mode 100644 index 00000000..742cf8fb --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/README.txt @@ -0,0 +1,17 @@ +//===----------------------------------------------------------------------===// +// Clang Python Bindings +//===----------------------------------------------------------------------===// + +This directory implements Python bindings for Clang. + +You may need to alter LD_LIBRARY_PATH so that the Clang library can be +found. The unit tests are designed to be run with 'nosetests'. For example: +-- +$ env PYTHONPATH=$(echo ~/llvm/tools/clang/bindings/python/) \ + LD_LIBRARY_PATH=$(llvm-config --libdir) \ + nosetests -v +tests.cindex.test_index.test_create ... ok +... + +OK +-- diff --git a/cpp/llvm/tools/clang/bindings/python/clang/__init__.py b/cpp/llvm/tools/clang/bindings/python/clang/__init__.py new file mode 100644 index 00000000..88f30812 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/clang/__init__.py @@ -0,0 +1,24 @@ +#===- __init__.py - Clang Python Bindings --------------------*- python -*--===# +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +#===------------------------------------------------------------------------===# + +r""" +Clang Library Bindings +====================== + +This package provides access to the Clang compiler and libraries. + +The available modules are: + + cindex + + Bindings for the Clang indexing library. +""" + +__all__ = ['cindex'] + diff --git a/cpp/llvm/tools/clang/bindings/python/clang/cindex.py b/cpp/llvm/tools/clang/bindings/python/clang/cindex.py new file mode 100644 index 00000000..6f0d25f1 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/clang/cindex.py @@ -0,0 +1,2126 @@ +#===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===# +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +#===------------------------------------------------------------------------===# + +r""" +Clang Indexing Library Bindings +=============================== + +This module provides an interface to the Clang indexing library. It is a +low-level interface to the indexing library which attempts to match the Clang +API directly while also being "pythonic". Notable differences from the C API +are: + + * string results are returned as Python strings, not CXString objects. + + * null cursors are translated to None. + + * access to child cursors is done via iteration, not visitation. + +The major indexing objects are: + + Index + + The top-level object which manages some global library state. + + TranslationUnit + + High-level object encapsulating the AST for a single translation unit. These + can be loaded from .ast files or parsed on the fly. + + Cursor + + Generic object for representing a node in the AST. + + SourceRange, SourceLocation, and File + + Objects representing information about the input source. + +Most object information is exposed using properties, when the underlying API +call is efficient. +""" + +# TODO +# ==== +# +# o API support for invalid translation units. Currently we can't even get the +# diagnostics on failure because they refer to locations in an object that +# will have been invalidated. +# +# o fix memory management issues (currently client must hold on to index and +# translation unit, or risk crashes). +# +# o expose code completion APIs. +# +# o cleanup ctypes wrapping, would be nice to separate the ctypes details more +# clearly, and hide from the external interface (i.e., help(cindex)). +# +# o implement additional SourceLocation, SourceRange, and File methods. + +from ctypes import * +import collections + +def get_cindex_library(): + # FIXME: It's probably not the case that the library is actually found in + # this location. We need a better system of identifying and loading the + # CIndex library. It could be on path or elsewhere, or versioned, etc. + import platform + name = platform.system() + if name == 'Darwin': + return cdll.LoadLibrary('libclang.dylib') + elif name == 'Windows': + return cdll.LoadLibrary('libclang.dll') + else: + return cdll.LoadLibrary('libclang.so') + +# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper +# object. This is a problem, because it means that from_parameter will see an +# integer and pass the wrong value on platforms where int != void*. Work around +# this by marshalling object arguments as void**. +c_object_p = POINTER(c_void_p) + +lib = get_cindex_library() + +### Structures and Utility Classes ### + +class _CXString(Structure): + """Helper for transforming CXString results.""" + + _fields_ = [("spelling", c_char_p), ("free", c_int)] + + def __del__(self): + _CXString_dispose(self) + + @staticmethod + def from_result(res, fn, args): + assert isinstance(res, _CXString) + return _CXString_getCString(res) + +class SourceLocation(Structure): + """ + A SourceLocation represents a particular location within a source file. + """ + _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)] + _data = None + + def _get_instantiation(self): + if self._data is None: + f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() + SourceLocation_loc(self, byref(f), byref(l), byref(c), byref(o)) + if f: + f = File(f) + else: + f = None + self._data = (f, int(l.value), int(c.value), int(o.value)) + return self._data + + @staticmethod + def from_position(tu, file, line, column): + """ + Retrieve the source location associated with a given file/line/column in + a particular translation unit. + """ + return SourceLocation_getLocation(tu, file, line, column) + + @property + def file(self): + """Get the file represented by this source location.""" + return self._get_instantiation()[0] + + @property + def line(self): + """Get the line represented by this source location.""" + return self._get_instantiation()[1] + + @property + def column(self): + """Get the column represented by this source location.""" + return self._get_instantiation()[2] + + @property + def offset(self): + """Get the file offset represented by this source location.""" + return self._get_instantiation()[3] + + def __eq__(self, other): + return SourceLocation_equalLocations(self, other) + + def __ne__(self, other): + return not self.__eq__(other) + + def __repr__(self): + if self.file: + filename = self.file.name + else: + filename = None + return "" % ( + filename, self.line, self.column) + +class SourceRange(Structure): + """ + A SourceRange describes a range of source locations within the source + code. + """ + _fields_ = [ + ("ptr_data", c_void_p * 2), + ("begin_int_data", c_uint), + ("end_int_data", c_uint)] + + # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes + # object. + @staticmethod + def from_locations(start, end): + return SourceRange_getRange(start, end) + + @property + def start(self): + """ + Return a SourceLocation representing the first character within a + source range. + """ + return SourceRange_start(self) + + @property + def end(self): + """ + Return a SourceLocation representing the last character within a + source range. + """ + return SourceRange_end(self) + + def __eq__(self, other): + return SourceRange_equalRanges(self, other) + + def __ne__(self, other): + return not self.__eq__(other) + + def __repr__(self): + return "" % (self.start, self.end) + +class Diagnostic(object): + """ + A Diagnostic is a single instance of a Clang diagnostic. It includes the + diagnostic severity, the message, the location the diagnostic occurred, as + well as additional source ranges and associated fix-it hints. + """ + + Ignored = 0 + Note = 1 + Warning = 2 + Error = 3 + Fatal = 4 + + def __init__(self, ptr): + self.ptr = ptr + + def __del__(self): + _clang_disposeDiagnostic(self) + + @property + def severity(self): + return _clang_getDiagnosticSeverity(self) + + @property + def location(self): + return _clang_getDiagnosticLocation(self) + + @property + def spelling(self): + return _clang_getDiagnosticSpelling(self) + + @property + def ranges(self): + class RangeIterator: + def __init__(self, diag): + self.diag = diag + + def __len__(self): + return int(_clang_getDiagnosticNumRanges(self.diag)) + + def __getitem__(self, key): + if (key >= len(self)): + raise IndexError + return _clang_getDiagnosticRange(self.diag, key) + + return RangeIterator(self) + + @property + def fixits(self): + class FixItIterator: + def __init__(self, diag): + self.diag = diag + + def __len__(self): + return int(_clang_getDiagnosticNumFixIts(self.diag)) + + def __getitem__(self, key): + range = SourceRange() + value = _clang_getDiagnosticFixIt(self.diag, key, byref(range)) + if len(value) == 0: + raise IndexError + + return FixIt(range, value) + + return FixItIterator(self) + + @property + def category_number(self): + """The category number for this diagnostic.""" + return _clang_getDiagnosticCategory(self) + + @property + def category_name(self): + """The string name of the category for this diagnostic.""" + return _clang_getDiagnosticCategoryName(self.category_number) + + @property + def option(self): + """The command-line option that enables this diagnostic.""" + return _clang_getDiagnosticOption(self, None) + + @property + def disable_option(self): + """The command-line option that disables this diagnostic.""" + disable = _CXString() + _clang_getDiagnosticOption(self, byref(disable)) + + return _CXString_getCString(disable) + + def __repr__(self): + return "" % ( + self.severity, self.location, self.spelling) + + def from_param(self): + return self.ptr + +class FixIt(object): + """ + A FixIt represents a transformation to be applied to the source to + "fix-it". The fix-it shouldbe applied by replacing the given source range + with the given value. + """ + + def __init__(self, range, value): + self.range = range + self.value = value + + def __repr__(self): + return "" % (self.range, self.value) + +### Cursor Kinds ### + +class CursorKind(object): + """ + A CursorKind describes the kind of entity that a cursor points to. + """ + + # The unique kind objects, indexed by id. + _kinds = [] + _name_map = None + + def __init__(self, value): + if value >= len(CursorKind._kinds): + CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1) + if CursorKind._kinds[value] is not None: + raise ValueError,'CursorKind already loaded' + self.value = value + CursorKind._kinds[value] = self + CursorKind._name_map = None + + def from_param(self): + return self.value + + @property + def name(self): + """Get the enumeration name of this cursor kind.""" + if self._name_map is None: + self._name_map = {} + for key,value in CursorKind.__dict__.items(): + if isinstance(value,CursorKind): + self._name_map[value] = key + return self._name_map[self] + + @staticmethod + def from_id(id): + if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None: + raise ValueError,'Unknown cursor kind' + return CursorKind._kinds[id] + + @staticmethod + def get_all_kinds(): + """Return all CursorKind enumeration instances.""" + return filter(None, CursorKind._kinds) + + def is_declaration(self): + """Test if this is a declaration kind.""" + return CursorKind_is_decl(self) + + def is_reference(self): + """Test if this is a reference kind.""" + return CursorKind_is_ref(self) + + def is_expression(self): + """Test if this is an expression kind.""" + return CursorKind_is_expr(self) + + def is_statement(self): + """Test if this is a statement kind.""" + return CursorKind_is_stmt(self) + + def is_attribute(self): + """Test if this is an attribute kind.""" + return CursorKind_is_attribute(self) + + def is_invalid(self): + """Test if this is an invalid kind.""" + return CursorKind_is_inv(self) + + def is_translation_unit(self): + """Test if this is a translation unit kind.""" + return CursorKind_is_translation_unit(self) + + def is_preprocessing(self): + """Test if this is a preprocessing kind.""" + return CursorKind_is_preprocessing(self) + + def is_unexposed(self): + """Test if this is an unexposed kind.""" + return CursorKind_is_unexposed(self) + + def __repr__(self): + return 'CursorKind.%s' % (self.name,) + +# FIXME: Is there a nicer way to expose this enumeration? We could potentially +# represent the nested structure, or even build a class hierarchy. The main +# things we want for sure are (a) simple external access to kinds, (b) a place +# to hang a description and name, (c) easy to keep in sync with Index.h. + +### +# Declaration Kinds + +# A declaration whose specific kind is not exposed via this interface. +# +# Unexposed declarations have the same operations as any other kind of +# declaration; one can extract their location information, spelling, find their +# definitions, etc. However, the specific kind of the declaration is not +# reported. +CursorKind.UNEXPOSED_DECL = CursorKind(1) + +# A C or C++ struct. +CursorKind.STRUCT_DECL = CursorKind(2) + +# A C or C++ union. +CursorKind.UNION_DECL = CursorKind(3) + +# A C++ class. +CursorKind.CLASS_DECL = CursorKind(4) + +# An enumeration. +CursorKind.ENUM_DECL = CursorKind(5) + +# A field (in C) or non-static data member (in C++) in a struct, union, or C++ +# class. +CursorKind.FIELD_DECL = CursorKind(6) + +# An enumerator constant. +CursorKind.ENUM_CONSTANT_DECL = CursorKind(7) + +# A function. +CursorKind.FUNCTION_DECL = CursorKind(8) + +# A variable. +CursorKind.VAR_DECL = CursorKind(9) + +# A function or method parameter. +CursorKind.PARM_DECL = CursorKind(10) + +# An Objective-C @interface. +CursorKind.OBJC_INTERFACE_DECL = CursorKind(11) + +# An Objective-C @interface for a category. +CursorKind.OBJC_CATEGORY_DECL = CursorKind(12) + +# An Objective-C @protocol declaration. +CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13) + +# An Objective-C @property declaration. +CursorKind.OBJC_PROPERTY_DECL = CursorKind(14) + +# An Objective-C instance variable. +CursorKind.OBJC_IVAR_DECL = CursorKind(15) + +# An Objective-C instance method. +CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16) + +# An Objective-C class method. +CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17) + +# An Objective-C @implementation. +CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18) + +# An Objective-C @implementation for a category. +CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19) + +# A typedef. +CursorKind.TYPEDEF_DECL = CursorKind(20) + +# A C++ class method. +CursorKind.CXX_METHOD = CursorKind(21) + +# A C++ namespace. +CursorKind.NAMESPACE = CursorKind(22) + +# A linkage specification, e.g. 'extern "C"'. +CursorKind.LINKAGE_SPEC = CursorKind(23) + +# A C++ constructor. +CursorKind.CONSTRUCTOR = CursorKind(24) + +# A C++ destructor. +CursorKind.DESTRUCTOR = CursorKind(25) + +# A C++ conversion function. +CursorKind.CONVERSION_FUNCTION = CursorKind(26) + +# A C++ template type parameter +CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27) + +# A C++ non-type template paramater. +CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28) + +# A C++ template template parameter. +CursorKind.TEMPLATE_TEMPLATE_PARAMTER = CursorKind(29) + +# A C++ function template. +CursorKind.FUNCTION_TEMPLATE = CursorKind(30) + +# A C++ class template. +CursorKind.CLASS_TEMPLATE = CursorKind(31) + +# A C++ class template partial specialization. +CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32) + +# A C++ namespace alias declaration. +CursorKind.NAMESPACE_ALIAS = CursorKind(33) + +# A C++ using directive +CursorKind.USING_DIRECTIVE = CursorKind(34) + +# A C++ using declaration +CursorKind.USING_DECLARATION = CursorKind(35) + +# A Type alias decl. +CursorKind.TYPE_ALIAS_DECL = CursorKind(36) + +# A Objective-C synthesize decl +CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37) + +# A Objective-C dynamic decl +CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38) + +# A C++ access specifier decl. +CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39) + + +### +# Reference Kinds + +CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40) +CursorKind.OBJC_PROTOCOL_REF = CursorKind(41) +CursorKind.OBJC_CLASS_REF = CursorKind(42) + +# A reference to a type declaration. +# +# A type reference occurs anywhere where a type is named but not +# declared. For example, given: +# typedef unsigned size_type; +# size_type size; +# +# The typedef is a declaration of size_type (CXCursor_TypedefDecl), +# while the type of the variable "size" is referenced. The cursor +# referenced by the type of size is the typedef for size_type. +CursorKind.TYPE_REF = CursorKind(43) +CursorKind.CXX_BASE_SPECIFIER = CursorKind(44) + +# A reference to a class template, function template, template +# template parameter, or class template partial specialization. +CursorKind.TEMPLATE_REF = CursorKind(45) + +# A reference to a namespace or namepsace alias. +CursorKind.NAMESPACE_REF = CursorKind(46) + +# A reference to a member of a struct, union, or class that occurs in +# some non-expression context, e.g., a designated initializer. +CursorKind.MEMBER_REF = CursorKind(47) + +# A reference to a labeled statement. +CursorKind.LABEL_REF = CursorKind(48) + +# A reference toa a set of overloaded functions or function templates +# that has not yet been resolved to a specific function or function template. +CursorKind.OVERLOADED_DECL_REF = CursorKind(49) + +### +# Invalid/Error Kinds + +CursorKind.INVALID_FILE = CursorKind(70) +CursorKind.NO_DECL_FOUND = CursorKind(71) +CursorKind.NOT_IMPLEMENTED = CursorKind(72) +CursorKind.INVALID_CODE = CursorKind(73) + +### +# Expression Kinds + +# An expression whose specific kind is not exposed via this interface. +# +# Unexposed expressions have the same operations as any other kind of +# expression; one can extract their location information, spelling, children, +# etc. However, the specific kind of the expression is not reported. +CursorKind.UNEXPOSED_EXPR = CursorKind(100) + +# An expression that refers to some value declaration, such as a function, +# varible, or enumerator. +CursorKind.DECL_REF_EXPR = CursorKind(101) + +# An expression that refers to a member of a struct, union, class, Objective-C +# class, etc. +CursorKind.MEMBER_REF_EXPR = CursorKind(102) + +# An expression that calls a function. +CursorKind.CALL_EXPR = CursorKind(103) + +# An expression that sends a message to an Objective-C object or class. +CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104) + +# An expression that represents a block literal. +CursorKind.BLOCK_EXPR = CursorKind(105) + +# An integer literal. +CursorKind.INTEGER_LITERAL = CursorKind(106) + +# A floating point number literal. +CursorKind.FLOATING_LITERAL = CursorKind(107) + +# An imaginary number literal. +CursorKind.IMAGINARY_LITERAL = CursorKind(108) + +# A string literal. +CursorKind.STRING_LITERAL = CursorKind(109) + +# A character literal. +CursorKind.CHARACTER_LITERAL = CursorKind(110) + +# A parenthesized expression, e.g. "(1)". +# +# This AST node is only formed if full location information is requested. +CursorKind.PAREN_EXPR = CursorKind(111) + +# This represents the unary-expression's (except sizeof and +# alignof). +CursorKind.UNARY_OPERATOR = CursorKind(112) + +# [C99 6.5.2.1] Array Subscripting. +CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113) + +# A builtin binary operation expression such as "x + y" or +# "x <= y". +CursorKind.BINARY_OPERATOR = CursorKind(114) + +# Compound assignment such as "+=". +CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) + +# The ?: ternary operator. +CursorKind.CONDITONAL_OPERATOR = CursorKind(116) + +# An explicit cast in C (C99 6.5.4) or a C-style cast in C++ +# (C++ [expr.cast]), which uses the syntax (Type)expr. +# +# For example: (int)f. +CursorKind.CSTYLE_CAST_EXPR = CursorKind(117) + +# [C99 6.5.2.5] +CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118) + +# Describes an C or C++ initializer list. +CursorKind.INIT_LIST_EXPR = CursorKind(119) + +# The GNU address of label extension, representing &&label. +CursorKind.ADDR_LABEL_EXPR = CursorKind(120) + +# This is the GNU Statement Expression extension: ({int X=4; X;}) +CursorKind.StmtExpr = CursorKind(121) + +# Represents a C11 generic selection. +CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122) + +# Implements the GNU __null extension, which is a name for a null +# pointer constant that has integral type (e.g., int or long) and is the same +# size and alignment as a pointer. +# +# The __null extension is typically only used by system headers, which define +# NULL as __null in C++ rather than using 0 (which is an integer that may not +# match the size of a pointer). +CursorKind.GNU_NULL_EXPR = CursorKind(123) + +# C++'s static_cast<> expression. +CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124) + +# C++'s dynamic_cast<> expression. +CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125) + +# C++'s reinterpret_cast<> expression. +CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126) + +# C++'s const_cast<> expression. +CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127) + +# Represents an explicit C++ type conversion that uses "functional" +# notion (C++ [expr.type.conv]). +# +# Example: +# \code +# x = int(0.5); +# \endcode +CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128) + +# A C++ typeid expression (C++ [expr.typeid]). +CursorKind.CXX_TYPEID_EXPR = CursorKind(129) + +# [C++ 2.13.5] C++ Boolean Literal. +CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130) + +# [C++0x 2.14.7] C++ Pointer Literal. +CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131) + +# Represents the "this" expression in C++ +CursorKind.CXX_THIS_EXPR = CursorKind(132) + +# [C++ 15] C++ Throw Expression. +# +# This handles 'throw' and 'throw' assignment-expression. When +# assignment-expression isn't present, Op will be null. +CursorKind.CXX_THROW_EXPR = CursorKind(133) + +# A new expression for memory allocation and constructor calls, e.g: +# "new CXXNewExpr(foo)". +CursorKind.CXX_NEW_EXPR = CursorKind(134) + +# A delete expression for memory deallocation and destructor calls, +# e.g. "delete[] pArray". +CursorKind.CXX_DELETE_EXPR = CursorKind(135) + +# Represents a unary expression. +CursorKind.CXX_UNARY_EXPR = CursorKind(136) + +# ObjCStringLiteral, used for Objective-C string literals i.e. "foo". +CursorKind.OBJC_STRING_LITERAL = CursorKind(137) + +# ObjCEncodeExpr, used for in Objective-C. +CursorKind.OBJC_ENCODE_EXPR = CursorKind(138) + +# ObjCSelectorExpr used for in Objective-C. +CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139) + +# Objective-C's protocol expression. +CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140) + +# An Objective-C "bridged" cast expression, which casts between +# Objective-C pointers and C pointers, transferring ownership in the process. +# +# \code +# NSString *str = (__bridge_transfer NSString *)CFCreateString(); +# \endcode +CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141) + +# Represents a C++0x pack expansion that produces a sequence of +# expressions. +# +# A pack expansion expression contains a pattern (which itself is an +# expression) followed by an ellipsis. For example: +CursorKind.PACK_EXPANSION_EXPR = CursorKind(142) + +# Represents an expression that computes the length of a parameter +# pack. +CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143) + +# A statement whose specific kind is not exposed via this interface. +# +# Unexposed statements have the same operations as any other kind of statement; +# one can extract their location information, spelling, children, etc. However, +# the specific kind of the statement is not reported. +CursorKind.UNEXPOSED_STMT = CursorKind(200) + +# A labelled statement in a function. +CursorKind.LABEL_STMT = CursorKind(201) + +# A compound statement +CursorKind.COMPOUND_STMT = CursorKind(202) + +# A case statement. +CursorKind.CASE_STMT = CursorKind(203) + +# A default statement. +CursorKind.DEFAULT_STMT = CursorKind(204) + +# An if statement. +CursorKind.IF_STMT = CursorKind(205) + +# A switch statement. +CursorKind.SWITCH_STMT = CursorKind(206) + +# A while statement. +CursorKind.WHILE_STMT = CursorKind(207) + +# A do statement. +CursorKind.DO_STMT = CursorKind(208) + +# A for statement. +CursorKind.FOR_STMT = CursorKind(209) + +# A goto statement. +CursorKind.GOTO_STMT = CursorKind(210) + +# An indirect goto statement. +CursorKind.INDIRECT_GOTO_STMT = CursorKind(211) + +# A continue statement. +CursorKind.CONTINUE_STMT = CursorKind(212) + +# A break statement. +CursorKind.BREAK_STMT = CursorKind(213) + +# A return statement. +CursorKind.RETURN_STMT = CursorKind(214) + +# A GNU-style inline assembler statement. +CursorKind.ASM_STMT = CursorKind(215) + +# Objective-C's overall @try-@catch-@finally statement. +CursorKind.OBJC_AT_TRY_STMT = CursorKind(216) + +# Objective-C's @catch statement. +CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217) + +# Objective-C's @finally statement. +CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218) + +# Objective-C's @throw statement. +CursorKind.OBJC_AT_THROW_STMT = CursorKind(219) + +# Objective-C's @synchronized statement. +CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220) + +# Objective-C's autorealease pool statement. +CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221) + +# Objective-C's for collection statement. +CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222) + +# C++'s catch statement. +CursorKind.CXX_CATCH_STMT = CursorKind(223) + +# C++'s try statement. +CursorKind.CXX_TRY_STMT = CursorKind(224) + +# C++'s for (* : *) statement. +CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225) + +# Windows Structured Exception Handling's try statement. +CursorKind.SEH_TRY_STMT = CursorKind(226) + +# Windows Structured Exception Handling's except statement. +CursorKind.SEH_EXCEPT_STMT = CursorKind(227) + +# Windows Structured Exception Handling's finally statement. +CursorKind.SEH_FINALLY_STMT = CursorKind(228) + +# The null statement. +CursorKind.NULL_STMT = CursorKind(230) + +# Adaptor class for mixing declarations with statements and expressions. +CursorKind.DECL_STMT = CursorKind(231) + +### +# Other Kinds + +# Cursor that represents the translation unit itself. +# +# The translation unit cursor exists primarily to act as the root cursor for +# traversing the contents of a translation unit. +CursorKind.TRANSLATION_UNIT = CursorKind(300) + +### +# Attributes + +# An attribute whoe specific kind is note exposed via this interface +CursorKind.UNEXPOSED_ATTR = CursorKind(400) + +CursorKind.IB_ACTION_ATTR = CursorKind(401) +CursorKind.IB_OUTLET_ATTR = CursorKind(402) +CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403) + +CursorKind.CXX_FINAL_ATTR = CursorKind(404) +CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405) +CursorKind.ANNOTATE_ATTR = CursorKind(406) +CursorKind.ASM_LABEL_ATTR = CursorKind(407) + +### +# Preprocessing +CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500) +CursorKind.MACRO_DEFINITION = CursorKind(501) +CursorKind.MACRO_INSTANTIATION = CursorKind(502) +CursorKind.INCLUSION_DIRECTIVE = CursorKind(503) + +### Cursors ### + +class Cursor(Structure): + """ + The Cursor class represents a reference to an element within the AST. It + acts as a kind of iterator. + """ + _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)] + + @staticmethod + def from_location(tu, location): + return Cursor_get(tu, location) + + def __eq__(self, other): + return Cursor_eq(self, other) + + def __ne__(self, other): + return not self.__eq__(other) + + def is_definition(self): + """ + Returns true if the declaration pointed at by the cursor is also a + definition of that entity. + """ + return Cursor_is_def(self) + + def get_definition(self): + """ + If the cursor is a reference to a declaration or a declaration of + some entity, return a cursor that points to the definition of that + entity. + """ + # TODO: Should probably check that this is either a reference or + # declaration prior to issuing the lookup. + return Cursor_def(self) + + def get_usr(self): + """Return the Unified Symbol Resultion (USR) for the entity referenced + by the given cursor (or None). + + A Unified Symbol Resolution (USR) is a string that identifies a + particular entity (function, class, variable, etc.) within a + program. USRs can be compared across translation units to determine, + e.g., when references in one translation refer to an entity defined in + another translation unit.""" + return Cursor_usr(self) + + @property + def kind(self): + """Return the kind of this cursor.""" + return CursorKind.from_id(self._kind_id) + + @property + def spelling(self): + """Return the spelling of the entity pointed at by the cursor.""" + if not self.kind.is_declaration(): + # FIXME: clang_getCursorSpelling should be fixed to not assert on + # this, for consistency with clang_getCursorUSR. + return None + if not hasattr(self, '_spelling'): + self._spelling = Cursor_spelling(self) + return self._spelling + + @property + def displayname(self): + """ + Return the display name for the entity referenced by this cursor. + + The display name contains extra information that helps identify the cursor, + such as the parameters of a function or template or the arguments of a + class template specialization. + """ + if not hasattr(self, '_displayname'): + self._displayname = Cursor_displayname(self) + return self._displayname + + @property + def location(self): + """ + Return the source location (the starting character) of the entity + pointed at by the cursor. + """ + if not hasattr(self, '_loc'): + self._loc = Cursor_loc(self) + return self._loc + + @property + def extent(self): + """ + Return the source range (the range of text) occupied by the entity + pointed at by the cursor. + """ + if not hasattr(self, '_extent'): + self._extent = Cursor_extent(self) + return self._extent + + @property + def type(self): + """ + Retrieve the Type (if any) of the entity pointed at by the cursor. + """ + if not hasattr(self, '_type'): + self._type = Cursor_type(self) + return self._type + + @property + def underlying_typedef_type(self): + """Return the underlying type of a typedef declaration. + + Returns a Type for the typedef this cursor is a declaration for. If + the current cursor is not a typedef, this raises. + """ + if not hasattr(self, '_underlying_type'): + assert self.kind.is_declaration() + self._underlying_type = Cursor_underlying_type(self) + + return self._underlying_type + + @property + def enum_type(self): + """Return the integer type of an enum declaration. + + Returns a Type corresponding to an integer. If the cursor is not for an + enum, this raises. + """ + if not hasattr(self, '_enum_type'): + assert self.kind == CursorKind.ENUM_DECL + self._enum_type = Cursor_enum_type(self) + + return self._enum_type + + @property + def objc_type_encoding(self): + """Return the Objective-C type encoding as a str.""" + if not hasattr(self, '_objc_type_encoding'): + self._objc_type_encoding = Cursor_objc_type_encoding(self) + + return self._objc_type_encoding + + @property + def hash(self): + """Returns a hash of the cursor as an int.""" + if not hasattr(self, '_hash'): + self._hash = Cursor_hash(self) + + return self._hash + + def get_children(self): + """Return an iterator for accessing the children of this cursor.""" + + # FIXME: Expose iteration from CIndex, PR6125. + def visitor(child, parent, children): + # FIXME: Document this assertion in API. + # FIXME: There should just be an isNull method. + assert child != Cursor_null() + children.append(child) + return 1 # continue + children = [] + Cursor_visit(self, Cursor_visit_callback(visitor), children) + return iter(children) + + @staticmethod + def from_result(res, fn, args): + assert isinstance(res, Cursor) + # FIXME: There should just be an isNull method. + if res == Cursor_null(): + return None + return res + + +### Type Kinds ### + +class TypeKind(object): + """ + Describes the kind of type. + """ + + # The unique kind objects, indexed by id. + _kinds = [] + _name_map = None + + def __init__(self, value): + if value >= len(TypeKind._kinds): + TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1) + if TypeKind._kinds[value] is not None: + raise ValueError,'TypeKind already loaded' + self.value = value + TypeKind._kinds[value] = self + TypeKind._name_map = None + + def from_param(self): + return self.value + + @property + def name(self): + """Get the enumeration name of this cursor kind.""" + if self._name_map is None: + self._name_map = {} + for key,value in TypeKind.__dict__.items(): + if isinstance(value,TypeKind): + self._name_map[value] = key + return self._name_map[self] + + @property + def spelling(self): + """Retrieve the spelling of this TypeKind.""" + return TypeKind_spelling(self.value) + + @staticmethod + def from_id(id): + if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None: + raise ValueError,'Unknown type kind %d' % id + return TypeKind._kinds[id] + + def __repr__(self): + return 'TypeKind.%s' % (self.name,) + +TypeKind_spelling = lib.clang_getTypeKindSpelling +TypeKind_spelling.argtypes = [c_uint] +TypeKind_spelling.restype = _CXString +TypeKind_spelling.errcheck = _CXString.from_result + + +TypeKind.INVALID = TypeKind(0) +TypeKind.UNEXPOSED = TypeKind(1) +TypeKind.VOID = TypeKind(2) +TypeKind.BOOL = TypeKind(3) +TypeKind.CHAR_U = TypeKind(4) +TypeKind.UCHAR = TypeKind(5) +TypeKind.CHAR16 = TypeKind(6) +TypeKind.CHAR32 = TypeKind(7) +TypeKind.USHORT = TypeKind(8) +TypeKind.UINT = TypeKind(9) +TypeKind.ULONG = TypeKind(10) +TypeKind.ULONGLONG = TypeKind(11) +TypeKind.UINT128 = TypeKind(12) +TypeKind.CHAR_S = TypeKind(13) +TypeKind.SCHAR = TypeKind(14) +TypeKind.WCHAR = TypeKind(15) +TypeKind.SHORT = TypeKind(16) +TypeKind.INT = TypeKind(17) +TypeKind.LONG = TypeKind(18) +TypeKind.LONGLONG = TypeKind(19) +TypeKind.INT128 = TypeKind(20) +TypeKind.FLOAT = TypeKind(21) +TypeKind.DOUBLE = TypeKind(22) +TypeKind.LONGDOUBLE = TypeKind(23) +TypeKind.NULLPTR = TypeKind(24) +TypeKind.OVERLOAD = TypeKind(25) +TypeKind.DEPENDENT = TypeKind(26) +TypeKind.OBJCID = TypeKind(27) +TypeKind.OBJCCLASS = TypeKind(28) +TypeKind.OBJCSEL = TypeKind(29) +TypeKind.COMPLEX = TypeKind(100) +TypeKind.POINTER = TypeKind(101) +TypeKind.BLOCKPOINTER = TypeKind(102) +TypeKind.LVALUEREFERENCE = TypeKind(103) +TypeKind.RVALUEREFERENCE = TypeKind(104) +TypeKind.RECORD = TypeKind(105) +TypeKind.ENUM = TypeKind(106) +TypeKind.TYPEDEF = TypeKind(107) +TypeKind.OBJCINTERFACE = TypeKind(108) +TypeKind.OBJCOBJECTPOINTER = TypeKind(109) +TypeKind.FUNCTIONNOPROTO = TypeKind(110) +TypeKind.FUNCTIONPROTO = TypeKind(111) +TypeKind.CONSTANTARRAY = TypeKind(112) +TypeKind.VECTOR = TypeKind(113) + +class Type(Structure): + """ + The type of an element in the abstract syntax tree. + """ + _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] + + @property + def kind(self): + """Return the kind of this type.""" + return TypeKind.from_id(self._kind_id) + + def argument_types(self): + """Retrieve a container for the non-variadic arguments for this type. + + The returned object is iterable and indexable. Each item in the + container is a Type instance. + """ + class ArgumentsIterator(collections.Sequence): + def __init__(self, parent): + self.parent = parent + self.length = None + + def __len__(self): + if self.length is None: + self.length = Type_get_num_arg_types(self.parent) + + return self.length + + def __getitem__(self, key): + # FIXME Support slice objects. + if not isinstance(key, int): + raise TypeError("Must supply a non-negative int.") + + if key < 0: + raise IndexError("Only non-negative indexes are accepted.") + + if key >= len(self): + raise IndexError("Index greater than container length: " + "%d > %d" % ( key, len(self) )) + + result = Type_get_arg_type(self.parent, key) + if result.kind == TypeKind.INVALID: + raise IndexError("Argument could not be retrieved.") + + return result + + assert self.kind == TypeKind.FUNCTIONPROTO + return ArgumentsIterator(self) + + @property + def element_type(self): + """Retrieve the Type of elements within this Type. + + If accessed on a type that is not an array, complex, or vector type, an + exception will be raised. + """ + result = Type_get_element_type(self) + if result.kind == TypeKind.INVALID: + raise Exception('Element type not available on this type.') + + return result + + @property + def element_count(self): + """Retrieve the number of elements in this type. + + Returns an int. + + If the Type is not an array or vector, this raises. + """ + result = Type_get_num_elements(self) + if result < 0: + raise Exception('Type does not have elements.') + + return result + + @staticmethod + def from_result(res, fn, args): + assert isinstance(res, Type) + return res + + def get_canonical(self): + """ + Return the canonical type for a Type. + + Clang's type system explicitly models typedefs and all the + ways a specific type can be represented. The canonical type + is the underlying type with all the "sugar" removed. For + example, if 'T' is a typedef for 'int', the canonical type for + 'T' would be 'int'. + """ + return Type_get_canonical(self) + + def is_const_qualified(self): + """Determine whether a Type has the "const" qualifier set. + + This does not look through typedefs that may have added "const" + at a different level. + """ + return Type_is_const_qualified(self) + + def is_volatile_qualified(self): + """Determine whether a Type has the "volatile" qualifier set. + + This does not look through typedefs that may have added "volatile" + at a different level. + """ + return Type_is_volatile_qualified(self) + + def is_restrict_qualified(self): + """Determine whether a Type has the "restrict" qualifier set. + + This does not look through typedefs that may have added "restrict" at + a different level. + """ + return Type_is_restrict_qualified(self) + + def is_function_variadic(self): + """Determine whether this function Type is a variadic function type.""" + assert self.kind == TypeKind.FUNCTIONPROTO + + return Type_is_variadic(self) + + def is_pod(self): + """Determine whether this Type represents plain old data (POD).""" + return Type_is_pod(self) + + def get_pointee(self): + """ + For pointer types, returns the type of the pointee. + """ + return Type_get_pointee(self) + + def get_declaration(self): + """ + Return the cursor for the declaration of the given type. + """ + return Type_get_declaration(self) + + def get_result(self): + """ + Retrieve the result type associated with a function type. + """ + return Type_get_result(self) + + def get_array_element_type(self): + """ + Retrieve the type of the elements of the array type. + """ + return Type_get_array_element(self) + + def get_array_size(self): + """ + Retrieve the size of the constant array. + """ + return Type_get_array_size(self) + + def __eq__(self, other): + if type(other) != type(self): + return False + + return Type_equal(self, other) + + def __ne__(self, other): + return not self.__eq__(other) + +## CIndex Objects ## + +# CIndex objects (derived from ClangObject) are essentially lightweight +# wrappers attached to some underlying object, which is exposed via CIndex as +# a void*. + +class ClangObject(object): + """ + A helper for Clang objects. This class helps act as an intermediary for + the ctypes library and the Clang CIndex library. + """ + def __init__(self, obj): + assert isinstance(obj, c_object_p) and obj + self.obj = self._as_parameter_ = obj + + def from_param(self): + return self._as_parameter_ + + +class _CXUnsavedFile(Structure): + """Helper for passing unsaved file arguments.""" + _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] + +## Diagnostic Conversion ## + +_clang_getNumDiagnostics = lib.clang_getNumDiagnostics +_clang_getNumDiagnostics.argtypes = [c_object_p] +_clang_getNumDiagnostics.restype = c_uint + +_clang_getDiagnostic = lib.clang_getDiagnostic +_clang_getDiagnostic.argtypes = [c_object_p, c_uint] +_clang_getDiagnostic.restype = c_object_p + +_clang_disposeDiagnostic = lib.clang_disposeDiagnostic +_clang_disposeDiagnostic.argtypes = [Diagnostic] + +_clang_getDiagnosticSeverity = lib.clang_getDiagnosticSeverity +_clang_getDiagnosticSeverity.argtypes = [Diagnostic] +_clang_getDiagnosticSeverity.restype = c_int + +_clang_getDiagnosticLocation = lib.clang_getDiagnosticLocation +_clang_getDiagnosticLocation.argtypes = [Diagnostic] +_clang_getDiagnosticLocation.restype = SourceLocation + +_clang_getDiagnosticSpelling = lib.clang_getDiagnosticSpelling +_clang_getDiagnosticSpelling.argtypes = [Diagnostic] +_clang_getDiagnosticSpelling.restype = _CXString +_clang_getDiagnosticSpelling.errcheck = _CXString.from_result + +_clang_getDiagnosticNumRanges = lib.clang_getDiagnosticNumRanges +_clang_getDiagnosticNumRanges.argtypes = [Diagnostic] +_clang_getDiagnosticNumRanges.restype = c_uint + +_clang_getDiagnosticRange = lib.clang_getDiagnosticRange +_clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint] +_clang_getDiagnosticRange.restype = SourceRange + +_clang_getDiagnosticNumFixIts = lib.clang_getDiagnosticNumFixIts +_clang_getDiagnosticNumFixIts.argtypes = [Diagnostic] +_clang_getDiagnosticNumFixIts.restype = c_uint + +_clang_getDiagnosticFixIt = lib.clang_getDiagnosticFixIt +_clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint, POINTER(SourceRange)] +_clang_getDiagnosticFixIt.restype = _CXString +_clang_getDiagnosticFixIt.errcheck = _CXString.from_result + +_clang_getDiagnosticCategory = lib.clang_getDiagnosticCategory +_clang_getDiagnosticCategory.argtypes = [Diagnostic] +_clang_getDiagnosticCategory.restype = c_uint + +_clang_getDiagnosticCategoryName = lib.clang_getDiagnosticCategoryName +_clang_getDiagnosticCategoryName.argtypes = [c_uint] +_clang_getDiagnosticCategoryName.restype = _CXString +_clang_getDiagnosticCategoryName.errcheck = _CXString.from_result + +_clang_getDiagnosticOption = lib.clang_getDiagnosticOption +_clang_getDiagnosticOption.argtypes = [Diagnostic, POINTER(_CXString)] +_clang_getDiagnosticOption.restype = _CXString +_clang_getDiagnosticOption.errcheck = _CXString.from_result + +### + +class CompletionChunk: + class Kind: + def __init__(self, name): + self.name = name + + def __str__(self): + return self.name + + def __repr__(self): + return "" % self + + def __init__(self, completionString, key): + self.cs = completionString + self.key = key + + def __repr__(self): + return "{'" + self.spelling + "', " + str(self.kind) + "}" + + @property + def spelling(self): + return _clang_getCompletionChunkText(self.cs, self.key).spelling + + @property + def kind(self): + res = _clang_getCompletionChunkKind(self.cs, self.key) + return completionChunkKindMap[res] + + @property + def string(self): + res = _clang_getCompletionChunkCompletionString(self.cs, self.key) + + if (res): + return CompletionString(res) + else: + None + + def isKindOptional(self): + return self.kind == completionChunkKindMap[0] + + def isKindTypedText(self): + return self.kind == completionChunkKindMap[1] + + def isKindPlaceHolder(self): + return self.kind == completionChunkKindMap[3] + + def isKindInformative(self): + return self.kind == completionChunkKindMap[4] + + def isKindResultType(self): + return self.kind == completionChunkKindMap[15] + +completionChunkKindMap = { + 0: CompletionChunk.Kind("Optional"), + 1: CompletionChunk.Kind("TypedText"), + 2: CompletionChunk.Kind("Text"), + 3: CompletionChunk.Kind("Placeholder"), + 4: CompletionChunk.Kind("Informative"), + 5: CompletionChunk.Kind("CurrentParameter"), + 6: CompletionChunk.Kind("LeftParen"), + 7: CompletionChunk.Kind("RightParen"), + 8: CompletionChunk.Kind("LeftBracket"), + 9: CompletionChunk.Kind("RightBracket"), + 10: CompletionChunk.Kind("LeftBrace"), + 11: CompletionChunk.Kind("RightBrace"), + 12: CompletionChunk.Kind("LeftAngle"), + 13: CompletionChunk.Kind("RightAngle"), + 14: CompletionChunk.Kind("Comma"), + 15: CompletionChunk.Kind("ResultType"), + 16: CompletionChunk.Kind("Colon"), + 17: CompletionChunk.Kind("SemiColon"), + 18: CompletionChunk.Kind("Equal"), + 19: CompletionChunk.Kind("HorizontalSpace"), + 20: CompletionChunk.Kind("VerticalSpace")} + +class CompletionString(ClangObject): + class Availability: + def __init__(self, name): + self.name = name + + def __str__(self): + return self.name + + def __repr__(self): + return "" % self + + def __len__(self): + return _clang_getNumCompletionChunks(self.obj) + + def __getitem__(self, key): + if len(self) <= key: + raise IndexError + return CompletionChunk(self.obj, key) + + @property + def priority(self): + return _clang_getCompletionPriority(self.obj) + + @property + def availability(self): + res = _clang_getCompletionAvailability(self.obj) + return availabilityKinds[res] + + def __repr__(self): + return " | ".join([str(a) for a in self]) \ + + " || Priority: " + str(self.priority) \ + + " || Availability: " + str(self.availability) + +availabilityKinds = { + 0: CompletionChunk.Kind("Available"), + 1: CompletionChunk.Kind("Deprecated"), + 2: CompletionChunk.Kind("NotAvailable")} + +class CodeCompletionResult(Structure): + _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] + + def __repr__(self): + return str(CompletionString(self.completionString)) + + @property + def kind(self): + return CursorKind.from_id(self.cursorKind) + + @property + def string(self): + return CompletionString(self.completionString) + +class CCRStructure(Structure): + _fields_ = [('results', POINTER(CodeCompletionResult)), + ('numResults', c_int)] + + def __len__(self): + return self.numResults + + def __getitem__(self, key): + if len(self) <= key: + raise IndexError + + return self.results[key] + +class CodeCompletionResults(ClangObject): + def __init__(self, ptr): + assert isinstance(ptr, POINTER(CCRStructure)) and ptr + self.ptr = self._as_parameter_ = ptr + + def from_param(self): + return self._as_parameter_ + + def __del__(self): + CodeCompletionResults_dispose(self) + + @property + def results(self): + return self.ptr.contents + + @property + def diagnostics(self): + class DiagnosticsItr: + def __init__(self, ccr): + self.ccr= ccr + + def __len__(self): + return int(_clang_codeCompleteGetNumDiagnostics(self.ccr)) + + def __getitem__(self, key): + return _clang_codeCompleteGetDiagnostic(self.ccr, key) + + return DiagnosticsItr(self) + + +class Index(ClangObject): + """ + The Index type provides the primary interface to the Clang CIndex library, + primarily by providing an interface for reading and parsing translation + units. + """ + + @staticmethod + def create(excludeDecls=False): + """ + Create a new Index. + Parameters: + excludeDecls -- Exclude local declarations from translation units. + """ + return Index(Index_create(excludeDecls, 0)) + + def __del__(self): + Index_dispose(self) + + def read(self, path): + """Load the translation unit from the given AST file.""" + ptr = TranslationUnit_read(self, path) + if ptr: + return TranslationUnit(ptr) + return None + + def parse(self, path, args = [], unsaved_files = [], options = 0): + """ + Load the translation unit from the given source code file by running + clang and generating the AST before loading. Additional command line + parameters can be passed to clang via the args parameter. + + In-memory contents for files can be provided by passing a list of pairs + to as unsaved_files, the first item should be the filenames to be mapped + and the second should be the contents to be substituted for the + file. The contents may be passed as strings or file objects. + """ + arg_array = 0 + if len(args): + arg_array = (c_char_p * len(args))(* args) + unsaved_files_array = 0 + if len(unsaved_files): + unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() + for i,(name,value) in enumerate(unsaved_files): + if not isinstance(value, str): + # FIXME: It would be great to support an efficient version + # of this, one day. + value = value.read() + print value + if not isinstance(value, str): + raise TypeError,'Unexpected unsaved file contents.' + unsaved_files_array[i].name = name + unsaved_files_array[i].contents = value + unsaved_files_array[i].length = len(value) + ptr = TranslationUnit_parse(self, path, arg_array, len(args), + unsaved_files_array, len(unsaved_files), + options) + if ptr: + return TranslationUnit(ptr) + return None + + +class TranslationUnit(ClangObject): + """ + The TranslationUnit class represents a source code translation unit and + provides read-only access to its top-level declarations. + """ + + def __init__(self, ptr): + ClangObject.__init__(self, ptr) + + def __del__(self): + TranslationUnit_dispose(self) + + @property + def cursor(self): + """Retrieve the cursor that represents the given translation unit.""" + return TranslationUnit_cursor(self) + + @property + def spelling(self): + """Get the original translation unit source file name.""" + return TranslationUnit_spelling(self) + + def get_includes(self): + """ + Return an iterable sequence of FileInclusion objects that describe the + sequence of inclusions in a translation unit. The first object in + this sequence is always the input file. Note that this method will not + recursively iterate over header files included through precompiled + headers. + """ + def visitor(fobj, lptr, depth, includes): + if depth > 0: + loc = lptr.contents + includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) + + # Automatically adapt CIndex/ctype pointers to python objects + includes = [] + TranslationUnit_includes(self, + TranslationUnit_includes_callback(visitor), + includes) + return iter(includes) + + @property + def diagnostics(self): + """ + Return an iterable (and indexable) object containing the diagnostics. + """ + class DiagIterator: + def __init__(self, tu): + self.tu = tu + + def __len__(self): + return int(_clang_getNumDiagnostics(self.tu)) + + def __getitem__(self, key): + diag = _clang_getDiagnostic(self.tu, key) + if not diag: + raise IndexError + return Diagnostic(diag) + + return DiagIterator(self) + + def reparse(self, unsaved_files = [], options = 0): + """ + Reparse an already parsed translation unit. + + In-memory contents for files can be provided by passing a list of pairs + as unsaved_files, the first items should be the filenames to be mapped + and the second should be the contents to be substituted for the + file. The contents may be passed as strings or file objects. + """ + unsaved_files_array = 0 + if len(unsaved_files): + unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() + for i,(name,value) in enumerate(unsaved_files): + if not isinstance(value, str): + # FIXME: It would be great to support an efficient version + # of this, one day. + value = value.read() + print value + if not isinstance(value, str): + raise TypeError,'Unexpected unsaved file contents.' + unsaved_files_array[i].name = name + unsaved_files_array[i].contents = value + unsaved_files_array[i].length = len(value) + ptr = TranslationUnit_reparse(self, len(unsaved_files), + unsaved_files_array, + options) + def codeComplete(self, path, line, column, unsaved_files = [], options = 0): + """ + Code complete in this translation unit. + + In-memory contents for files can be provided by passing a list of pairs + as unsaved_files, the first items should be the filenames to be mapped + and the second should be the contents to be substituted for the + file. The contents may be passed as strings or file objects. + """ + unsaved_files_array = 0 + if len(unsaved_files): + unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() + for i,(name,value) in enumerate(unsaved_files): + if not isinstance(value, str): + # FIXME: It would be great to support an efficient version + # of this, one day. + value = value.read() + print value + if not isinstance(value, str): + raise TypeError,'Unexpected unsaved file contents.' + unsaved_files_array[i].name = name + unsaved_files_array[i].contents = value + unsaved_files_array[i].length = len(value) + ptr = TranslationUnit_codeComplete(self, path, + line, column, + unsaved_files_array, + len(unsaved_files), + options) + if ptr: + return CodeCompletionResults(ptr) + return None + +class File(ClangObject): + """ + The File class represents a particular source file that is part of a + translation unit. + """ + + @staticmethod + def from_name(translation_unit, file_name): + """Retrieve a file handle within the given translation unit.""" + return File(File_getFile(translation_unit, file_name)) + + @property + def name(self): + """Return the complete file and path name of the file.""" + return _CXString_getCString(File_name(self)) + + @property + def time(self): + """Return the last modification time of the file.""" + return File_time(self) + + def __str__(self): + return self.name + + def __repr__(self): + return "" % (self.name) + +class FileInclusion(object): + """ + The FileInclusion class represents the inclusion of one source file by + another via a '#include' directive or as the input file for the translation + unit. This class provides information about the included file, the including + file, the location of the '#include' directive and the depth of the included + file in the stack. Note that the input file has depth 0. + """ + + def __init__(self, src, tgt, loc, depth): + self.source = src + self.include = tgt + self.location = loc + self.depth = depth + + @property + def is_input_file(self): + """True if the included file is the input file.""" + return self.depth == 0 + +# Additional Functions and Types + +# String Functions +_CXString_dispose = lib.clang_disposeString +_CXString_dispose.argtypes = [_CXString] + +_CXString_getCString = lib.clang_getCString +_CXString_getCString.argtypes = [_CXString] +_CXString_getCString.restype = c_char_p + +# Source Location Functions +SourceLocation_loc = lib.clang_getInstantiationLocation +SourceLocation_loc.argtypes = [SourceLocation, POINTER(c_object_p), + POINTER(c_uint), POINTER(c_uint), + POINTER(c_uint)] + +SourceLocation_getLocation = lib.clang_getLocation +SourceLocation_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint] +SourceLocation_getLocation.restype = SourceLocation + +SourceLocation_equalLocations = lib.clang_equalLocations +SourceLocation_equalLocations.argtypes = [SourceLocation, SourceLocation] +SourceLocation_equalLocations.restype = bool + +# Source Range Functions +SourceRange_getRange = lib.clang_getRange +SourceRange_getRange.argtypes = [SourceLocation, SourceLocation] +SourceRange_getRange.restype = SourceRange + +SourceRange_start = lib.clang_getRangeStart +SourceRange_start.argtypes = [SourceRange] +SourceRange_start.restype = SourceLocation + +SourceRange_end = lib.clang_getRangeEnd +SourceRange_end.argtypes = [SourceRange] +SourceRange_end.restype = SourceLocation + +SourceRange_equalRanges = lib.clang_equalRanges +SourceRange_equalRanges.argtypes = [SourceRange, SourceRange] +SourceRange_equalRanges.restype = bool + +# CursorKind Functions +CursorKind_is_decl = lib.clang_isDeclaration +CursorKind_is_decl.argtypes = [CursorKind] +CursorKind_is_decl.restype = bool + +CursorKind_is_ref = lib.clang_isReference +CursorKind_is_ref.argtypes = [CursorKind] +CursorKind_is_ref.restype = bool + +CursorKind_is_expr = lib.clang_isExpression +CursorKind_is_expr.argtypes = [CursorKind] +CursorKind_is_expr.restype = bool + +CursorKind_is_stmt = lib.clang_isStatement +CursorKind_is_stmt.argtypes = [CursorKind] +CursorKind_is_stmt.restype = bool + +CursorKind_is_attribute = lib.clang_isAttribute +CursorKind_is_attribute.argtypes = [CursorKind] +CursorKind_is_attribute.restype = bool + +CursorKind_is_inv = lib.clang_isInvalid +CursorKind_is_inv.argtypes = [CursorKind] +CursorKind_is_inv.restype = bool + +CursorKind_is_translation_unit = lib.clang_isTranslationUnit +CursorKind_is_translation_unit.argtypes = [CursorKind] +CursorKind_is_translation_unit.restype = bool + +CursorKind_is_preprocessing = lib.clang_isPreprocessing +CursorKind_is_preprocessing.argtypes = [CursorKind] +CursorKind_is_preprocessing.restype = bool + +CursorKind_is_unexposed = lib.clang_isUnexposed +CursorKind_is_unexposed.argtypes = [CursorKind] +CursorKind_is_unexposed.restype = bool + +# Cursor Functions +# TODO: Implement this function +Cursor_get = lib.clang_getCursor +Cursor_get.argtypes = [TranslationUnit, SourceLocation] +Cursor_get.restype = Cursor + +Cursor_null = lib.clang_getNullCursor +Cursor_null.restype = Cursor + +Cursor_usr = lib.clang_getCursorUSR +Cursor_usr.argtypes = [Cursor] +Cursor_usr.restype = _CXString +Cursor_usr.errcheck = _CXString.from_result + +Cursor_is_def = lib.clang_isCursorDefinition +Cursor_is_def.argtypes = [Cursor] +Cursor_is_def.restype = bool + +Cursor_def = lib.clang_getCursorDefinition +Cursor_def.argtypes = [Cursor] +Cursor_def.restype = Cursor +Cursor_def.errcheck = Cursor.from_result + +Cursor_eq = lib.clang_equalCursors +Cursor_eq.argtypes = [Cursor, Cursor] +Cursor_eq.restype = bool + +Cursor_hash = lib.clang_hashCursor +Cursor_hash.argtypes = [Cursor] +Cursor_hash.restype = c_uint + +Cursor_spelling = lib.clang_getCursorSpelling +Cursor_spelling.argtypes = [Cursor] +Cursor_spelling.restype = _CXString +Cursor_spelling.errcheck = _CXString.from_result + +Cursor_displayname = lib.clang_getCursorDisplayName +Cursor_displayname.argtypes = [Cursor] +Cursor_displayname.restype = _CXString +Cursor_displayname.errcheck = _CXString.from_result + +Cursor_loc = lib.clang_getCursorLocation +Cursor_loc.argtypes = [Cursor] +Cursor_loc.restype = SourceLocation + +Cursor_extent = lib.clang_getCursorExtent +Cursor_extent.argtypes = [Cursor] +Cursor_extent.restype = SourceRange + +Cursor_ref = lib.clang_getCursorReferenced +Cursor_ref.argtypes = [Cursor] +Cursor_ref.restype = Cursor +Cursor_ref.errcheck = Cursor.from_result + +Cursor_type = lib.clang_getCursorType +Cursor_type.argtypes = [Cursor] +Cursor_type.restype = Type +Cursor_type.errcheck = Type.from_result + +Cursor_underlying_type = lib.clang_getTypedefDeclUnderlyingType +Cursor_underlying_type.argtypes = [Cursor] +Cursor_underlying_type.restype = Type +Cursor_underlying_type.errcheck = Type.from_result + +Cursor_enum_type = lib.clang_getEnumDeclIntegerType +Cursor_enum_type.argtypes = [Cursor] +Cursor_enum_type.restype = Type +Cursor_enum_type.errcheck = Type.from_result + +Cursor_objc_type_encoding = lib.clang_getDeclObjCTypeEncoding +Cursor_objc_type_encoding.argtypes = [Cursor] +Cursor_objc_type_encoding.restype = _CXString +Cursor_objc_type_encoding.errcheck = _CXString.from_result + +Cursor_visit_callback = CFUNCTYPE(c_int, Cursor, Cursor, py_object) +Cursor_visit = lib.clang_visitChildren +Cursor_visit.argtypes = [Cursor, Cursor_visit_callback, py_object] +Cursor_visit.restype = c_uint + +# Type Functions +Type_get_canonical = lib.clang_getCanonicalType +Type_get_canonical.argtypes = [Type] +Type_get_canonical.restype = Type +Type_get_canonical.errcheck = Type.from_result + +Type_is_const_qualified = lib.clang_isConstQualifiedType +Type_is_const_qualified.argtypes = [Type] +Type_is_const_qualified.restype = bool + +Type_is_volatile_qualified = lib.clang_isVolatileQualifiedType +Type_is_volatile_qualified.argtypes = [Type] +Type_is_volatile_qualified.restype = bool + +Type_is_restrict_qualified = lib.clang_isRestrictQualifiedType +Type_is_restrict_qualified.argtypes = [Type] +Type_is_restrict_qualified.restype = bool + +Type_is_pod = lib.clang_isPODType +Type_is_pod.argtypes = [Type] +Type_is_pod.restype = bool + +Type_is_variadic = lib.clang_isFunctionTypeVariadic +Type_is_variadic.argtypes = [Type] +Type_is_variadic.restype = bool + +Type_get_pointee = lib.clang_getPointeeType +Type_get_pointee.argtypes = [Type] +Type_get_pointee.restype = Type +Type_get_pointee.errcheck = Type.from_result + +Type_get_declaration = lib.clang_getTypeDeclaration +Type_get_declaration.argtypes = [Type] +Type_get_declaration.restype = Cursor +Type_get_declaration.errcheck = Cursor.from_result + +Type_get_result = lib.clang_getResultType +Type_get_result.argtypes = [Type] +Type_get_result.restype = Type +Type_get_result.errcheck = Type.from_result + +Type_get_num_arg_types = lib.clang_getNumArgTypes +Type_get_num_arg_types.argtypes = [Type] +Type_get_num_arg_types.restype = c_uint + +Type_get_arg_type = lib.clang_getArgType +Type_get_arg_type.argtypes = [Type, c_uint] +Type_get_arg_type.restype = Type +Type_get_arg_type.errcheck = Type.from_result +Type_get_element_type = lib.clang_getElementType + +Type_get_element_type.argtypes = [Type] +Type_get_element_type.restype = Type +Type_get_element_type.errcheck = Type.from_result + +Type_get_num_elements = lib.clang_getNumElements +Type_get_num_elements.argtypes = [Type] +Type_get_num_elements.restype = c_longlong + +Type_get_array_element = lib.clang_getArrayElementType +Type_get_array_element.argtypes = [Type] +Type_get_array_element.restype = Type +Type_get_array_element.errcheck = Type.from_result + +Type_get_array_size = lib.clang_getArraySize +Type_get_array_size.argtype = [Type] +Type_get_array_size.restype = c_longlong + +Type_equal = lib.clang_equalTypes +Type_equal.argtypes = [Type, Type] +Type_equal.restype = bool + +# Index Functions +Index_create = lib.clang_createIndex +Index_create.argtypes = [c_int, c_int] +Index_create.restype = c_object_p + +Index_dispose = lib.clang_disposeIndex +Index_dispose.argtypes = [Index] + +# Translation Unit Functions +TranslationUnit_read = lib.clang_createTranslationUnit +TranslationUnit_read.argtypes = [Index, c_char_p] +TranslationUnit_read.restype = c_object_p + +TranslationUnit_parse = lib.clang_parseTranslationUnit +TranslationUnit_parse.argtypes = [Index, c_char_p, c_void_p, + c_int, c_void_p, c_int, c_int] +TranslationUnit_parse.restype = c_object_p + +TranslationUnit_reparse = lib.clang_reparseTranslationUnit +TranslationUnit_reparse.argtypes = [TranslationUnit, c_int, c_void_p, c_int] +TranslationUnit_reparse.restype = c_int + +TranslationUnit_codeComplete = lib.clang_codeCompleteAt +TranslationUnit_codeComplete.argtypes = [TranslationUnit, c_char_p, c_int, + c_int, c_void_p, c_int, c_int] +TranslationUnit_codeComplete.restype = POINTER(CCRStructure) + +TranslationUnit_cursor = lib.clang_getTranslationUnitCursor +TranslationUnit_cursor.argtypes = [TranslationUnit] +TranslationUnit_cursor.restype = Cursor +TranslationUnit_cursor.errcheck = Cursor.from_result + +TranslationUnit_spelling = lib.clang_getTranslationUnitSpelling +TranslationUnit_spelling.argtypes = [TranslationUnit] +TranslationUnit_spelling.restype = _CXString +TranslationUnit_spelling.errcheck = _CXString.from_result + +TranslationUnit_dispose = lib.clang_disposeTranslationUnit +TranslationUnit_dispose.argtypes = [TranslationUnit] + +TranslationUnit_includes_callback = CFUNCTYPE(None, + c_object_p, + POINTER(SourceLocation), + c_uint, py_object) +TranslationUnit_includes = lib.clang_getInclusions +TranslationUnit_includes.argtypes = [TranslationUnit, + TranslationUnit_includes_callback, + py_object] + +# File Functions +File_getFile = lib.clang_getFile +File_getFile.argtypes = [TranslationUnit, c_char_p] +File_getFile.restype = c_object_p + +File_name = lib.clang_getFileName +File_name.argtypes = [File] +File_name.restype = _CXString + +File_time = lib.clang_getFileTime +File_time.argtypes = [File] +File_time.restype = c_uint + +# Code completion + +CodeCompletionResults_dispose = lib.clang_disposeCodeCompleteResults +CodeCompletionResults_dispose.argtypes = [CodeCompletionResults] + +_clang_codeCompleteGetNumDiagnostics = lib.clang_codeCompleteGetNumDiagnostics +_clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults] +_clang_codeCompleteGetNumDiagnostics.restype = c_int + +_clang_codeCompleteGetDiagnostic = lib.clang_codeCompleteGetDiagnostic +_clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults, c_int] +_clang_codeCompleteGetDiagnostic.restype = Diagnostic + +_clang_getCompletionChunkText = lib.clang_getCompletionChunkText +_clang_getCompletionChunkText.argtypes = [c_void_p, c_int] +_clang_getCompletionChunkText.restype = _CXString + +_clang_getCompletionChunkKind = lib.clang_getCompletionChunkKind +_clang_getCompletionChunkKind.argtypes = [c_void_p, c_int] +_clang_getCompletionChunkKind.restype = c_int + +_clang_getCompletionChunkCompletionString = lib.clang_getCompletionChunkCompletionString +_clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int] +_clang_getCompletionChunkCompletionString.restype = c_object_p + +_clang_getNumCompletionChunks = lib.clang_getNumCompletionChunks +_clang_getNumCompletionChunks.argtypes = [c_void_p] +_clang_getNumCompletionChunks.restype = c_int + +_clang_getCompletionAvailability = lib.clang_getCompletionAvailability +_clang_getCompletionAvailability.argtypes = [c_void_p] +_clang_getCompletionAvailability.restype = c_int + +_clang_getCompletionPriority = lib.clang_getCompletionPriority +_clang_getCompletionPriority.argtypes = [c_void_p] +_clang_getCompletionPriority.restype = c_int + + +### + +__all__ = ['Index', 'TranslationUnit', 'Cursor', 'CursorKind', 'Type', 'TypeKind', + 'Diagnostic', 'FixIt', 'CodeCompletionResults', 'SourceRange', + 'SourceLocation', 'File'] diff --git a/cpp/llvm/tools/clang/bindings/python/examples/cindex/cindex-dump.py b/cpp/llvm/tools/clang/bindings/python/examples/cindex/cindex-dump.py new file mode 100644 index 00000000..af7ddab6 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/examples/cindex/cindex-dump.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python + +#===- cindex-dump.py - cindex/Python Source Dump -------------*- python -*--===# +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +#===------------------------------------------------------------------------===# + +""" +A simple command line tool for dumping a source file using the Clang Index +Library. +""" + +def get_diag_info(diag): + return { 'severity' : diag.severity, + 'location' : diag.location, + 'spelling' : diag.spelling, + 'ranges' : diag.ranges, + 'fixits' : diag.fixits } + +def get_cursor_id(cursor, cursor_list = []): + if not opts.showIDs: + return None + + if cursor is None: + return None + + # FIXME: This is really slow. It would be nice if the index API exposed + # something that let us hash cursors. + for i,c in enumerate(cursor_list): + if cursor == c: + return i + cursor_list.append(cursor) + return len(cursor_list) - 1 + +def get_info(node, depth=0): + if opts.maxDepth is not None and depth >= opts.maxDepth: + children = None + else: + children = [get_info(c, depth+1) + for c in node.get_children()] + return { 'id' : get_cursor_id(node), + 'kind' : node.kind, + 'usr' : node.get_usr(), + 'spelling' : node.spelling, + 'location' : node.location, + 'extent.start' : node.extent.start, + 'extent.end' : node.extent.end, + 'is_definition' : node.is_definition(), + 'definition id' : get_cursor_id(node.get_definition()), + 'children' : children } + +def main(): + from clang.cindex import Index + from pprint import pprint + + from optparse import OptionParser, OptionGroup + + global opts + + parser = OptionParser("usage: %prog [options] {filename} [clang-args*]") + parser.add_option("", "--show-ids", dest="showIDs", + help="Don't compute cursor IDs (very slow)", + default=False) + parser.add_option("", "--max-depth", dest="maxDepth", + help="Limit cursor expansion to depth N", + metavar="N", type=int, default=None) + parser.disable_interspersed_args() + (opts, args) = parser.parse_args() + + if len(args) == 0: + parser.error('invalid number arguments') + + index = Index.create() + tu = index.parse(None, args) + if not tu: + parser.error("unable to load input") + + pprint(('diags', map(get_diag_info, tu.diagnostics))) + pprint(('nodes', get_info(tu.cursor))) + +if __name__ == '__main__': + main() + diff --git a/cpp/llvm/tools/clang/bindings/python/examples/cindex/cindex-includes.py b/cpp/llvm/tools/clang/bindings/python/examples/cindex/cindex-includes.py new file mode 100644 index 00000000..17500227 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/examples/cindex/cindex-includes.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python + +#===- cindex-includes.py - cindex/Python Inclusion Graph -----*- python -*--===# +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +#===------------------------------------------------------------------------===# + +""" +A simple command line tool for dumping a Graphviz description (dot) that +describes include dependencies. +""" + +def main(): + import sys + from clang.cindex import Index + + from optparse import OptionParser, OptionGroup + + parser = OptionParser("usage: %prog [options] {filename} [clang-args*]") + parser.disable_interspersed_args() + (opts, args) = parser.parse_args() + if len(args) == 0: + parser.error('invalid number arguments') + + # FIXME: Add an output file option + out = sys.stdout + + index = Index.create() + tu = index.parse(None, args) + if not tu: + parser.error("unable to load input") + + # A helper function for generating the node name. + def name(f): + if f: + return "\"" + f.name + "\"" + + # Generate the include graph + out.write("digraph G {\n") + for i in tu.get_includes(): + line = " "; + if i.is_input_file: + # Always write the input file as a node just in case it doesn't + # actually include anything. This would generate a 1 node graph. + line += name(i.include) + else: + line += '%s->%s' % (name(i.source), name(i.include)) + line += "\n"; + out.write(line) + out.write("}\n") + +if __name__ == '__main__': + main() + diff --git a/cpp/llvm/tools/clang/bindings/python/tests/__init__.py b/cpp/llvm/tools/clang/bindings/python/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/header1.h b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/header1.h new file mode 100644 index 00000000..b4eacbee --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/header1.h @@ -0,0 +1,6 @@ +#ifndef HEADER1 +#define HEADER1 + +#include "header3.h" + +#endif diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/header2.h b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/header2.h new file mode 100644 index 00000000..c4eddc0c --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/header2.h @@ -0,0 +1,6 @@ +#ifndef HEADER2 +#define HEADER2 + +#include "header3.h" + +#endif diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/header3.h b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/header3.h new file mode 100644 index 00000000..6dca7648 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/header3.h @@ -0,0 +1,3 @@ +// Not a guarded header! + +void f(); diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/hello.cpp b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/hello.cpp new file mode 100644 index 00000000..7ef086e5 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/hello.cpp @@ -0,0 +1,6 @@ +#include "stdio.h" + +int main(int argc, char* argv[]) { + printf("hello world\n"); + return 0; +} diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/include.cpp b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/include.cpp new file mode 100644 index 00000000..60cfdaae --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/include.cpp @@ -0,0 +1,5 @@ +#include "header1.h" +#include "header2.h" +#include "header1.h" + +int main() { } diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/parse_arguments.c b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/parse_arguments.c new file mode 100644 index 00000000..7196486c --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/INPUTS/parse_arguments.c @@ -0,0 +1,2 @@ +int DECL_ONE = 1; +int DECL_TWO = 2; diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/__init__.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_cursor.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_cursor.py new file mode 100644 index 00000000..9f02bb2a --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_cursor.py @@ -0,0 +1,92 @@ +from clang.cindex import CursorKind +from clang.cindex import TypeKind +from .util import get_cursor +from .util import get_tu + +kInput = """\ +// FIXME: Find nicer way to drop builtins and other cruft. +int start_decl; + +struct s0 { + int a; + int b; +}; + +struct s1; + +void f0(int a0, int a1) { + int l0, l1; + + if (a0) + return; + + for (;;) { + break; + } +} +""" + +def test_get_children(): + tu = get_tu(kInput) + + # Skip until past start_decl. + it = tu.cursor.get_children() + while it.next().spelling != 'start_decl': + pass + + tu_nodes = list(it) + + assert len(tu_nodes) == 3 + + assert tu_nodes[0] != tu_nodes[1] + assert tu_nodes[0].kind == CursorKind.STRUCT_DECL + assert tu_nodes[0].spelling == 's0' + assert tu_nodes[0].is_definition() == True + assert tu_nodes[0].location.file.name == 't.c' + assert tu_nodes[0].location.line == 4 + assert tu_nodes[0].location.column == 8 + assert tu_nodes[0].hash > 0 + + s0_nodes = list(tu_nodes[0].get_children()) + assert len(s0_nodes) == 2 + assert s0_nodes[0].kind == CursorKind.FIELD_DECL + assert s0_nodes[0].spelling == 'a' + assert s0_nodes[0].type.kind == TypeKind.INT + assert s0_nodes[1].kind == CursorKind.FIELD_DECL + assert s0_nodes[1].spelling == 'b' + assert s0_nodes[1].type.kind == TypeKind.INT + + assert tu_nodes[1].kind == CursorKind.STRUCT_DECL + assert tu_nodes[1].spelling == 's1' + assert tu_nodes[1].displayname == 's1' + assert tu_nodes[1].is_definition() == False + + assert tu_nodes[2].kind == CursorKind.FUNCTION_DECL + assert tu_nodes[2].spelling == 'f0' + assert tu_nodes[2].displayname == 'f0(int, int)' + assert tu_nodes[2].is_definition() == True + +def test_underlying_type(): + tu = get_tu('typedef int foo;') + typedef = get_cursor(tu, 'foo') + assert typedef is not None + + assert typedef.kind.is_declaration() + underlying = typedef.underlying_typedef_type + assert underlying.kind == TypeKind.INT + +def test_enum_type(): + tu = get_tu('enum TEST { FOO=1, BAR=2 };') + enum = get_cursor(tu, 'TEST') + assert enum is not None + + assert enum.kind == CursorKind.ENUM_DECL + enum_type = enum.enum_type + assert enum_type.kind == TypeKind.UINT + +def test_objc_type_encoding(): + tu = get_tu('int i;', lang='objc') + i = get_cursor(tu, 'i') + + assert i is not None + assert i.objc_type_encoding == 'i' diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_cursor_kind.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_cursor_kind.py new file mode 100644 index 00000000..f8466e5e --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_cursor_kind.py @@ -0,0 +1,40 @@ +from clang.cindex import CursorKind + +def test_name(): + assert CursorKind.UNEXPOSED_DECL.name is 'UNEXPOSED_DECL' + +def test_get_all_kinds(): + assert CursorKind.UNEXPOSED_DECL in CursorKind.get_all_kinds() + assert CursorKind.TRANSLATION_UNIT in CursorKind.get_all_kinds() + +def test_kind_groups(): + """Check that every kind classifies to exactly one group.""" + + assert CursorKind.UNEXPOSED_DECL.is_declaration() + assert CursorKind.TYPE_REF.is_reference() + assert CursorKind.DECL_REF_EXPR.is_expression() + assert CursorKind.UNEXPOSED_STMT.is_statement() + assert CursorKind.INVALID_FILE.is_invalid() + + assert CursorKind.TRANSLATION_UNIT.is_translation_unit() + assert not CursorKind.TYPE_REF.is_translation_unit() + + assert CursorKind.PREPROCESSING_DIRECTIVE.is_preprocessing() + assert not CursorKind.TYPE_REF.is_preprocessing() + + assert CursorKind.UNEXPOSED_DECL.is_unexposed() + assert not CursorKind.TYPE_REF.is_unexposed() + + for k in CursorKind.get_all_kinds(): + group = [n for n in ('is_declaration', 'is_reference', 'is_expression', + 'is_statement', 'is_invalid', 'is_attribute') + if getattr(k, n)()] + + if k in ( CursorKind.TRANSLATION_UNIT, + CursorKind.MACRO_DEFINITION, + CursorKind.MACRO_INSTANTIATION, + CursorKind.INCLUSION_DIRECTIVE, + CursorKind.PREPROCESSING_DIRECTIVE): + assert len(group) == 0 + else: + assert len(group) == 1 diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_diagnostics.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_diagnostics.py new file mode 100644 index 00000000..48ab6176 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_diagnostics.py @@ -0,0 +1,82 @@ +from clang.cindex import * +from .util import get_tu + +# FIXME: We need support for invalid translation units to test better. + +def test_diagnostic_warning(): + tu = get_tu('int f0() {}\n') + assert len(tu.diagnostics) == 1 + assert tu.diagnostics[0].severity == Diagnostic.Warning + assert tu.diagnostics[0].location.line == 1 + assert tu.diagnostics[0].location.column == 11 + assert (tu.diagnostics[0].spelling == + 'control reaches end of non-void function') + +def test_diagnostic_note(): + # FIXME: We aren't getting notes here for some reason. + tu = get_tu('#define A x\nvoid *A = 1;\n') + assert len(tu.diagnostics) == 1 + assert tu.diagnostics[0].severity == Diagnostic.Warning + assert tu.diagnostics[0].location.line == 2 + assert tu.diagnostics[0].location.column == 7 + assert 'incompatible' in tu.diagnostics[0].spelling +# assert tu.diagnostics[1].severity == Diagnostic.Note +# assert tu.diagnostics[1].location.line == 1 +# assert tu.diagnostics[1].location.column == 11 +# assert tu.diagnostics[1].spelling == 'instantiated from' + +def test_diagnostic_fixit(): + tu = get_tu('struct { int f0; } x = { f0 : 1 };') + assert len(tu.diagnostics) == 1 + assert tu.diagnostics[0].severity == Diagnostic.Warning + assert tu.diagnostics[0].location.line == 1 + assert tu.diagnostics[0].location.column == 26 + assert tu.diagnostics[0].spelling.startswith('use of GNU old-style') + assert len(tu.diagnostics[0].fixits) == 1 + assert tu.diagnostics[0].fixits[0].range.start.line == 1 + assert tu.diagnostics[0].fixits[0].range.start.column == 26 + assert tu.diagnostics[0].fixits[0].range.end.line == 1 + assert tu.diagnostics[0].fixits[0].range.end.column == 30 + assert tu.diagnostics[0].fixits[0].value == '.f0 = ' + +def test_diagnostic_range(): + tu = get_tu('void f() { int i = "a" + 1; }') + assert len(tu.diagnostics) == 1 + assert tu.diagnostics[0].severity == Diagnostic.Warning + assert tu.diagnostics[0].location.line == 1 + assert tu.diagnostics[0].location.column == 16 + assert tu.diagnostics[0].spelling.startswith('incompatible pointer to') + assert len(tu.diagnostics[0].fixits) == 0 + assert len(tu.diagnostics[0].ranges) == 1 + assert tu.diagnostics[0].ranges[0].start.line == 1 + assert tu.diagnostics[0].ranges[0].start.column == 20 + assert tu.diagnostics[0].ranges[0].end.line == 1 + assert tu.diagnostics[0].ranges[0].end.column == 27 + try: + tu.diagnostics[0].ranges[1].start.line + except IndexError: + assert True + else: + assert False + +def test_diagnostic_category(): + """Ensure that category properties work.""" + tu = get_tu('int f(int i) { return 7; }', all_warnings=True) + assert len(tu.diagnostics) == 1 + d = tu.diagnostics[0] + + assert d.severity == Diagnostic.Warning + assert d.location.line == 1 + assert d.location.column == 11 + + assert d.category_number == 2 + assert d.category_name == 'Semantic Issue' + +def test_diagnostic_option(): + """Ensure that category option properties work.""" + tu = get_tu('int f(int i) { return 7; }', all_warnings=True) + assert len(tu.diagnostics) == 1 + d = tu.diagnostics[0] + + assert d.option == '-Wunused-parameter' + assert d.disable_option == '-Wno-unused-parameter' diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_file.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_file.py new file mode 100644 index 00000000..146e8c57 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_file.py @@ -0,0 +1,9 @@ +from clang.cindex import Index, File + +def test_file(): + index = Index.create() + tu = index.parse('t.c', unsaved_files = [('t.c', "")]) + file = File.from_name(tu, "t.c") + assert str(file) == "t.c" + assert file.name == "t.c" + assert repr(file) == "" diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_index.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_index.py new file mode 100644 index 00000000..dc173f04 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_index.py @@ -0,0 +1,15 @@ +from clang.cindex import * +import os + +kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS') + +def test_create(): + index = Index.create() + +# FIXME: test Index.read + +def test_parse(): + index = Index.create() + assert isinstance(index, Index) + tu = index.parse(os.path.join(kInputsDir, 'hello.cpp')) + assert isinstance(tu, TranslationUnit) diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_location.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_location.py new file mode 100644 index 00000000..528676ef --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_location.py @@ -0,0 +1,86 @@ +from clang.cindex import Cursor +from clang.cindex import File +from clang.cindex import SourceLocation +from clang.cindex import SourceRange +from .util import get_cursor +from .util import get_tu + +baseInput="int one;\nint two;\n" + +def assert_location(loc, line, column, offset): + assert loc.line == line + assert loc.column == column + assert loc.offset == offset + +def test_location(): + tu = get_tu(baseInput) + one = get_cursor(tu, 'one') + two = get_cursor(tu, 'two') + + assert one is not None + assert two is not None + + assert_location(one.location,line=1,column=5,offset=4) + assert_location(two.location,line=2,column=5,offset=13) + + # adding a linebreak at top should keep columns same + tu = get_tu('\n' + baseInput) + one = get_cursor(tu, 'one') + two = get_cursor(tu, 'two') + + assert one is not None + assert two is not None + + assert_location(one.location,line=2,column=5,offset=5) + assert_location(two.location,line=3,column=5,offset=14) + + # adding a space should affect column on first line only + tu = get_tu(' ' + baseInput) + one = get_cursor(tu, 'one') + two = get_cursor(tu, 'two') + + assert_location(one.location,line=1,column=6,offset=5) + assert_location(two.location,line=2,column=5,offset=14) + + # define the expected location ourselves and see if it matches + # the returned location + tu = get_tu(baseInput) + + file = File.from_name(tu, 't.c') + location = SourceLocation.from_position(tu, file, 1, 5) + cursor = Cursor.from_location(tu, location) + + one = get_cursor(tu, 'one') + assert one is not None + assert one == cursor + + # Ensure locations referring to the same entity are equivalent. + location2 = SourceLocation.from_position(tu, file, 1, 5) + assert location == location2 + location3 = SourceLocation.from_position(tu, file, 1, 4) + assert location2 != location3 + +def test_extent(): + tu = get_tu(baseInput) + one = get_cursor(tu, 'one') + two = get_cursor(tu, 'two') + + assert_location(one.extent.start,line=1,column=1,offset=0) + assert_location(one.extent.end,line=1,column=8,offset=7) + assert baseInput[one.extent.start.offset:one.extent.end.offset] == "int one" + + assert_location(two.extent.start,line=2,column=1,offset=9) + assert_location(two.extent.end,line=2,column=8,offset=16) + assert baseInput[two.extent.start.offset:two.extent.end.offset] == "int two" + + file = File.from_name(tu, 't.c') + location1 = SourceLocation.from_position(tu, file, 1, 1) + location2 = SourceLocation.from_position(tu, file, 1, 8) + + range1 = SourceRange.from_locations(location1, location2) + range2 = SourceRange.from_locations(location1, location2) + assert range1 == range2 + + location3 = SourceLocation.from_position(tu, file, 1, 6) + range3 = SourceRange.from_locations(location1, location3) + assert range1 != range3 diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_translation_unit.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_translation_unit.py new file mode 100644 index 00000000..2e65d951 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_translation_unit.py @@ -0,0 +1,84 @@ +from clang.cindex import * +import os + +kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS') + +def test_spelling(): + path = os.path.join(kInputsDir, 'hello.cpp') + index = Index.create() + tu = index.parse(path) + assert tu.spelling == path + +def test_cursor(): + path = os.path.join(kInputsDir, 'hello.cpp') + index = Index.create() + tu = index.parse(path) + c = tu.cursor + assert isinstance(c, Cursor) + assert c.kind is CursorKind.TRANSLATION_UNIT + +def test_parse_arguments(): + path = os.path.join(kInputsDir, 'parse_arguments.c') + index = Index.create() + tu = index.parse(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi']) + spellings = [c.spelling for c in tu.cursor.get_children()] + assert spellings[-2] == 'hello' + assert spellings[-1] == 'hi' + +def test_reparse_arguments(): + path = os.path.join(kInputsDir, 'parse_arguments.c') + index = Index.create() + tu = index.parse(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi']) + tu.reparse() + spellings = [c.spelling for c in tu.cursor.get_children()] + assert spellings[-2] == 'hello' + assert spellings[-1] == 'hi' + +def test_unsaved_files(): + index = Index.create() + tu = index.parse('fake.c', ['-I./'], unsaved_files = [ + ('fake.c', """ +#include "fake.h" +int x; +int SOME_DEFINE; +"""), + ('./fake.h', """ +#define SOME_DEFINE y +""") + ]) + spellings = [c.spelling for c in tu.cursor.get_children()] + assert spellings[-2] == 'x' + assert spellings[-1] == 'y' + +def test_unsaved_files_2(): + import StringIO + index = Index.create() + tu = index.parse('fake.c', unsaved_files = [ + ('fake.c', StringIO.StringIO('int x;'))]) + spellings = [c.spelling for c in tu.cursor.get_children()] + assert spellings[-1] == 'x' + +def normpaths_equal(path1, path2): + """ Compares two paths for equality after normalizing them with + os.path.normpath + """ + return os.path.normpath(path1) == os.path.normpath(path2) + +def test_includes(): + def eq(expected, actual): + if not actual.is_input_file: + return normpaths_equal(expected[0], actual.source.name) and \ + normpaths_equal(expected[1], actual.include.name) + else: + return normpaths_equal(expected[1], actual.include.name) + + src = os.path.join(kInputsDir, 'include.cpp') + h1 = os.path.join(kInputsDir, "header1.h") + h2 = os.path.join(kInputsDir, "header2.h") + h3 = os.path.join(kInputsDir, "header3.h") + inc = [(src, h1), (h1, h3), (src, h2), (h2, h3)] + + index = Index.create() + tu = index.parse(src) + for i in zip(inc, tu.get_includes()): + assert eq(i[0], i[1]) diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_type.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_type.py new file mode 100644 index 00000000..03621f30 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/test_type.py @@ -0,0 +1,276 @@ +from clang.cindex import CursorKind +from clang.cindex import TypeKind +from nose.tools import raises +from .util import get_cursor +from .util import get_tu + +kInput = """\ + +typedef int I; + +struct teststruct { + int a; + I b; + long c; + unsigned long d; + signed long e; + const int f; + int *g; + int ***h; +}; + +""" + +def test_a_struct(): + tu = get_tu(kInput) + + teststruct = get_cursor(tu, 'teststruct') + assert teststruct is not None, "Could not find teststruct." + fields = list(teststruct.get_children()) + assert all(x.kind == CursorKind.FIELD_DECL for x in fields) + + assert fields[0].spelling == 'a' + assert not fields[0].type.is_const_qualified() + assert fields[0].type.kind == TypeKind.INT + assert fields[0].type.get_canonical().kind == TypeKind.INT + + assert fields[1].spelling == 'b' + assert not fields[1].type.is_const_qualified() + assert fields[1].type.kind == TypeKind.TYPEDEF + assert fields[1].type.get_canonical().kind == TypeKind.INT + assert fields[1].type.get_declaration().spelling == 'I' + + assert fields[2].spelling == 'c' + assert not fields[2].type.is_const_qualified() + assert fields[2].type.kind == TypeKind.LONG + assert fields[2].type.get_canonical().kind == TypeKind.LONG + + assert fields[3].spelling == 'd' + assert not fields[3].type.is_const_qualified() + assert fields[3].type.kind == TypeKind.ULONG + assert fields[3].type.get_canonical().kind == TypeKind.ULONG + + assert fields[4].spelling == 'e' + assert not fields[4].type.is_const_qualified() + assert fields[4].type.kind == TypeKind.LONG + assert fields[4].type.get_canonical().kind == TypeKind.LONG + + assert fields[5].spelling == 'f' + assert fields[5].type.is_const_qualified() + assert fields[5].type.kind == TypeKind.INT + assert fields[5].type.get_canonical().kind == TypeKind.INT + + assert fields[6].spelling == 'g' + assert not fields[6].type.is_const_qualified() + assert fields[6].type.kind == TypeKind.POINTER + assert fields[6].type.get_pointee().kind == TypeKind.INT + + assert fields[7].spelling == 'h' + assert not fields[7].type.is_const_qualified() + assert fields[7].type.kind == TypeKind.POINTER + assert fields[7].type.get_pointee().kind == TypeKind.POINTER + assert fields[7].type.get_pointee().get_pointee().kind == TypeKind.POINTER + assert fields[7].type.get_pointee().get_pointee().get_pointee().kind == TypeKind.INT + +constarrayInput=""" +struct teststruct { + void *A[2]; +}; +""" +def testConstantArray(): + tu = get_tu(constarrayInput) + + teststruct = get_cursor(tu, 'teststruct') + assert teststruct is not None, "Didn't find teststruct??" + fields = list(teststruct.get_children()) + assert fields[0].spelling == 'A' + assert fields[0].type.kind == TypeKind.CONSTANTARRAY + assert fields[0].type.get_array_element_type() is not None + assert fields[0].type.get_array_element_type().kind == TypeKind.POINTER + assert fields[0].type.get_array_size() == 2 + +def test_equal(): + """Ensure equivalence operators work on Type.""" + source = 'int a; int b; void *v;' + tu = get_tu(source) + + a = get_cursor(tu, 'a') + b = get_cursor(tu, 'b') + v = get_cursor(tu, 'v') + + assert a is not None + assert b is not None + assert v is not None + + assert a.type == b.type + assert a.type != v.type + + assert a.type != None + assert a.type != 'foo' + +def test_typekind_spelling(): + """Ensure TypeKind.spelling works.""" + tu = get_tu('int a;') + a = get_cursor(tu, 'a') + + assert a is not None + assert a.type.kind.spelling == 'Int' + +def test_function_argument_types(): + """Ensure that Type.argument_types() works as expected.""" + tu = get_tu('void f(int, int);') + f = get_cursor(tu, 'f') + assert f is not None + + args = f.type.argument_types() + assert args is not None + assert len(args) == 2 + + t0 = args[0] + assert t0 is not None + assert t0.kind == TypeKind.INT + + t1 = args[1] + assert t1 is not None + assert t1.kind == TypeKind.INT + + args2 = list(args) + assert len(args2) == 2 + assert t0 == args2[0] + assert t1 == args2[1] + +@raises(TypeError) +def test_argument_types_string_key(): + """Ensure that non-int keys raise a TypeError.""" + tu = get_tu('void f(int, int);') + f = get_cursor(tu, 'f') + assert f is not None + + args = f.type.argument_types() + assert len(args) == 2 + + args['foo'] + +@raises(IndexError) +def test_argument_types_negative_index(): + """Ensure that negative indexes on argument_types Raises an IndexError.""" + tu = get_tu('void f(int, int);') + f = get_cursor(tu, 'f') + args = f.type.argument_types() + + args[-1] + +@raises(IndexError) +def test_argument_types_overflow_index(): + """Ensure that indexes beyond the length of Type.argument_types() raise.""" + tu = get_tu('void f(int, int);') + f = get_cursor(tu, 'f') + args = f.type.argument_types() + + args[2] + +@raises(Exception) +def test_argument_types_invalid_type(): + """Ensure that obtaining argument_types on a Type without them raises.""" + tu = get_tu('int i;') + i = get_cursor(tu, 'i') + assert i is not None + + i.type.argument_types() + +def test_is_pod(): + """Ensure Type.is_pod() works.""" + tu = get_tu('int i; void f();') + i = get_cursor(tu, 'i') + f = get_cursor(tu, 'f') + + assert i is not None + assert f is not None + + assert i.type.is_pod() + assert not f.type.is_pod() + +def test_function_variadic(): + """Ensure Type.is_function_variadic works.""" + + source =""" +#include + +void foo(int a, ...); +void bar(int a, int b); +""" + + tu = get_tu(source) + foo = get_cursor(tu, 'foo') + bar = get_cursor(tu, 'bar') + + assert foo is not None + assert bar is not None + + assert isinstance(foo.type.is_function_variadic(), bool) + assert foo.type.is_function_variadic() + assert not bar.type.is_function_variadic() + +def test_element_type(): + """Ensure Type.element_type works.""" + tu = get_tu('int i[5];') + i = get_cursor(tu, 'i') + assert i is not None + + assert i.type.kind == TypeKind.CONSTANTARRAY + assert i.type.element_type.kind == TypeKind.INT + +@raises(Exception) +def test_invalid_element_type(): + """Ensure Type.element_type raises if type doesn't have elements.""" + tu = get_tu('int i;') + i = get_cursor(tu, 'i') + assert i is not None + i.element_type + +def test_element_count(): + """Ensure Type.element_count works.""" + tu = get_tu('int i[5]; int j;') + i = get_cursor(tu, 'i') + j = get_cursor(tu, 'j') + + assert i is not None + assert j is not None + + assert i.type.element_count == 5 + + try: + j.type.element_count + assert False + except: + assert True + +def test_is_volatile_qualified(): + """Ensure Type.is_volatile_qualified works.""" + + tu = get_tu('volatile int i = 4; int j = 2;') + + i = get_cursor(tu, 'i') + j = get_cursor(tu, 'j') + + assert i is not None + assert j is not None + + assert isinstance(i.type.is_volatile_qualified(), bool) + assert i.type.is_volatile_qualified() + assert not j.type.is_volatile_qualified() + +def test_is_restrict_qualified(): + """Ensure Type.is_restrict_qualified works.""" + + tu = get_tu('struct s { void * restrict i; void * j };') + + i = get_cursor(tu, 'i') + j = get_cursor(tu, 'j') + + assert i is not None + assert j is not None + + assert isinstance(i.type.is_restrict_qualified(), bool) + assert i.type.is_restrict_qualified() + assert not j.type.is_restrict_qualified() diff --git a/cpp/llvm/tools/clang/bindings/python/tests/cindex/util.py b/cpp/llvm/tools/clang/bindings/python/tests/cindex/util.py new file mode 100644 index 00000000..388b2694 --- /dev/null +++ b/cpp/llvm/tools/clang/bindings/python/tests/cindex/util.py @@ -0,0 +1,65 @@ +# This file provides common utility functions for the test suite. + +from clang.cindex import Cursor +from clang.cindex import Index + +def get_tu(source, lang='c', all_warnings=False): + """Obtain a translation unit from source and language. + + By default, the translation unit is created from source file "t." + where is the default file extension for the specified language. By + default it is C, so "t.c" is the default file name. + + Supported languages are {c, cpp, objc}. + + all_warnings is a convenience argument to enable all compiler warnings. + """ + name = 't.c' + if lang == 'cpp': + name = 't.cpp' + elif lang == 'objc': + name = 't.m' + elif lang != 'c': + raise Exception('Unknown language: %s' % lang) + + args = [] + if all_warnings: + args = ['-Wall', '-Wextra'] + + index = Index.create() + tu = index.parse(name, args=args, unsaved_files=[(name, source)]) + assert tu is not None + return tu + +def get_cursor(source, spelling): + """Obtain a cursor from a source object. + + This provides a convenient search mechanism to find a cursor with specific + spelling within a source. The first argument can be either a + TranslationUnit or Cursor instance. + + If the cursor is not found, None is returned. + """ + children = [] + if isinstance(source, Cursor): + children = source.get_children() + else: + # Assume TU + children = source.cursor.get_children() + + for cursor in children: + if cursor.spelling == spelling: + return cursor + + # Recurse into children. + result = get_cursor(cursor, spelling) + if result is not None: + return result + + return None + + +__all__ = [ + 'get_cursor', + 'get_tu', +] diff --git a/cpp/llvm/tools/clang/docs/AddressSanitizer.html b/cpp/llvm/tools/clang/docs/AddressSanitizer.html new file mode 100644 index 00000000..c1dc91bf --- /dev/null +++ b/cpp/llvm/tools/clang/docs/AddressSanitizer.html @@ -0,0 +1,139 @@ + + + + + + AddressSanitizer, a fast memory error detector + + + + + + + + +
+ +

AddressSanitizer

+ + +

Introduction

+AddressSanitizer is a fast memory error detector. +It consists of a compiler instrumentation module and a run-time library. +The tool can detect the following types of bugs: +
  • Out-of-bounds accesses to heap, stack and globals +
  • Use-after-free +
  • Use-after-return (to some extent) +
  • Double-free, invalid free +
+Typical slowdown introduced by AddressSanitizer is 2x. + +

How to build

+Follow the clang build instructions.
+Note: CMake build does not work yet. +See bug 12272. + +

Usage

+Simply compile and link your program with -faddress-sanitizer flag.
+To get a reasonable performance add -O1 or higher.
+To get nicer stack traces in error messages add +-fno-omit-frame-pointer.
+To get perfect stack traces you may need to disable inlining (just use -O1) and tail call +elimination (-fno-optimize-sibling-calls). + +
+% cat example_UseAfterFree.cc
+int main(int argc, char **argv) {
+  int *array = new int[100];
+  delete [] array;
+  return array[argc];  // BOOM
+}
+
+ +
+% clang -O1 -g -faddress-sanitizer -fno-omit-frame-pointer example_UseAfterFree.cc
+
+ +If a bug is detected, the program will print an error message to stderr and exit with a +non-zero exit code. +Currently, AddressSanitizer does not symbolize its output, so you may need to use a +separate script to symbolize the result offline (this will be fixed in future). +
+% ./a.out 2> log
+% projects/compiler-rt/lib/asan/scripts/asan_symbolize.py / < log | c++filt
+==9442== ERROR: AddressSanitizer heap-use-after-free on address 0x7f7ddab8c084 at pc 0x403c8c bp 0x7fff87fb82d0 sp 0x7fff87fb82c8
+READ of size 4 at 0x7f7ddab8c084 thread T0
+    #0 0x403c8c in main example_UseAfterFree.cc:4
+    #1 0x7f7ddabcac4d in __libc_start_main ??:0
+0x7f7ddab8c084 is located 4 bytes inside of 400-byte region [0x7f7ddab8c080,0x7f7ddab8c210)
+freed by thread T0 here:
+    #0 0x404704 in operator delete[](void*) ??:0
+    #1 0x403c53 in main example_UseAfterFree.cc:4
+    #2 0x7f7ddabcac4d in __libc_start_main ??:0
+previously allocated by thread T0 here:
+    #0 0x404544 in operator new[](unsigned long) ??:0
+    #1 0x403c43 in main example_UseAfterFree.cc:2
+    #2 0x7f7ddabcac4d in __libc_start_main ??:0
+==9442== ABORTING
+
+ +

__has_feature(address_sanitizer)

+In some cases one may need to execute different code depending on whether +AddressSanitizer is enabled. +__has_feature +can be used for this purpose. +
+#if defined(__has_feature) && __has_feature(address_sanitizer)
+  code that runs only under AddressSanitizer
+#else
+  code that does not run under AddressSanitizer
+#endif
+
+ +

Supported Platforms

+AddressSanitizer is supported on +
  • Linux x86_64 (tested on Ubuntu 10.04). +
  • MacOS 10.6 i386/x86_64. +
+Support for Linux i386/ARM and MacOS 10.7 is in progress +(it may work, but is not guaranteed too). + + +

Limitations

+
    +
  • AddressSanitizer uses more real memory than a native run. + How much -- depends on the allocations sizes. The smaller the + allocations you make the bigger the overhead. +
  • On 64-bit platforms AddressSanitizer maps (but not reserves) + 16+ Terabytes of virtual address space. + This means that tools like ulimit may not work as usually expected. +
  • Static linking is not supported. +
+ + +

Current Status

+AddressSanitizer is fully functional on supported platforms in LLVM head. +However, the test suite is not fully integrated yet and we lack the testing +process (buildbots). + +

More Information

+http://code.google.com/p/address-sanitizer. + + +
+ + diff --git a/cpp/llvm/tools/clang/docs/AnalyzerRegions.html b/cpp/llvm/tools/clang/docs/AnalyzerRegions.html new file mode 100644 index 00000000..f9d33379 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/AnalyzerRegions.html @@ -0,0 +1,260 @@ + + + +Static Analyzer Design Document: Memory Regions + + + +

Static Analyzer Design Document: Memory Regions

+ +

Authors

+ +

Ted Kremenek, kremenek at apple
+Zhongxing Xu, xuzhongzhing at gmail

+ +

Introduction

+ +

The path-sensitive analysis engine in libAnalysis employs an extensible API +for abstractly modeling the memory of an analyzed program. This API employs the +concept of "memory regions" to abstractly model chunks of program memory such as +program variables and dynamically allocated memory such as those returned from +'malloc' and 'alloca'. Regions are hierarchical, with subregions modeling +subtyping relationships, field and array offsets into larger chunks of memory, +and so on.

+ +

The region API consists of two components:

+ +
  • A taxonomy and representation of regions themselves within the analyzer +engine. The primary definitions and interfaces are described in MemRegion.h. +At the root of the region hierarchy is the class MemRegion with +specific subclasses refining the region concept for variables, heap allocated +memory, and so forth.
  • The modeling of binding of values to regions. For +example, modeling the value stored to a local variable x consists of +recording the binding between the region for x (which represents the +raw memory associated with x) and the value stored to x. This +binding relationship is captured with the notion of "symbolic +stores."
+ +

Symbolic stores, which can be thought of as representing the relation +regions -> values, are implemented by subclasses of the +StoreManager class (Store.h). A +particular StoreManager implementation has complete flexibility concerning the +following: + +

    +
  • How to model the binding between regions and values
  • +
  • What bindings are recorded +
+ +

Together, both points allow different StoreManagers to tradeoff between +different levels of analysis precision and scalability concerning the reasoning +of program memory. Meanwhile, the core path-sensitive engine makes no +assumptions about either points, and queries a StoreManager about the bindings +to a memory region through a generic interface that all StoreManagers share. If +a particular StoreManager cannot reason about the potential bindings of a given +memory region (e.g., 'BasicStoreManager' does not reason about fields +of structures) then the StoreManager can simply return 'unknown' (represented by +'UnknownVal') for a particular region-binding. This separation of +concerns not only isolates the core analysis engine from the details of +reasoning about program memory but also facilities the option of a client of the +path-sensitive engine to easily swap in different StoreManager implementations +that internally reason about program memory in very different ways.

+ +

The rest of this document is divided into two parts. We first discuss region +taxonomy and the semantics of regions. We then discuss the StoreManager +interface, and details of how the currently available StoreManager classes +implement region bindings.

+ +

Memory Regions and Region Taxonomy

+ +

Pointers

+ +

Before talking about the memory regions, we would talk about the pointers +since memory regions are essentially used to represent pointer values.

+ +

The pointer is a type of values. Pointer values have two semantic aspects. +One is its physical value, which is an address or location. The other is the +type of the memory object residing in the address.

+ +

Memory regions are designed to abstract these two properties of the pointer. +The physical value of a pointer is represented by MemRegion pointers. The rvalue +type of the region corresponds to the type of the pointee object.

+ +

One complication is that we could have different view regions on the same +memory chunk. They represent the same memory location, but have different +abstract location, i.e., MemRegion pointers. Thus we need to canonicalize the +abstract locations to get a unique abstract location for one physical +location.

+ +

Furthermore, these different view regions may or may not represent memory +objects of different types. Some different types are semantically the same, +for example, 'struct s' and 'my_type' are the same type.

+ +
+struct s;
+typedef struct s my_type;
+
+ +

But char and int are not the same type in the code below:

+ +
+void *p;
+int *q = (int*) p;
+char *r = (char*) p;
+
+ +

Thus we need to canonicalize the MemRegion which is used in binding and +retrieving.

+ +

Regions

+

Region is the entity used to model pointer values. A Region has the following +properties:

+ +
    +
  • Kind
  • + +
  • ObjectType: the type of the object residing on the region.
  • + +
  • LocationType: the type of the pointer value that the region corresponds to. + Usually this is the pointer to the ObjectType. But sometimes we want to cache + this type explicitly, for example, for a CodeTextRegion.
  • + +
  • StartLocation
  • + +
  • EndLocation
  • +
+ +

Symbolic Regions

+ +

A symbolic region is a map of the concept of symbolic values into the domain +of regions. It is the way that we represent symbolic pointers. Whenever a +symbolic pointer value is needed, a symbolic region is created to represent +it.

+ +

A symbolic region has no type. It wraps a SymbolData. But sometimes we have +type information associated with a symbolic region. For this case, a +TypedViewRegion is created to layer the type information on top of the symbolic +region. The reason we do not carry type information with the symbolic region is +that the symbolic regions can have no type. To be consistent, we don't let them +to carry type information.

+ +

Like a symbolic pointer, a symbolic region may be NULL, has unknown extent, +and represents a generic chunk of memory.

+ +

NOTE: We plan not to use loc::SymbolVal in RegionStore and remove it + gradually.

+ +

Symbolic regions get their rvalue types through the following ways:

+ +
    +
  • Through the parameter or global variable that points to it, e.g.: +
    +void f(struct s* p) {
    +  ...
    +}
    +
    + +

    The symbolic region pointed to by p has type struct +s.

  • + +
  • Through explicit or implicit casts, e.g.: +
    +void f(void* p) {
    +  struct s* q = (struct s*) p;
    +  ...
    +}
    +
    +
  • +
+ +

We attach the type information to the symbolic region lazily. For the first +case above, we create the TypedViewRegion only when the pointer is +actually used to access the pointee memory object, that is when the element or +field region is created. For the cast case, the TypedViewRegion is +created when visiting the CastExpr.

+ +

The reason for doing lazy typing is that symbolic regions are sometimes only +used to do location comparison.

+ +

Pointer Casts

+ +

Pointer casts allow people to impose different 'views' onto a chunk of +memory.

+ +

Usually we have two kinds of casts. One kind of casts cast down with in the +type hierarchy. It imposes more specific views onto more generic memory regions. +The other kind of casts cast up with in the type hierarchy. It strips away more +specific views on top of the more generic memory regions.

+ +

We simulate the down casts by layering another TypedViewRegion on +top of the original region. We simulate the up casts by striping away the top +TypedViewRegion. Down casts is usually simple. For up casts, if the +there is no TypedViewRegion to be stripped, we return the original +region. If the underlying region is of the different type than the cast-to type, +we flag an error state.

+ +

For toll-free bridging casts, we return the original region.

+ +

We can set up a partial order for pointer types, with the most general type +void* at the top. The partial order forms a tree with void* as +its root node.

+ +

Every MemRegion has a root position in the type tree. For example, +the pointee region of void *p has its root position at the root node of +the tree. VarRegion of int x has its root position at the 'int +type' node.

+ +

TypedViewRegion is used to move the region down or up in the tree. +Moving down in the tree adds a TypedViewRegion. Moving up in the tree +removes a TypedViewRegion.

+ +

Do we want to allow moving up beyond the root position? This happens +when:

 int x; void *p = &x; 
+ +

The region of x has its root position at 'int*' node. the cast to +void* moves that region up to the 'void*' node. I propose to not allow such +casts, and assign the region of x for p.

+ +

Another non-ideal case is that people might cast to a non-generic pointer +from another non-generic pointer instead of first casting it back to the generic +pointer. Direct handling of this case would result in multiple layers of +TypedViewRegions. This enforces an incorrect semantic view to the region, +because we can only have one typed view on a region at a time. To avoid this +inconsistency, before casting the region, we strip the TypedViewRegion, then do +the cast. In summary, we only allow one layer of TypedViewRegion.

+ +

Region Bindings

+ +

The following region kinds are boundable: VarRegion, CompoundLiteralRegion, +StringRegion, ElementRegion, FieldRegion, and ObjCIvarRegion.

+ +

When binding regions, we perform canonicalization on element regions and field +regions. This is because we can have different views on the same region, some +of which are essentially the same view with different sugar type names.

+ +

To canonicalize a region, we get the canonical types for all TypedViewRegions +along the way up to the root region, and make new TypedViewRegions with those +canonical types.

+ +

For Objective-C and C++, perhaps another canonicalization rule should be +added: for FieldRegion, the least derived class that has the field is used as +the type of the super region of the FieldRegion.

+ +

All bindings and retrievings are done on the canonicalized regions.

+ +

Canonicalization is transparent outside the region store manager, and more +specifically, unaware outside the Bind() and Retrieve() method. We don't need to +consider region canonicalization when doing pointer cast.

+ +

Constraint Manager

+ +

The constraint manager reasons about the abstract location of memory objects. +We can have different views on a region, but none of these views changes the +location of that object. Thus we should get the same abstract location for those +regions.

+ + + diff --git a/cpp/llvm/tools/clang/docs/AutomaticReferenceCounting.html b/cpp/llvm/tools/clang/docs/AutomaticReferenceCounting.html new file mode 100644 index 00000000..1416df58 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/AutomaticReferenceCounting.html @@ -0,0 +1,2187 @@ + + + +Objective-C Automatic Reference Counting (ARC) + + + + + + + + + + +
+

Automatic Reference Counting

+ +
+
+ +
+

About this document

+ +
+

Purpose

+ +

The first and primary purpose of this document is to serve as a +complete technical specification of Automatic Reference Counting. +Given a core Objective-C compiler and runtime, it should be possible +to write a compiler and runtime which implements these new +semantics.

+ +

The secondary purpose is to act as a rationale for why ARC was +designed in this way. This should remain tightly focused on the +technical design and should not stray into marketing speculation.

+ +
+ +
+

Background

+ +

This document assumes a basic familiarity with C.

+ +

Blocks are a C language extension for +creating anonymous functions. Users interact with and transfer block +objects using block pointers, which are +represented like a normal pointer. A block may capture values from +local variables; when this occurs, memory must be dynamically +allocated. The initial allocation is done on the stack, but the +runtime provides a Block_copy function which, given a block +pointer, either copies the underlying block object to the heap, +setting its reference count to 1 and returning the new block pointer, +or (if the block object is already on the heap) increases its +reference count by 1. The paired function is Block_release, +which decreases the reference count by 1 and destroys the object if +the count reaches zero and is on the heap.

+ +

Objective-C is a set of language extensions, significant enough to +be considered a different language. It is a strict superset of C. +The extensions can also be imposed on C++, producing a language called +Objective-C++. The primary feature is a single-inheritance object +system; we briefly describe the modern dialect.

+ +

Objective-C defines a new type kind, collectively called +the object pointer types. This kind has two +notable builtin members, id and Class; id +is the final supertype of all object pointers. The validity of +conversions between object pointer types is not checked at runtime. +Users may define classes; each class is a +type, and the pointer to that type is an object pointer type. A class +may have a superclass; its pointer type is a subtype of its +superclass's pointer type. A class has a set +of ivars, fields which appear on all +instances of that class. For every class T there's an +associated metaclass; it has no fields, its superclass is the +metaclass of T's superclass, and its metaclass is a global +class. Every class has a global object whose class is the +class's metaclass; metaclasses have no associated type, so pointers to +this object have type Class.

+ +

A class declaration (@interface) declares a set +of methods. A method has a return type, a +list of argument types, and a selector: a +name like foo:bar:baz:, where the number of colons +corresponds to the number of formal arguments. A method may be an +instance method, in which case it can be invoked on objects of the +class, or a class method, in which case it can be invoked on objects +of the metaclass. A method may be invoked by providing an object +(called the receiver) and a list of formal +arguments interspersed with the selector, like so:

+ +
[receiver foo: fooArg bar: barArg baz: bazArg]
+ +

This looks in the dynamic class of the receiver for a method with +this name, then in that class's superclass, etc., until it finds +something it can execute. The receiver expression may also be +the name of a class, in which case the actual receiver is the class +object for that class, or (within method definitions) it may +be super, in which case the lookup algorithm starts with the +static superclass instead of the dynamic class. The actual methods +dynamically found in a class are not those declared in the +@interface, but those defined in a separate +@implementation declaration; however, when compiling a +call, typechecking is done based on the methods declared in the +@interface.

+ +

Method declarations may also be grouped into +protocols, which are not inherently +associated with any class, but which classes may claim to follow. +Object pointer types may be qualified with additional protocols that +the object is known to support.

+ +

Class extensions are collections of ivars +and methods, designed to allow a class's @interface to be +split across multiple files; however, there is still a primary +implementation file which must see the @interfaces of all +class extensions. +Categories allow methods (but not ivars) to +be declared post hoc on an arbitrary class; the methods in the +category's @implementation will be dynamically added to that +class's method tables which the category is loaded at runtime, +replacing those methods in case of a collision.

+ +

In the standard environment, objects are allocated on the heap, and +their lifetime is manually managed using a reference count. This is +done using two instance methods which all classes are expected to +implement: retain increases the object's reference count by +1, whereas release decreases it by 1 and calls the instance +method dealloc if the count reaches 0. To simplify certain +operations, there is also an autorelease +pool, a thread-local list of objects to call release +on later; an object can be added to this pool by +calling autorelease on it.

+ +

Block pointers may be converted to type id; block objects +are laid out in a way that makes them compatible with Objective-C +objects. There is a builtin class that all block objects are +considered to be objects of; this class implements retain by +adjusting the reference count, not by calling Block_copy.

+ +
+ +
+

Evolution

+ +

ARC is under continual evolution, and this document must be updated +as the language progresses.

+ +

If a change increases the expressiveness of the language, for +example by lifting a restriction or by adding new syntax, the change +will be annotated with a revision marker, like so:

+ +
+ ARC applies to Objective-C pointer types, block pointer types, and + [beginning Apple + 8.0, LLVM 3.8] BPTRs declared within extern + "BCPL" blocks. +
+ +

For now, it is sensible to version this document by the releases of +its sole implementation (and its host project), clang. +LLVM X.Y refers to an open-source release of clang from the +LLVM project. Apple X.Y refers to an Apple-provided release of +the Apple LLVM Compiler. Other organizations that prepare their own, +separately-versioned clang releases and wish to maintain similar +information in this document should send requests to cfe-dev.

+ +

If a change decreases the expressiveness of the language, for +example by imposing a new restriction, this should be taken as an +oversight in the original specification and something to be avoided +in all versions. Such changes are generally to be avoided.

+ +
+ +
+ +
+

General

+ +

Automatic Reference Counting implements automatic memory management +for Objective-C objects and blocks, freeing the programmer from the +need to explicitly insert retains and releases. It does not provide a +cycle collector; users must explicitly manage the lifetime of their +objects, breaking cycles manually or with weak or unsafe +references.

+ +

ARC may be explicitly enabled with the compiler +flag -fobjc-arc. It may also be explicitly disabled with the +compiler flag -fno-objc-arc. The last of these two flags +appearing on the compile line wins.

+ +

If ARC is enabled, __has_feature(objc_arc) will expand to +1 in the preprocessor. For more information about __has_feature, +see the language +extensions document.

+ +
+ +
+

Retainable object pointers

+ +

This section describes retainable object pointers, their basic +operations, and the restrictions imposed on their use under ARC. Note +in particular that it covers the rules for pointer values +(patterns of bits indicating the location of a pointed-to object), not +pointer +objects (locations in memory which store pointer values). +The rules for objects are covered in the next section.

+ +

A retainable object pointer +(or retainable pointer) is a value of +a retainable object pointer type +(retainable type). There are three kinds of retainable object +pointer types:

+
    +
  • block pointers (formed by applying the caret (^) +declarator sigil to a function type)
  • +
  • Objective-C object pointers (id, Class, NSFoo*, etc.)
  • +
  • typedefs marked with __attribute__((NSObject))
  • +
+ +

Other pointer types, such as int* and CFStringRef, +are not subject to ARC's semantics and restrictions.

+ +
+ +

Rationale: We are not at liberty to require +all code to be recompiled with ARC; therefore, ARC must interoperate +with Objective-C code which manages retains and releases manually. In +general, there are three requirements in order for a +compiler-supported reference-count system to provide reliable +interoperation:

+ +
    +
  • The type system must reliably identify which objects are to be +managed. An int* might be a pointer to a malloc'ed +array, or it might be a interior pointer to such an array, or it might +point to some field or local variable. In contrast, values of the +retainable object pointer types are never interior.
  • +
  • The type system must reliably indicate how to +manage objects of a type. This usually means that the type must imply +a procedure for incrementing and decrementing retain counts. +Supporting single-ownership objects requires a lot more explicit +mediation in the language.
  • +
  • There must be reliable conventions for whether and +when ownership is passed between caller and callee, for both +arguments and return values. Objective-C methods follow such a +convention very reliably, at least for system libraries on Mac OS X, +and functions always pass objects at +0. The C-based APIs for Core +Foundation objects, on the other hand, have much more varied transfer +semantics.
  • +
+
+ +

The use of __attribute__((NSObject)) typedefs is not +recommended. If it's absolutely necessary to use this attribute, be +very explicit about using the typedef, and do not assume that it will +be preserved by language features like __typeof and C++ +template argument substitution.

+ +

Rationale: any compiler operation which +incidentally strips type sugar from a type will yield a type +without the attribute, which may result in unexpected +behavior.

+ +
+

Retain count semantics

+ +

A retainable object pointer is either a null +pointer or a pointer to a valid object. Furthermore, if it has +block pointer type and is not null then it must actually be a +pointer to a block object, and if it has Class type (possibly +protocol-qualified) then it must actually be a pointer to a class +object. Otherwise ARC does not enforce the Objective-C type system as +long as the implementing methods follow the signature of the static +type. It is undefined behavior if ARC is exposed to an invalid +pointer.

+ +

For ARC's purposes, a valid object is one with well-behaved +retaining operations. Specifically, the object must be laid out such +that the Objective-C message send machinery can successfully send it +the following messages:

+ +
    +
  • retain, taking no arguments and returning a pointer to +the object.
  • +
  • release, taking no arguments and returning void.
  • +
  • autorelease, taking no arguments and returning a pointer +to the object.
  • +
+ +

The behavior of these methods is constrained in the following ways. +The term high-level semantics is an +intentionally vague term; the intent is that programmers must +implement these methods in a way such that the compiler, modifying +code in ways it deems safe according to these constraints, will not +violate their requirements. For example, if the user puts logging +statements in retain, they should not be surprised if those +statements are executed more or less often depending on optimization +settings. These constraints are not exhaustive of the optimization +opportunities: values held in local variables are subject to +additional restrictions, described later in this document.

+ +

It is undefined behavior if a computation history featuring a send +of retain followed by a send of release to the same +object, with no intervening release on that object, is not +equivalent under the high-level semantics to a computation +history in which these sends are removed. Note that this implies that +these methods may not raise exceptions.

+ +

It is undefined behavior if a computation history features any use +whatsoever of an object following the completion of a send +of release that is not preceded by a send of retain +to the same object.

+ +

The behavior of autorelease must be equivalent to sending +release when one of the autorelease pools currently in scope +is popped. It may not throw an exception.

+ +

When the semantics call for performing one of these operations on a +retainable object pointer, if that pointer is null then the +effect is a no-op.

+ +

All of the semantics described in this document are subject to +additional optimization rules which permit +the removal or optimization of operations based on local knowledge of +data flow. The semantics describe the high-level behaviors that the +compiler implements, not an exact sequence of operations that a +program will be compiled into.

+ +
+ +
+

Retainable object pointers as operands and arguments

+ +

In general, ARC does not perform retain or release operations when +simply using a retainable object pointer as an operand within an +expression. This includes:

+
    +
  • loading a retainable pointer from an object with non-weak +ownership,
  • +
  • passing a retainable pointer as an argument to a function or +method, and
  • +
  • receiving a retainable pointer as the result of a function or +method call.
  • +
+ +

Rationale: while this might seem +uncontroversial, it is actually unsafe when multiple expressions are +evaluated in parallel, as with binary operators and calls, +because (for example) one expression might load from an object while +another writes to it. However, C and C++ already call this undefined +behavior because the evaluations are unsequenced, and ARC simply +exploits that here to avoid needing to retain arguments across a large +number of calls.

+ +

The remainder of this section describes exceptions to these rules, +how those exceptions are detected, and what those exceptions imply +semantically.

+ +
+

Consumed parameters

+ +

A function or method parameter of retainable object pointer type +may be marked as consumed, signifying that +the callee expects to take ownership of a +1 retain count. This is +done by adding the ns_consumed attribute to the parameter +declaration, like so:

+ +
void foo(__attribute((ns_consumed)) id x);
+- (void) foo: (id) __attribute((ns_consumed)) x;
+ +

This attribute is part of the type of the function or method, not +the type of the parameter. It controls only how the argument is +passed and received.

+ +

When passing such an argument, ARC retains the argument prior to +making the call.

+ +

When receiving such an argument, ARC releases the argument at the +end of the function, subject to the usual optimizations for local +values.

+ +

Rationale: this formalizes direct transfers +of ownership from a caller to a callee. The most common scenario here +is passing the self parameter to init, but it is +useful to generalize. Typically, local optimization will remove any +extra retains and releases: on the caller side the retain will be +merged with a +1 source, and on the callee side the release will be +rolled into the initialization of the parameter.

+ +

The implicit self parameter of a method may be marked as +consumed by adding __attribute__((ns_consumes_self)) to the +method declaration. Methods in the init +family are treated as if they were implicitly +marked with this attribute.

+ +

It is undefined behavior if an Objective-C message send to a method +with ns_consumed parameters (other than self) is made with a +null receiver. It is undefined behavior if the method to which an +Objective-C message send statically resolves to has a different set +of ns_consumed parameters than the method it dynamically +resolves to. It is undefined behavior if a block or function call is +made through a static type with a different set of ns_consumed +parameters than the implementation of the called block or function.

+ +

Rationale: consumed parameters with null +receiver are a guaranteed leak. Mismatches with consumed parameters +will cause over-retains or over-releases, depending on the direction. +The rule about function calls is really just an application of the +existing C/C++ rule about calling functions through an incompatible +function type, but it's useful to state it explicitly.

+ +
+ +
+

Retained return values

+ +

A function or method which returns a retainable object pointer type +may be marked as returning a retained value, signifying that the +caller expects to take ownership of a +1 retain count. This is done +by adding the ns_returns_retained attribute to the function or +method declaration, like so:

+ +
id foo(void) __attribute((ns_returns_retained));
+- (id) foo __attribute((ns_returns_retained));
+ +

This attribute is part of the type of the function or method.

+ +

When returning from such a function or method, ARC retains the +value at the point of evaluation of the return statement, before +leaving all local scopes.

+ +

When receiving a return result from such a function or method, ARC +releases the value at the end of the full-expression it is contained +within, subject to the usual optimizations for local values.

+ +

Rationale: this formalizes direct transfers of +ownership from a callee to a caller. The most common scenario this +models is the retained return from init, alloc, +new, and copy methods, but there are other cases in +the frameworks. After optimization there are typically no extra +retains and releases required.

+ +

Methods in +the alloc, copy, init, mutableCopy, +and new families are implicitly marked +__attribute__((ns_returns_retained)). This may be suppressed +by explicitly marking the +method __attribute__((ns_returns_not_retained)).

+ +

It is undefined behavior if the method to which an Objective-C +message send statically resolves has different retain semantics on its +result from the method it dynamically resolves to. It is undefined +behavior if a block or function call is made through a static type +with different retain semantics on its result from the implementation +of the called block or function.

+ +

Rationale: Mismatches with returned results +will cause over-retains or over-releases, depending on the direction. +Again, the rule about function calls is really just an application of +the existing C/C++ rule about calling functions through an +incompatible function type.

+ +
+ +
+

Unretained return values

+ +

A method or function which returns a retainable object type but +does not return a retained value must ensure that the object is +still valid across the return boundary.

+ +

When returning from such a function or method, ARC retains the +value at the point of evaluation of the return statement, then leaves +all local scopes, and then balances out the retain while ensuring that +the value lives across the call boundary. In the worst case, this may +involve an autorelease, but callers must not assume that the +value is actually in the autorelease pool.

+ +

ARC performs no extra mandatory work on the caller side, although +it may elect to do something to shorten the lifetime of the returned +value.

+ +

Rationale: it is common in non-ARC code to not +return an autoreleased value; therefore the convention does not force +either path. It is convenient to not be required to do unnecessary +retains and autoreleases; this permits optimizations such as eliding +retain/autoreleases when it can be shown that the original pointer +will still be valid at the point of return.

+ +

A method or function may be marked +with __attribute__((ns_returns_autoreleased)) to indicate +that it returns a pointer which is guaranteed to be valid at least as +long as the innermost autorelease pool. There are no additional +semantics enforced in the definition of such a method; it merely +enables optimizations in callers.

+ +
+ +
+

Bridged casts

+ +

A bridged cast is a C-style cast +annotated with one of three keywords:

+ +
    +
  • (__bridge T) op casts the operand to the destination +type T. If T is a retainable object pointer type, +then op must have a non-retainable pointer type. +If T is a non-retainable pointer type, then op must +have a retainable object pointer type. Otherwise the cast is +ill-formed. There is no transfer of ownership, and ARC inserts +no retain operations.
  • + +
  • (__bridge_retained T) op casts the operand, which must +have retainable object pointer type, to the destination type, which +must be a non-retainable pointer type. ARC retains the value, subject +to the usual optimizations on local values, and the recipient is +responsible for balancing that +1.
  • + +
  • (__bridge_transfer T) op casts the operand, which must +have non-retainable pointer type, to the destination type, which must +be a retainable object pointer type. ARC will release the value at +the end of the enclosing full-expression, subject to the usual +optimizations on local values.
  • +
+ +

These casts are required in order to transfer objects in and out of +ARC control; see the rationale in the section +on conversion of retainable +object pointers.

+ +

Using a __bridge_retained or __bridge_transfer +cast purely to convince ARC to emit an unbalanced retain or release, +respectively, is poor form.

+ +
+ +
+ +
+

Restrictions

+ +
+

Conversion of retainable object pointers

+ +

In general, a program which attempts to implicitly or explicitly +convert a value of retainable object pointer type to any +non-retainable type, or vice-versa, is ill-formed. For example, an +Objective-C object pointer shall not be converted to void*. +As an exception, cast to intptr_t is allowed because such +casts are not transferring ownership. The bridged +casts may be used to perform these conversions where +necessary.

+ +

Rationale: we cannot ensure the correct +management of the lifetime of objects if they may be freely passed +around as unmanaged types. The bridged casts are provided so that the +programmer may explicitly describe whether the cast transfers control +into or out of ARC.

+ +

However, the following exceptions apply.

+ +
+ +
+

Conversion to retainable object pointer type of + expressions with known semantics

+ +

[beginning Apple + 4.0, LLVM 3.1] These exceptions have been greatly expanded; + they previously applied only to a much-reduced subset which is + difficult to categorize but which included null pointers, message + sends (under the given rules), and the various global constants.

+ +

An unbridged conversion to a retainable object pointer type from a +type other than a retainable object pointer type is ill-formed, as +discussed above, unless the operand of the cast has a syntactic form +which is known retained, known unretained, or known +retain-agnostic.

+ +

An expression is known retain-agnostic if +it is:

+
    +
  • an Objective-C string literal,
  • +
  • a load from a const system global variable of +C retainable pointer type, or
  • +
  • a null pointer constant.
  • +
+ +

An expression is known unretained if it +is an rvalue of C retainable +pointer type and it is:

+
    +
  • a direct call to a function, and either that function has the + cf_returns_not_retained attribute or it is an + audited function that does not + have the cf_returns_retained attribute and does not follow + the create/copy naming convention,
  • +
  • a message send, and the declared method either has + the cf_returns_not_retained attribute or it has neither + the cf_returns_retained attribute nor a + selector family that implies a retained + result.
  • +
+ +

An expression is known retained if it is +an rvalue of C retainable pointer type +and it is:

+
    +
  • a message send, and the declared method either has the + cf_returns_retained attribute, or it does not have + the cf_returns_not_retained attribute but it does have a + selector family that implies a retained + result.
  • +
+ +

Furthermore:

+
    +
  • a comma expression is classified according to its right-hand side,
  • +
  • a statement expression is classified according to its result +expression, if it has one,
  • +
  • an lvalue-to-rvalue conversion applied to an Objective-C property +lvalue is classified according to the underlying message send, and
  • +
  • a conditional operator is classified according to its second and +third operands, if they agree in classification, or else the other +if one is known retain-agnostic.
  • +
+ +

If the cast operand is known retained, the conversion is treated as +a __bridge_transfer cast. If the cast operand is known +unretained or known retain-agnostic, the conversion is treated as +a __bridge cast.

+ +

Rationale: Bridging casts are annoying. +Absent the ability to completely automate the management of CF +objects, however, we are left with relatively poor attempts to reduce +the need for a glut of explicit bridges. Hence these rules.

+ +

We've so far consciously refrained from implicitly turning retained +CF results from function calls into __bridge_transfer casts. +The worry is that some code patterns — for example, creating a +CF value, assigning it to an ObjC-typed local, and then +calling CFRelease when done — are a bit too likely to +be accidentally accepted, leading to mysterious behavior.

+ +
+ +
+

Conversion from retainable object pointer type in certain contexts

+ +

[beginning Apple + 4.0, LLVM 3.1]

+ +

If an expression of retainable object pointer type is explicitly +cast to a C retainable pointer type, +the program is ill-formed as discussed above unless the result is +immediately used:

+ +
    +
  • to initialize a parameter in an Objective-C message send where the +parameter is not marked with the cf_consumed attribute, or
  • +
  • to initialize a parameter in a direct call to +an audited function where the +parameter is not marked with the cf_consumed attribute.
  • +
+ +

Rationale: Consumed parameters are left out +because ARC would naturally balance them with a retain, which was +judged too treacherous. This is in part because several of the most +common consuming functions are in the Release family, and it +would be quite unfortunate for explicit releases to be silently +balanced out in this way.

+ +
+ +
+ +
+ +
+

Ownership qualification

+ +

This section describes the behavior of objects of +retainable object pointer type; that is, locations in memory which +store retainable object pointers.

+ +

A type is a retainable object owner type +if it is a retainable object pointer type or an array type whose +element type is a retainable object owner type.

+ +

An ownership qualifier is a type +qualifier which applies only to retainable object owner types. An array type is +ownership-qualified according to its element type, and adding an ownership +qualifier to an array type so qualifies its element type.

+ +

A program is ill-formed if it attempts to apply an ownership qualifier +to a type which is already ownership-qualified, even if it is the same +qualifier. There is a single exception to this rule: an ownership qualifier +may be applied to a substituted template type parameter, which overrides the +ownership qualifier provided by the template argument.

+ +

Except as described under +the inference rules, a program is +ill-formed if it attempts to form a pointer or reference type to a +retainable object owner type which lacks an ownership qualifier.

+ +

Rationale: these rules, together with the +inference rules, ensure that all objects and lvalues of retainable +object pointer type have an ownership qualifier. The ability to override an ownership qualifier during template substitution is required to counteract the inference of __strong for template type arguments.

+ +

There are four ownership qualifiers:

+ +
    +
  • __autoreleasing
  • +
  • __strong
  • +
  • __unsafe_unretained
  • +
  • __weak
  • +
+ +

A type is nontrivially ownership-qualified +if it is qualified with __autoreleasing, __strong, or +__weak.

+ +
+

Spelling

+ +

The names of the ownership qualifiers are reserved for the +implementation. A program may not assume that they are or are not +implemented with macros, or what those macros expand to.

+ +

An ownership qualifier may be written anywhere that any other type +qualifier may be written.

+ +

If an ownership qualifier appears in +the declaration-specifiers, the following rules apply:

+ +
    +
  • if the type specifier is a retainable object owner type, the +qualifier applies to that type;
  • +
  • if the outermost non-array part of the declarator is a pointer or +block pointer, the qualifier applies to that type;
  • +
  • otherwise the program is ill-formed.
  • +
+ +

If an ownership qualifier appears on the declarator name, or on the +declared object, it is applied to outermost pointer or block-pointer +type.

+ +

If an ownership qualifier appears anywhere else in a declarator, it +applies to the type there.

+ +
+

Property declarations

+ +

A property of retainable object pointer type may have ownership. +If the property's type is ownership-qualified, then the property has +that ownership. If the property has one of the following modifiers, +then the property has the corresponding ownership. A property is +ill-formed if it has conflicting sources of ownership, or if it has +redundant ownership modifiers, or if it has __autoreleasing +ownership.

+ +
    +
  • assign implies __unsafe_unretained ownership.
  • +
  • copy implies __strong ownership, as well as the + usual behavior of copy semantics on the setter.
  • +
  • retain implies __strong ownership.
  • +
  • strong implies __strong ownership.
  • +
  • unsafe_unretained implies __unsafe_unretained + ownership.
  • +
  • weak implies __weak ownership.
  • +
+ +

With the exception of weak, these modifiers are available +in non-ARC modes.

+ +

A property's specified ownership is preserved in its metadata, but +otherwise the meaning is purely conventional unless the property is +synthesized. If a property is synthesized, then the +associated instance variable is the +instance variable which is named, possibly implicitly, by the +@synthesize declaration. If the associated instance variable +already exists, then its ownership qualification must equal the +ownership of the property; otherwise, the instance variable is created +with that ownership qualification.

+ +

A property of retainable object pointer type which is synthesized +without a source of ownership has the ownership of its associated +instance variable, if it already exists; otherwise, +[beginning Apple 3.1, +LLVM 3.1] its ownership is implicitly strong. +Prior to this revision, it was ill-formed to synthesize such a +property.

+ +

Rationale: using strong by default +is safe and consistent with the generic ARC rule about +inferring ownership. It +is, unfortunately, inconsistent with the non-ARC rule which states +that such properties are implicitly assign. However, that +rule is clearly untenable in ARC, since it leads to default-unsafe +code. The main merit to banning the properties is to avoid confusion +with non-ARC practice, which did not ultimately strike us as +sufficient to justify requiring extra syntax and (more importantly) +forcing novices to understand ownership rules just to declare a +property when the default is so reasonable. Changing the rule away +from non-ARC practice was acceptable because we had conservatively +banned the synthesis in order to give ourselves exactly this +leeway.

+ +
+ +
+ +
+

Semantics

+ +

There are five managed operations which +may be performed on an object of retainable object pointer type. Each +qualifier specifies different semantics for each of these operations. +It is still undefined behavior to access an object outside of its +lifetime.

+ +

A load or store with primitive semantics has the same +semantics as the respective operation would have on an void* +lvalue with the same alignment and non-ownership qualification.

+ +

Reading occurs when performing a +lvalue-to-rvalue conversion on an object lvalue.

+ +
    +
  • For __weak objects, the current pointee is retained and +then released at the end of the current full-expression. This must +execute atomically with respect to assignments and to the final +release of the pointee.
  • +
  • For all other objects, the lvalue is loaded with primitive +semantics.
  • +
+ +

Assignment occurs when evaluating +an assignment operator. The semantics vary based on the qualification:

+
    +
  • For __strong objects, the new pointee is first retained; +second, the lvalue is loaded with primitive semantics; third, the new +pointee is stored into the lvalue with primitive semantics; and +finally, the old pointee is released. This is not performed +atomically; external synchronization must be used to make this safe in +the face of concurrent loads and stores.
  • +
  • For __weak objects, the lvalue is updated to point to the +new pointee, unless the new pointee is an object currently undergoing +deallocation, in which case the lvalue is updated to a null pointer. +This must execute atomically with respect to other assignments to the +object, to reads from the object, and to the final release of the new +pointee.
  • +
  • For __unsafe_unretained objects, the new pointee is +stored into the lvalue using primitive semantics.
  • +
  • For __autoreleasing objects, the new pointee is retained, +autoreleased, and stored into the lvalue using primitive semantics.
  • +
+ +

Initialization occurs when an object's +lifetime begins, which depends on its storage duration. +Initialization proceeds in two stages:

+
    +
  1. First, a null pointer is stored into the lvalue using primitive +semantics. This step is skipped if the object +is __unsafe_unretained.
  2. +
  3. Second, if the object has an initializer, that expression is +evaluated and then assigned into the object using the usual assignment +semantics.
  4. +
+ +

Destruction occurs when an object's +lifetime ends. In all cases it is semantically equivalent to +assigning a null pointer to the object, with the proviso that of +course the object cannot be legally read after the object's lifetime +ends.

+ +

Moving occurs in specific situations +where an lvalue is moved from, meaning that its current pointee +will be used but the object may be left in a different (but still +valid) state. This arises with __block variables and rvalue +references in C++. For __strong lvalues, moving is equivalent +to loading the lvalue with primitive semantics, writing a null pointer +to it with primitive semantics, and then releasing the result of the +load at the end of the current full-expression. For all other +lvalues, moving is equivalent to reading the object.

+ +
+ +
+

Restrictions

+ +
+

Weak-unavailable types

+ +

It is explicitly permitted for Objective-C classes to not +support __weak references. It is undefined behavior to +perform an operation with weak assignment semantics with a pointer to +an Objective-C object whose class does not support __weak +references.

+ +

Rationale: historically, it has been +possible for a class to provide its own reference-count implementation +by overriding retain, release, etc. However, weak +references to an object require coordination with its class's +reference-count implementation because, among other things, weak loads +and stores must be atomic with respect to the final release. +Therefore, existing custom reference-count implementations will +generally not support weak references without additional effort. This +is unavoidable without breaking binary compatibility.

+ +

A class may indicate that it does not support weak references by +providing the objc_arc_weak_unavailable attribute on the +class's interface declaration. A retainable object pointer type +is weak-unavailable if is a pointer to an +(optionally protocol-qualified) Objective-C class T +where T or one of its superclasses has +the objc_arc_weak_unavailable attribute. A program is +ill-formed if it applies the __weak ownership qualifier to a +weak-unavailable type or if the value operand of a weak assignment +operation has a weak-unavailable type.

+
+ +
+

Storage duration of __autoreleasing objects

+ +

A program is ill-formed if it declares an __autoreleasing +object of non-automatic storage duration. A program is ill-formed +if it captures an __autoreleasing object in a block or, +unless by reference, in a C++11 lambda.

+ +

Rationale: autorelease pools are tied to the +current thread and scope by their nature. While it is possible to +have temporary objects whose instance variables are filled with +autoreleased objects, there is no way that ARC can provide any sort of +safety guarantee there.

+ +

It is undefined behavior if a non-null pointer is assigned to +an __autoreleasing object while an autorelease pool is in +scope and then that object is read after the autorelease pool's scope +is left.

+ +
+ +
+

Conversion of pointers to ownership-qualified types

+ +

A program is ill-formed if an expression of type T* is +converted, explicitly or implicitly, to the type U*, +where T and U have different ownership +qualification, unless:

+
    +
  • T is qualified with __strong, + __autoreleasing, or __unsafe_unretained, and + U is qualified with both const and + __unsafe_unretained; or
  • +
  • either T or U is cv void, where +cv is an optional sequence of non-ownership qualifiers; or
  • +
  • the conversion is requested with a reinterpret_cast in + Objective-C++; or
  • +
  • the conversion is a +well-formed pass-by-writeback.
  • +
+ +

The analogous rule applies to T& and U& in +Objective-C++.

+ +

Rationale: these rules provide a reasonable +level of type-safety for indirect pointers, as long as the underlying +memory is not deallocated. The conversion to const +__unsafe_unretained is permitted because the semantics of reads +are equivalent across all these ownership semantics, and that's a very +useful and common pattern. The interconversion with void* is +useful for allocating memory or otherwise escaping the type system, +but use it carefully. reinterpret_cast is considered to be +an obvious enough sign of taking responsibility for any +problems.

+ +

It is undefined behavior to access an ownership-qualified object +through an lvalue of a differently-qualified type, except that any +non-__weak object may be read through +an __unsafe_unretained lvalue.

+ +

It is undefined behavior if a managed operation is performed on +a __strong or __weak object without a guarantee that +it contains a primitive zero bit-pattern, or if the storage for such +an object is freed or reused without the object being first assigned a +null pointer.

+ +

Rationale: ARC cannot differentiate between +an assignment operator which is intended to initialize dynamic +memory and one which is intended to potentially replace a value. +Therefore the object's pointer must be valid before letting ARC at it. +Similarly, C and Objective-C do not provide any language hooks for +destroying objects held in dynamic memory, so it is the programmer's +responsibility to avoid leaks (__strong objects) and +consistency errors (__weak objects).

+ +

These requirements are followed automatically in Objective-C++ when +creating objects of retainable object owner type with new +or new[] and destroying them with delete, +delete[], or a pseudo-destructor expression. Note that +arrays of nontrivially-ownership-qualified type are not ABI compatible +with non-ARC code because the element type is non-POD: such arrays +that are new[]'d in ARC translation units cannot +be delete[]'d in non-ARC translation units and +vice-versa.

+ +
+ +
+

Passing to an out parameter by writeback

+ +

If the argument passed to a parameter of type +T __autoreleasing * has type U oq *, +where oq is an ownership qualifier, then the argument is a +candidate for pass-by-writeback if:

+ +
    +
  • oq is __strong or __weak, and
  • +
  • it would be legal to initialize a T __strong * with +a U __strong *.
  • +
+ +

For purposes of overload resolution, an implicit conversion +sequence requiring a pass-by-writeback is always worse than an +implicit conversion sequence not requiring a pass-by-writeback.

+ +

The pass-by-writeback is ill-formed if the argument expression does +not have a legal form:

+ +
    +
  • &var, where var is a scalar variable of +automatic storage duration with retainable object pointer type
  • +
  • a conditional expression where the second and third operands are +both legal forms
  • +
  • a cast whose operand is a legal form
  • +
  • a null pointer constant
  • +
+ +

Rationale: the restriction in the form of +the argument serves two purposes. First, it makes it impossible to +pass the address of an array to the argument, which serves to protect +against an otherwise serious risk of mis-inferring an array +argument as an out-parameter. Second, it makes it much less likely +that the user will see confusing aliasing problems due to the +implementation, below, where their store to the writeback temporary is +not immediately seen in the original argument variable.

+ +

A pass-by-writeback is evaluated as follows:

+
    +
  1. The argument is evaluated to yield a pointer p of + type U oq *.
  2. +
  3. If p is a null pointer, then a null pointer is passed as + the argument, and no further work is required for the pass-by-writeback.
  4. +
  5. Otherwise, a temporary of type T __autoreleasing is + created and initialized to a null pointer.
  6. +
  7. If the parameter is not an Objective-C method parameter marked + out, then *p is read, and the result is written + into the temporary with primitive semantics.
  8. +
  9. The address of the temporary is passed as the argument to the + actual call.
  10. +
  11. After the call completes, the temporary is loaded with primitive + semantics, and that value is assigned into *p.
  12. +
+ +

Rationale: this is all admittedly +convoluted. In an ideal world, we would see that a local variable is +being passed to an out-parameter and retroactively modify its type to +be __autoreleasing rather than __strong. This would +be remarkably difficult and not always well-founded under the C type +system. However, it was judged unacceptably invasive to require +programmers to write __autoreleasing on all the variables +they intend to use for out-parameters. This was the least bad +solution.

+ +
+ +
+

Ownership-qualified fields of structs and unions

+ +

A program is ill-formed if it declares a member of a C struct or +union to have a nontrivially ownership-qualified type.

+ +

Rationale: the resulting type would be +non-POD in the C++ sense, but C does not give us very good language +tools for managing the lifetime of aggregates, so it is more +convenient to simply forbid them. It is still possible to manage this +with a void* or an __unsafe_unretained +object.

+ +

This restriction does not apply in Objective-C++. However, +nontrivally ownership-qualified types are considered non-POD: in C++11 +terms, they are not trivially default constructible, copy +constructible, move constructible, copy assignable, move assignable, +or destructible. It is a violation of C++'s One Definition Rule to use +a class outside of ARC that, under ARC, would have a nontrivially +ownership-qualified member.

+ +

Rationale: unlike in C, we can express all +the necessary ARC semantics for ownership-qualified subobjects as +suboperations of the (default) special member functions for the class. +These functions then become non-trivial. This has the non-obvious +result that the class will have a non-trivial copy constructor and +non-trivial destructor; if this would not normally be true outside of +ARC, objects of the type will be passed and returned in an +ABI-incompatible manner.

+ +
+ +
+ +
+

Ownership inference

+ +
+

Objects

+ +

If an object is declared with retainable object owner type, but +without an explicit ownership qualifier, its type is implicitly +adjusted to have __strong qualification.

+ +

As a special case, if the object's base type is Class +(possibly protocol-qualified), the type is adjusted to +have __unsafe_unretained qualification instead.

+ +
+ +
+

Indirect parameters

+ +

If a function or method parameter has type T*, where +T is an ownership-unqualified retainable object pointer type, +then:

+ +
    +
  • if T is const-qualified or Class, then +it is implicitly qualified with __unsafe_unretained;
  • +
  • otherwise, it is implicitly qualified +with __autoreleasing.
  • +
+ +

Rationale: __autoreleasing exists +mostly for this case, the Cocoa convention for out-parameters. Since +a pointer to const is obviously not an out-parameter, we +instead use a type more useful for passing arrays. If the user +instead intends to pass in a mutable array, inferring +__autoreleasing is the wrong thing to do; this directs some +of the caution in the following rules about writeback.

+ +

Such a type written anywhere else would be ill-formed by the +general rule requiring ownership qualifiers.

+ +

This rule does not apply in Objective-C++ if a parameter's type is +dependent in a template pattern and is only instantiated to +a type which would be a pointer to an unqualified retainable object +pointer type. Such code is still ill-formed.

+ +

Rationale: the convention is very unlikely +to be intentional in template code.

+ +
+ +
+

Template arguments

+ +

If a template argument for a template type parameter is an +retainable object owner type that does not have an explicit ownership +qualifier, it is adjusted to have __strong +qualification. This adjustment occurs regardless of whether the +template argument was deduced or explicitly specified.

+ +

Rationale: __strong is a useful default for containers (e.g., std::vector<id>), which would otherwise require explicit qualification. Moreover, unqualified retainable object pointer types are unlikely to be useful within templates, since they generally need to have a qualifier applied to the before being used.

+ +
+
+
+ + +
+

Method families

+ +

An Objective-C method may fall into a method +family, which is a conventional set of behaviors ascribed to it +by the Cocoa conventions.

+ +

A method is in a certain method family if:

+
    +
  • it has a objc_method_family attribute placing it in that + family; or if not that,
  • +
  • it does not have an objc_method_family attribute placing + it in a different or no family, and
  • +
  • its selector falls into the corresponding selector family, and
  • +
  • its signature obeys the added restrictions of the method family.
  • +
+ +

A selector is in a certain selector family if, ignoring any leading +underscores, the first component of the selector either consists +entirely of the name of the method family or it begins with that name +followed by a character other than a lowercase letter. For +example, _perform:with: and performWith: would fall +into the perform family (if we recognized one), +but performing:with would not.

+ +

The families and their added restrictions are:

+ +
    +
  • alloc methods must return a retainable object pointer type.
  • +
  • copy methods must return a retainable object pointer type.
  • +
  • mutableCopy methods must return a retainable object pointer type.
  • +
  • new methods must return a retainable object pointer type.
  • +
  • init methods must be instance methods and must return an +Objective-C pointer type. Additionally, a program is ill-formed if it +declares or contains a call to an init method whose return +type is neither id nor a pointer to a super-class or +sub-class of the declaring class (if the method was declared on +a class) or the static receiver type of the call (if it was declared +on a protocol). + +

    Rationale: there are a fair number of existing +methods with init-like selectors which nonetheless don't +follow the init conventions. Typically these are either +accidental naming collisions or helper methods called during +initialization. Because of the peculiar retain/release behavior +of init methods, it's very important not to treat these +methods as init methods if they aren't meant to be. It was +felt that implicitly defining these methods out of the family based on +the exact relationship between the return type and the declaring class +would be much too subtle and fragile. Therefore we identify a small +number of legitimate-seeming return types and call everything else an +error. This serves the secondary purpose of encouraging programmers +not to accidentally give methods names in the init family.

    + +

    Note that a method with an init-family selector which +returns a non-Objective-C type (e.g. void) is perfectly +well-formed; it simply isn't in the init family.

    +
  • +
+ +

A program is ill-formed if a method's declarations, +implementations, and overrides do not all have the same method +family.

+ +
+

Explicit method family control

+ +

A method may be annotated with the objc_method_family +attribute to precisely control which method family it belongs to. If +a method in an @implementation does not have this attribute, +but there is a method declared in the corresponding @interface +that does, then the attribute is copied to the declaration in the +@implementation. The attribute is available outside of ARC, +and may be tested for with the preprocessor query +__has_attribute(objc_method_family).

+ +

The attribute is spelled +__attribute__((objc_method_family(family))). +If family is none, the method has no family, even if +it would otherwise be considered to have one based on its selector and +type. Otherwise, family must be one +of alloc, copy, init, +mutableCopy, or new, in which case the method is +considered to belong to the corresponding family regardless of its +selector. It is an error if a method that is explicitly added to a +family in this way does not meet the requirements of the family other +than the selector naming convention.

+ +

Rationale: the rules codified in this document +describe the standard conventions of Objective-C. However, as these +conventions have not heretofore been enforced by an unforgiving +mechanical system, they are only imperfectly kept, especially as they +haven't always even been precisely defined. While it is possible to +define low-level ownership semantics with attributes like +ns_returns_retained, this attribute allows the user to +communicate semantic intent, which is of use both to ARC (which, e.g., +treats calls to init specially) and the static analyzer.

+
+ +
+

Semantics of method families

+ +

A method's membership in a method family may imply non-standard +semantics for its parameters and return type.

+ +

Methods in the alloc, copy, mutableCopy, +and new families — that is, methods in all the +currently-defined families except init — implicitly +return a retained +object as if they were annotated with +the ns_returns_retained attribute. This can be overridden by +annotating the method with either of +the ns_returns_autoreleased or +ns_returns_not_retained attributes.

+ +

Properties also follow same naming rules as methods. This means that +those in the alloc, copy, mutableCopy, +and new families provide access to +retained objects. +This can be overridden by annotating the property with +ns_returns_not_retained attribute.

+ +
+

Semantics of init

+

Methods in the init family implicitly +consume their self +parameter and return a +retained object. Neither of these properties can be altered +through attributes.

+ +

A call to an init method with a receiver that is either +self (possibly parenthesized or casted) or super is +called a delegate init call. It is an error +for a delegate init call to be made except from an init +method, and excluding blocks within such methods.

+ +

As an exception to the usual rule, the +variable self is mutable in an init method and has +the usual semantics for a __strong variable. However, it is +undefined behavior and the program is ill-formed, no diagnostic +required, if an init method attempts to use the previous +value of self after the completion of a delegate init call. +It is conventional, but not required, for an init method to +return self.

+ +

It is undefined behavior for a program to cause two or more calls +to init methods on the same object, except that +each init method invocation may perform at most one delegate +init call.

+ +
+ +
+

Related result types

+ +

Certain methods are candidates to have related +result types:

+
    +
  • class methods in the alloc and new method families
  • +
  • instance methods in the init family
  • +
  • the instance method self
  • +
  • outside of ARC, the instance methods retain and autorelease
  • +
+ +

If the formal result type of such a method is id or +protocol-qualified id, or a type equal to the declaring class +or a superclass, then it is said to have a related result type. In +this case, when invoked in an explicit message send, it is assumed to +return a type related to the type of the receiver:

+ +
    +
  • if it is a class method, and the receiver is a class +name T, the message send expression has type T*; +otherwise
  • +
  • if it is an instance method, and the receiver has type T, +the message send expression has type T; otherwise
  • +
  • the message send expression has the normal result type of the +method.
  • +
+ +

This is a new rule of the Objective-C language and applies outside +of ARC.

+ +

Rationale: ARC's automatic code emission is +more prone than most code to signature errors, i.e. errors where a +call was emitted against one method signature, but the implementing +method has an incompatible signature. Having more precise type +information helps drastically lower this risk, as well as catching +a number of latent bugs.

+ +
+
+
+ +
+

Optimization

+ +

ARC applies aggressive rules for the optimization of local +behavior. These rules are based around a core assumption of +local balancing: that other code will +perform retains and releases as necessary (and only as necessary) for +its own safety, and so the optimizer does not need to consider global +properties of the retain and release sequence. For example, if a +retain and release immediately bracket a call, the optimizer can +delete the retain and release on the assumption that the called +function will not do a constant number of unmotivated releases +followed by a constant number of balancing retains, such that +the local retain/release pair is the only thing preventing the called +function from ending up with a dangling reference.

+ +

The optimizer assumes that when a new value enters local control, +e.g. from a load of a non-local object or as the result of a function +call, it is instaneously valid. Subsequently, a retain and release of +a value are necessary on a computation path only if there is a use of +that value before the release and after any operation which might +cause a release of the value (including indirectly or non-locally), +and only if the value is not demonstrably already retained.

+ +

The complete optimization rules are quite complicated, but it would +still be useful to document them here.

+ +
+

Precise lifetime semantics

+ +

In general, ARC maintains an invariant that a retainable object +pointer held in a __strong object will be retained for the +full formal lifetime of the object. Objects subject to this invariant +have precise lifetime semantics.

+ +

By default, local variables of automatic storage duration do not +have precise lifetime semantics. Such objects are simply strong +references which hold values of retainable object pointer type, and +these values are still fully subject to the optimizations on values +under local control.

+ +

Rationale: applying these precise-lifetime +semantics strictly would be prohibitive. Many useful optimizations +that might theoretically decrease the lifetime of an object would be +rendered impossible. Essentially, it promises too much.

+ +

A local variable of retainable object owner type and automatic +storage duration may be annotated with the objc_precise_lifetime +attribute to indicate that it should be considered to be an object +with precise lifetime semantics.

+ +

Rationale: nonetheless, it is sometimes +useful to be able to force an object to be released at a precise time, +even if that object does not appear to be used. This is likely to be +uncommon enough that the syntactic weight of explicitly requesting +these semantics will not be burdensome, and may even make the code +clearer.

+ +
+ +
+ +
+

Miscellaneous

+ +
+

Special methods

+ +
+

Memory management methods

+ +

A program is ill-formed if it contains a method definition, message +send, or @selector expression for any of the following +selectors:

+
    +
  • autorelease
  • +
  • release
  • +
  • retain
  • +
  • retainCount
  • +
+ +

Rationale: retainCount is banned +because ARC robs it of consistent semantics. The others were banned +after weighing three options for how to deal with message sends:

+ +

Honoring them would work out very poorly if a programmer +naively or accidentally tried to incorporate code written for manual +retain/release code into an ARC program. At best, such code would do +twice as much work as necessary; quite frequently, however, ARC and +the explicit code would both try to balance the same retain, leading +to crashes. The cost is losing the ability to perform unrooted +retains, i.e. retains not logically corresponding to a strong +reference in the object graph.

+ +

Ignoring them would badly violate user expectations about their +code. While it would make it easier to develop code simultaneously +for ARC and non-ARC, there is very little reason to do so except for +certain library developers. ARC and non-ARC translation units share +an execution model and can seamlessly interoperate. Within a +translation unit, a developer who faithfully maintains their code in +non-ARC mode is suffering all the restrictions of ARC for zero +benefit, while a developer who isn't testing the non-ARC mode is +likely to be unpleasantly surprised if they try to go back to it.

+ +

Banning them has the disadvantage of making it very awkward +to migrate existing code to ARC. The best answer to that, given a +number of other changes and restrictions in ARC, is to provide a +specialized tool to assist users in that migration.

+ +

Implementing these methods was banned because they are too integral +to the semantics of ARC; many tricks which worked tolerably under +manual reference counting will misbehave if ARC performs an ephemeral +extra retain or two. If absolutely required, it is still possible to +implement them in non-ARC code, for example in a category; the +implementations must obey the semantics +laid out elsewhere in this document.

+ +
+
+ +
+

dealloc

+ +

A program is ill-formed if it contains a message send +or @selector expression for the selector dealloc.

+ +

Rationale: there are no legitimate reasons +to call dealloc directly.

+ +

A class may provide a method definition for an instance method +named dealloc. This method will be called after the final +release of the object but before it is deallocated or any of +its instance variables are destroyed. The superclass's implementation +of dealloc will be called automatically when the method +returns.

+ +

Rationale: even though ARC destroys instance +variables automatically, there are still legitimate reasons to write +a dealloc method, such as freeing non-retainable resources. +Failing to call [super dealloc] in such a method is nearly +always a bug. Sometimes, the object is simply trying to prevent +itself from being destroyed, but dealloc is really far too +late for the object to be raising such objections. Somewhat more +legitimately, an object may have been pool-allocated and should not be +deallocated with free; for now, this can only be supported +with a dealloc implementation outside of ARC. Such an +implementation must be very careful to do all the other work +that NSObject's dealloc would, which is outside the +scope of this document to describe.

+ +
+ +
+ +
+

@autoreleasepool

+ +

To simplify the use of autorelease pools, and to bring them under +the control of the compiler, a new kind of statement is available in +Objective-C. It is written @autoreleasepool followed by +a compound-statement, i.e. by a new scope delimited by curly +braces. Upon entry to this block, the current state of the +autorelease pool is captured. When the block is exited normally, +whether by fallthrough or directed control flow (such +as return or break), the autorelease pool is +restored to the saved state, releasing all the objects in it. When +the block is exited with an exception, the pool is not drained.

+ +

@autoreleasepool may be used in non-ARC translation units, +with equivalent semantics.

+ +

A program is ill-formed if it refers to the +NSAutoreleasePool class.

+ +

Rationale: autorelease pools are clearly +important for the compiler to reason about, but it is far too much to +expect the compiler to accurately reason about control dependencies +between two calls. It is also very easy to accidentally forget to +drain an autorelease pool when using the manual API, and this can +significantly inflate the process's high-water-mark. The introduction +of a new scope is unfortunate but basically required for sane +interaction with the rest of the language. Not draining the pool +during an unwind is apparently required by the Objective-C exceptions +implementation.

+ +
+ +
+

self

+ +

The self parameter variable of an Objective-C method is +never actually retained by the implementation. It is undefined +behavior, or at least dangerous, to cause an object to be deallocated +during a message send to that object.

+ +

To make this safe, for Objective-C instance methods self is +implicitly const unless the method is in the init family. Further, self +is always implicitly const within a class method.

+ +

Rationale: the cost of +retaining self in all methods was found to be prohibitive, as +it tends to be live across calls, preventing the optimizer from +proving that the retain and release are unnecessary — for good +reason, as it's quite possible in theory to cause an object to be +deallocated during its execution without this retain and release. +Since it's extremely uncommon to actually do so, even unintentionally, +and since there's no natural way for the programmer to remove this +retain/release pair otherwise (as there is for other parameters by, +say, making the variable __unsafe_unretained), we chose to +make this optimizing assumption and shift some amount of risk to the +user.

+ +
+ +
+

Fast enumeration iteration variables

+ +

If a variable is declared in the condition of an Objective-C fast +enumeration loop, and the variable has no explicit ownership +qualifier, then it is qualified with const __strong and +objects encountered during the enumeration are not actually +retained.

+ +

Rationale: this is an optimization made +possible because fast enumeration loops promise to keep the objects +retained during enumeration, and the collection itself cannot be +synchronously modified. It can be overridden by explicitly qualifying +the variable with __strong, which will make the variable +mutable again and cause the loop to retain the objects it +encounters.

+ +
+ +
+

Blocks

+ +

The implicit const capture variables created when +evaluating a block literal expression have the same ownership +semantics as the local variables they capture. The capture is +performed by reading from the captured variable and initializing the +capture variable with that value; the capture variable is destroyed +when the block literal is, i.e. at the end of the enclosing scope.

+ +

The inference rules apply +equally to __block variables, which is a shift in semantics +from non-ARC, where __block variables did not implicitly +retain during capture.

+ +

__block variables of retainable object owner type are +moved off the stack by initializing the heap copy with the result of +moving from the stack copy.

+ +

With the exception of retains done as part of initializing +a __strong parameter variable or reading a __weak +variable, whenever these semantics call for retaining a value of +block-pointer type, it has the effect of a Block_copy. The +optimizer may remove such copies when it sees that the result is +used only as an argument to a call.

+ +
+ +
+

Exceptions

+ +

By default in Objective C, ARC is not exception-safe for normal +releases:

+
    +
  • It does not end the lifetime of __strong variables when +their scopes are abnormally terminated by an exception.
  • +
  • It does not perform releases which would occur at the end of +a full-expression if that full-expression throws an exception.
  • +
+ +

A program may be compiled with the option +-fobjc-arc-exceptions in order to enable these, or with the +option -fno-objc-arc-exceptions to explicitly disable them, +with the last such argument winning.

+ +

Rationale: the standard Cocoa convention is +that exceptions signal programmer error and are not intended to be +recovered from. Making code exceptions-safe by default would impose +severe runtime and code size penalties on code that typically does not +actually care about exceptions safety. Therefore, ARC-generated code +leaks by default on exceptions, which is just fine if the process is +going to be immediately terminated anyway. Programs which do care +about recovering from exceptions should enable the option.

+ +

In Objective-C++, -fobjc-arc-exceptions is enabled by +default.

+ +

Rationale: C++ already introduces pervasive +exceptions-cleanup code of the sort that ARC introduces. C++ +programmers who have not already disabled exceptions are much more +likely to actual require exception-safety.

+ +

ARC does end the lifetimes of __weak objects when an +exception terminates their scope unless exceptions are disabled in the +compiler.

+ +

Rationale: the consequence of a +local __weak object not being destroyed is very likely to be +corruption of the Objective-C runtime, so we want to be safer here. +Of course, potentially massive leaks are about as likely to take down +the process as this corruption is if the program does try to recover +from exceptions.

+ +
+ +
+

Interior pointers

+ +

An Objective-C method returning a non-retainable pointer may be +annotated with the objc_returns_inner_pointer attribute to +indicate that it returns a handle to the internal data of an object, +and that this reference will be invalidated if the object is +destroyed. When such a message is sent to an object, the object's +lifetime will be extended until at least the earliest of:

+ +
    +
  • the last use of the returned pointer, or any pointer derived from +it, in the calling function or
  • +
  • the autorelease pool is restored to a previous state.
  • +
+ +

Rationale: not all memory and resources are +managed with reference counts; it is common for objects to manage +private resources in their own, private way. Typically these +resources are completely encapsulated within the object, but some +classes offer their users direct access for efficiency. If ARC is not +aware of methods that return such interior pointers, its +optimizations can cause the owning object to be reclaimed too soon. +This attribute informs ARC that it must tread lightly.

+ +

The extension rules are somewhat intentionally vague. The +autorelease pool limit is there to permit a simple implementation to +simply retain and autorelease the receiver. The other limit permits +some amount of optimization. The phrase derived from is +intended to encompass the results both of pointer transformations, +such as casts and arithmetic, and of loading from such derived +pointers; furthermore, it applies whether or not such derivations are +applied directly in the calling code or by other utility code (for +example, the C library routine strchr). However, the +implementation never need account for uses after a return from the +code which calls the method returning an interior pointer.

+ +

As an exception, no extension is required if the receiver is loaded +directly from a __strong object +with precise lifetime semantics.

+ +

Rationale: implicit autoreleases carry the +risk of significantly inflating memory use, so it's important to +provide users a way of avoiding these autoreleases. Tying this to +precise lifetime semantics is ideal, as for local variables this +requires a very explicit annotation, which allows ARC to trust the +user with good cheer.

+ +
+ +
+

C retainable pointer types

+ +

A type is a C retainable pointer type +if it is a pointer to (possibly qualified) void or a +pointer to a (possibly qualifier) struct or class +type.

+ +

Rationale: ARC does not manage pointers of +CoreFoundation type (or any of the related families of retainable C +pointers which interoperate with Objective-C for retain/release +operation). In fact, ARC does not even know how to distinguish these +types from arbitrary C pointer types. The intent of this concept is +to filter out some obviously non-object types while leaving a hook for +later tightening if a means of exhaustively marking CF types is made +available.

+ +
+

Auditing of C retainable pointer interfaces

+ +

[beginning Apple 4.0, LLVM 3.1]

+ +

A C function may be marked with the cf_audited_transfer +attribute to express that, except as otherwise marked with attributes, +it obeys the parameter (consuming vs. non-consuming) and return +(retained vs. non-retained) conventions for a C function of its name, +namely:

+ +
    +
  • A parameter of C retainable pointer type is assumed to not be +consumed unless it is marked with the cf_consumed attribute, and
  • +
  • A result of C retainable pointer type is assumed to not be +returned retained unless the function is either +marked cf_returns_retained or it follows +the create/copy naming convention and is not +marked cf_returns_not_retained.
  • +
+ +

A function obeys the create/copy naming +convention if its name contains as a substring:

+
    +
  • either Create or Copy not followed by a lowercase letter, or
  • +
  • either create or copy not followed by a lowercase +letter and not preceded by any letter, whether uppercase or lowercase.
  • +
+ +

A second attribute, cf_unknown_transfer, signifies that a +function's transfer semantics cannot be accurately captured using any +of these annotations. A program is ill-formed if it annotates the +same function with both cf_audited_transfer +and cf_unknown_transfer.

+ +

A pragma is provided to faciliate the mass annotation of interfaces:

+ +
#pragma arc_cf_code_audited begin
+...
+#pragma arc_cf_code_audited end
+ +

All C functions declared within the extent of this pragma are +treated as if annotated with the cf_audited_transfer +attribute unless they otherwise have the cf_unknown_transfer +attribute. The pragma is accepted in all language modes. A program +is ill-formed if it attempts to change files, whether by including a +file or ending the current file, within the extent of this pragma.

+ +

It is possible to test for all the features in this section with +__has_feature(arc_cf_code_audited).

+ +

Rationale: A significant inconvenience in +ARC programming is the necessity of interacting with APIs based around +C retainable pointers. These features are designed to make it +relatively easy for API authors to quickly review and annotate their +interfaces, in turn improving the fidelity of tools such as the static +analyzer and ARC. The single-file restriction on the pragma is +designed to eliminate the risk of accidentally annotating some other +header's interfaces.

+ +
+ +
+ +
+ +
+

Runtime support

+ +

This section describes the interaction between the ARC runtime and +the code generated by the ARC compiler. This is not part of the ARC +language specification; instead, it is effectively a language-specific +ABI supplement, akin to the Itanium generic ABI for C++.

+ +

Ownership qualification does not alter the storage requirements for +objects, except that it is undefined behavior if a __weak +object is inadequately aligned for an object of type id. The +other qualifiers may be used on explicitly under-aligned memory.

+ +

The runtime tracks __weak objects which holds non-null +values. It is undefined behavior to direct modify a __weak +object which is being tracked by the runtime except through an +objc_storeWeak, +objc_destroyWeak, +or objc_moveWeak +call.

+ +

The runtime must provide a number of new entrypoints which the +compiler may emit, which are described in the remainder of this +section.

+ +

Rationale: Several of these functions are +semantically equivalent to a message send; we emit calls to C +functions instead because:

+
    +
  • the machine code to do so is significantly smaller,
  • +
  • it is much easier to recognize the C functions in the ARC optimizer, and
  • +
  • a sufficient sophisticated runtime may be able to avoid the +message send in common cases.
  • +
+ +

Several other of these functions are fused operations which +can be described entirely in terms of other operations. We use the +fused operations primarily as a code-size optimization, although in +some cases there is also a real potential for avoiding redundant +operations in the runtime.

+ +
+ +
+

id objc_autorelease(id value);

+

Precondition: value is null or a pointer to a +valid object.

+

If value is null, this call has no effect. Otherwise, it +adds the object to the innermost autorelease pool exactly as if the +object had been sent the autorelease message.

+

Always returns value.

+
+ +
+

void objc_autoreleasePoolPop(void *pool);

+

Precondition: pool is the result of a previous call to +objc_autoreleasePoolPush +on the current thread, where neither pool nor any enclosing +pool have previously been popped.

+

Releases all the objects added to the given autorelease pool and +any autorelease pools it encloses, then sets the current autorelease +pool to the pool directly enclosing pool.

+
+ +
+

void *objc_autoreleasePoolPush(void);

+

Creates a new autorelease pool that is enclosed by the current +pool, makes that the current pool, and returns an opaque handle +to it.

+ +

Rationale: while the interface is described +as an explicit hierarchy of pools, the rules allow the implementation +to just keep a stack of objects, using the stack depth as the opaque +pool handle.

+ +
+ +
+

id objc_autoreleaseReturnValue(id value);

+

Precondition: value is null or a pointer to a +valid object.

+

If value is null, this call has no effect. Otherwise, it +makes a best effort to hand off ownership of a retain count on the +object to a call +to objc_retainAutoreleasedReturnValue +for the same object in an enclosing call frame. If this is not +possible, the object is autoreleased as above.

+

Always returns value.

+
+ +
+

void objc_copyWeak(id *dest, id *src);

+

Precondition: src is a valid pointer which either +contains a null pointer or has been registered as a __weak +object. dest is a valid pointer which has not been +registered as a __weak object.

+

dest is initialized to be equivalent to src, +potentially registering it with the runtime. Equivalent to the +following code:

+
void objc_copyWeak(id *dest, id *src) {
+  objc_release(objc_initWeak(dest, objc_loadWeakRetained(src)));
+}
+

Must be atomic with respect to calls to objc_storeWeak +on src.

+
+ +
+

void objc_destroyWeak(id *object);

+

Precondition: object is a valid pointer which +either contains a null pointer or has been registered as +a __weak object.

+

object is unregistered as a weak object, if it ever was. +The current value of object is left unspecified; otherwise, +equivalent to the following code:

+
void objc_destroyWeak(id *object) {
+  objc_storeWeak(object, nil);
+}
+

Does not need to be atomic with respect to calls +to objc_storeWeak on object.

+
+ +
+

id objc_initWeak(id *object, id value);

+

Precondition: object is a valid pointer which has +not been registered as a __weak object. value is +null or a pointer to a valid object.

+

If value is a null pointer or the object to which it +points has begun deallocation, object is zero-initialized. +Otherwise, object is registered as a __weak object +pointing to value. Equivalent to the following code:

+
id objc_initWeak(id *object, id value) {
+  *object = nil;
+  return objc_storeWeak(object, value);
+}
+

Returns the value of object after the call.

+

Does not need to be atomic with respect to calls +to objc_storeWeak on object.

+
+ +
+

id objc_loadWeak(id *object);

+

Precondition: object is a valid pointer which +either contains a null pointer or has been registered as +a __weak object.

+

If object is registered as a __weak object, and +the last value stored into object has not yet been +deallocated or begun deallocation, retains and autoreleases that value +and returns it. Otherwise returns null. Equivalent to the following +code:

+
id objc_loadWeak(id *object) {
+  return objc_autorelease(objc_loadWeakRetained(object));
+}
+

Must be atomic with respect to calls to objc_storeWeak +on object.

+
Rationale: loading weak references would be +inherently prone to race conditions without the retain.
+
+ +
+

id objc_loadWeakRetained(id *object);

+

Precondition: object is a valid pointer which +either contains a null pointer or has been registered as +a __weak object.

+

If object is registered as a __weak object, and +the last value stored into object has not yet been +deallocated or begun deallocation, retains that value and returns it. +Otherwise returns null.

+

Must be atomic with respect to calls to objc_storeWeak +on object.

+
+ +
+

void objc_moveWeak(id *dest, id *src);

+

Precondition: src is a valid pointer which either +contains a null pointer or has been registered as a __weak +object. dest is a valid pointer which has not been +registered as a __weak object.

+

dest is initialized to be equivalent to src, +potentially registering it with the runtime. src may then be +left in its original state, in which case this call is equivalent +to objc_copyWeak, or it +may be left as null.

+

Must be atomic with respect to calls to objc_storeWeak +on src.

+
+ +
+

void objc_release(id value);

+

Precondition: value is null or a pointer to a +valid object.

+

If value is null, this call has no effect. Otherwise, it +performs a release operation exactly as if the object had been sent +the release message.

+
+ +
+

id objc_retain(id value);

+

Precondition: value is null or a pointer to a +valid object.

+

If value is null, this call has no effect. Otherwise, it +performs a retain operation exactly as if the object had been sent +the retain message.

+

Always returns value.

+
+ +
+

id objc_retainAutorelease(id value);

+

Precondition: value is null or a pointer to a +valid object.

+

If value is null, this call has no effect. Otherwise, it +performs a retain operation followed by an autorelease operation. +Equivalent to the following code:

+
id objc_retainAutorelease(id value) {
+  return objc_autorelease(objc_retain(value));
+}
+

Always returns value.

+
+ +
+

id objc_retainAutoreleaseReturnValue(id value);

+

Precondition: value is null or a pointer to a +valid object.

+

If value is null, this call has no effect. Otherwise, it +performs a retain operation followed by the operation described in +objc_autoreleaseReturnValue. +Equivalent to the following code:

+
id objc_retainAutoreleaseReturnValue(id value) {
+  return objc_autoreleaseReturnValue(objc_retain(value));
+}
+

Always returns value.

+
+ +
+

id objc_retainAutoreleasedReturnValue(id value);

+

Precondition: value is null or a pointer to a +valid object.

+

If value is null, this call has no effect. Otherwise, it +attempts to accept a hand off of a retain count from a call to +objc_autoreleaseReturnValue +on value in a recently-called function or something it +calls. If that fails, it performs a retain operation exactly +like objc_retain.

+

Always returns value.

+
+ +
+

id objc_retainBlock(id value);

+

Precondition: value is null or a pointer to a +valid block object.

+

If value is null, this call has no effect. Otherwise, if +the block pointed to by value is still on the stack, it is +copied to the heap and the address of the copy is returned. Otherwise +a retain operation is performed on the block exactly as if it had been +sent the retain message.

+
+ +
+

id objc_storeStrong(id *object, id value);

+

Precondition: object is a valid pointer to +a __strong object which is adequately aligned for a +pointer. value is null or a pointer to a valid object.

+

Performs the complete sequence for assigning to a __strong +object of non-block type. Equivalent to the following code:

+
id objc_storeStrong(id *object, id value) {
+  value = [value retain];
+  id oldValue = *object;
+  *object = value;
+  [oldValue release];
+  return value;
+}
+

Always returns value.

+
+ +
+

id objc_storeWeak(id *object, id value);

+

Precondition: object is a valid pointer which +either contains a null pointer or has been registered as +a __weak object. value is null or a pointer to a +valid object.

+

If value is a null pointer or the object to which it +points has begun deallocation, object is assigned null +and unregistered as a __weak object. Otherwise, +object is registered as a __weak object or has its +registration updated to point to value.

+

Returns the value of object after the call.

+
+ +
+
+ + diff --git a/cpp/llvm/tools/clang/docs/Block-ABI-Apple.txt b/cpp/llvm/tools/clang/docs/Block-ABI-Apple.txt new file mode 100644 index 00000000..917059b4 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/Block-ABI-Apple.txt @@ -0,0 +1,669 @@ +Block Implementation Specification + +Copyright 2008-2010 Apple, Inc. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +0. History + +2008/7/14 - created +2008/8/21 - revised, C++ +2008/9/24 - add NULL isa field to __block storage +2008/10/1 - revise block layout to use a static descriptor structure +2008/10/6 - revise block layout to use an unsigned long int flags +2008/10/28 - specify use of _Block_object_assign/dispose for all "Object" types in helper functions +2008/10/30 - revise new layout to have invoke function in same place +2008/10/30 - add __weak support + +2010/3/16 - rev for stret return, signature field +2010/4/6 - improved wording + +This document describes the Apple ABI implementation specification of Blocks. + +The first shipping version of this ABI is found in Mac OS X 10.6, and shall be referred to as 10.6.ABI. As of 2010/3/16, the following describes the ABI contract with the runtime and the compiler, and, as necessary, will be referred to as ABI.2010.3.16. + +Since the Apple ABI references symbols from other elements of the system, any attempt to use this ABI on systems prior to SnowLeopard is undefined. + +1. High Level + +The ABI of blocks consist of their layout and the runtime functions required by the compiler. +A Block consists of a structure of the following form: + +struct Block_literal_1 { + void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock + int flags; + int reserved; + void (*invoke)(void *, ...); + struct Block_descriptor_1 { + unsigned long int reserved; // NULL + unsigned long int size; // sizeof(struct Block_literal_1) + // optional helper functions + void (*copy_helper)(void *dst, void *src); // IFF (1<<25) + void (*dispose_helper)(void *src); // IFF (1<<25) + // required ABI.2010.3.16 + const char *signature; // IFF (1<<30) + } *descriptor; + // imported variables +}; + +The following flags bits are in use thusly for a possible ABI.2010.3.16: + +enum { + BLOCK_HAS_COPY_DISPOSE = (1 << 25), + BLOCK_HAS_CTOR = (1 << 26), // helpers have C++ code + BLOCK_IS_GLOBAL = (1 << 28), + BLOCK_HAS_STRET = (1 << 29), // IFF BLOCK_HAS_SIGNATURE + BLOCK_HAS_SIGNATURE = (1 << 30), +}; + +In 10.6.ABI the (1<<29) was usually set and was always ignored by the runtime - it had been a transitional marker that did not get deleted after the transition. This bit is now paired with (1<<30), and represented as the pair (3<<30), for the following combinations of valid bit settings, and their meanings. + +switch (flags & (3<<29)) { + case (0<<29): 10.6.ABI, no signature field available + case (1<<29): 10.6.ABI, no signature field available + case (2<<29): ABI.2010.3.16, regular calling convention, presence of signature field + case (3<<29): ABI.2010.3.16, stret calling convention, presence of signature field, +} + +The signature field is not always populated. + +The following discussions are presented as 10.6.ABI otherwise. + +Block literals may occur within functions where the structure is created in stack local memory. They may also appear as initialization expressions for Block variables of global or static local variables. + +When a Block literal expression is evaluated the stack based structure is initialized as follows: + +1) static descriptor structure is declared and initialized as follows: +1a) the invoke function pointer is set to a function that takes the Block structure as its first argument and the rest of the arguments (if any) to the Block and executes the Block compound statement. +1b) the size field is set to the size of the following Block literal structure. +1c) the copy_helper and dispose_helper function pointers are set to respective helper functions if they are required by the Block literal +2) a stack (or global) Block literal data structure is created and initialized as follows: +2a) the isa field is set to the address of the external _NSConcreteStackBlock, which is a block of uninitialized memory supplied in libSystem, or _NSConcreteGlobalBlock if this is a static or file level block literal. +2) The flags field is set to zero unless there are variables imported into the block that need helper functions for program level Block_copy() and Block_release() operations, in which case the (1<<25) flags bit is set. + + +As an example, the Block literal expression + ^ { printf("hello world\n"); } +would cause to be created on a 32-bit system: + +struct __block_literal_1 { + void *isa; + int flags; + int reserved; + void (*invoke)(struct __block_literal_1 *); + struct __block_descriptor_1 *descriptor; +}; + +void __block_invoke_1(struct __block_literal_1 *_block) { + printf("hello world\n"); +} + +static struct __block_descriptor_1 { + unsigned long int reserved; + unsigned long int Block_size; +} __block_descriptor_1 = { 0, sizeof(struct __block_literal_1), __block_invoke_1 }; + +and where the block literal appeared + + struct __block_literal_1 _block_literal = { + &_NSConcreteStackBlock, + (1<<29), , + __block_invoke_1, + &__block_descriptor_1 + }; + +Blocks import other Block references, const copies of other variables, and variables marked __block. In Objective-C variables may additionally be objects. + +When a Block literal expression used as the initial value of a global or static local variable it is initialized as follows: + struct __block_literal_1 __block_literal_1 = { + &_NSConcreteGlobalBlock, + (1<<28)|(1<<29), , + __block_invoke_1, + &__block_descriptor_1 + }; +that is, a different address is provided as the first value and a particular (1<<28) bit is set in the flags field, and otherwise it is the same as for stack based Block literals. This is an optimization that can be used for any Block literal that imports no const or __block storage variables. + + +2. Imported Variables + +Variables of "auto" storage class are imported as const copies. Variables of "__block" storage class are imported as a pointer to an enclosing data structure. Global variables are simply referenced and not considered as imported. + +2.1 Imported const copy variables + +Automatic storage variables not marked with __block are imported as const copies. + +The simplest example is that of importing a variable of type int. + + int x = 10; + void (^vv)(void) = ^{ printf("x is %d\n", x); } + x = 11; + vv(); + +would be compiled + +struct __block_literal_2 { + void *isa; + int flags; + int reserved; + void (*invoke)(struct __block_literal_2 *); + struct __block_descriptor_2 *descriptor; + const int x; +}; + +void __block_invoke_2(struct __block_literal_2 *_block) { + printf("x is %d\n", _block->x); +} + +static struct __block_descriptor_2 { + unsigned long int reserved; + unsigned long int Block_size; +} __block_descriptor_2 = { 0, sizeof(struct __block_literal_2) }; + +and + + struct __block_literal_2 __block_literal_2 = { + &_NSConcreteStackBlock, + (1<<29), , + __block_invoke_2, + &__block_descriptor_2, + x + }; + +In summary, scalars, structures, unions, and function pointers are generally imported as const copies with no need for helper functions. + +2.2 Imported const copy of Block reference + +The first case where copy and dispose helper functions are required is for the case of when a block itself is imported. In this case both a copy_helper function and a dispose_helper function are needed. The copy_helper function is passed both the existing stack based pointer and the pointer to the new heap version and should call back into the runtime to actually do the copy operation on the imported fields within the block. The runtime functions are all described in Section 5.0 Runtime Helper Functions. + +An example: + + void (^existingBlock)(void) = ...; + void (^vv)(void) = ^{ existingBlock(); } + vv(); + +struct __block_literal_3 { + ...; // existing block +}; + +struct __block_literal_4 { + void *isa; + int flags; + int reserved; + void (*invoke)(struct __block_literal_4 *); + struct __block_literal_3 *const existingBlock; +}; + +void __block_invoke_4(struct __block_literal_2 *_block) { + __block->existingBlock->invoke(__block->existingBlock); +} + +void __block_copy_4(struct __block_literal_4 *dst, struct __block_literal_4 *src) { + //_Block_copy_assign(&dst->existingBlock, src->existingBlock, 0); + _Block_object_assign(&dst->existingBlock, src->existingBlock, BLOCK_FIELD_IS_BLOCK); +} + +void __block_dispose_4(struct __block_literal_4 *src) { + // was _Block_destroy + _Block_object_dispose(src->existingBlock, BLOCK_FIELD_IS_BLOCK); +} + +static struct __block_descriptor_4 { + unsigned long int reserved; + unsigned long int Block_size; + void (*copy_helper)(struct __block_literal_4 *dst, struct __block_literal_4 *src); + void (*dispose_helper)(struct __block_literal_4 *); +} __block_descriptor_4 = { + 0, + sizeof(struct __block_literal_4), + __block_copy_4, + __block_dispose_4, +}; + +and where it is used + + struct __block_literal_4 _block_literal = { + &_NSConcreteStackBlock, + (1<<25)|(1<<29), + __block_invoke_4, + & __block_descriptor_4 + existingBlock, + }; + +2.2.1 Importing __attribute__((NSObject)) variables. + +GCC introduces __attribute__((NSObject)) on structure pointers to mean "this is an object". This is useful because many low level data structures are declared as opaque structure pointers, e.g. CFStringRef, CFArrayRef, etc. When used from C, however, these are still really objects and are the second case where that requires copy and dispose helper functions to be generated. The copy helper functions generated by the compiler should use the _Block_object_assign runtime helper function and in the dispose helper the _Block_object_dispose runtime helper function should be called. + +For example, block xyzzy in the following + + struct Opaque *__attribute__((NSObject)) objectPointer = ...; + ... + void (^xyzzy)(void) = ^{ CFPrint(objectPointer); }; + +would have helper functions + +void __block_copy_xyzzy(struct __block_literal_5 *dst, struct __block_literal_5 *src) { + _Block_object_assign(&dst->objectPointer, src-> objectPointer, BLOCK_FIELD_IS_OBJECT); +} + +void __block_dispose_xyzzy(struct __block_literal_5 *src) { + _Block_object_dispose(src->objectPointer, BLOCK_FIELD_IS_OBJECT); +} + +generated. + + +2.3 Imported __block marked variables. + +2.3.1 Layout of __block marked variables + +The compiler must embed variables that are marked __block in a specialized structure of the form: + +struct _block_byref_xxxx { + void *isa; + struct Block_byref *forwarding; + int flags; //refcount; + int size; + typeof(marked_variable) marked_variable; +}; + +Variables of certain types require helper functions for when Block_copy() and Block_release() are performed upon a referencing Block. At the "C" level only variables that are of type Block or ones that have __attribute__((NSObject)) marked require helper functions. In Objective-C objects require helper functions and in C++ stack based objects require helper functions. Variables that require helper functions use the form: + +struct _block_byref_xxxx { + void *isa; + struct _block_byref_xxxx *forwarding; + int flags; //refcount; + int size; + // helper functions called via Block_copy() and Block_release() + void (*byref_keep)(void *dst, void *src); + void (*byref_dispose)(void *); + typeof(marked_variable) marked_variable; +}; + +The structure is initialized such that + a) the forwarding pointer is set to the beginning of its enclosing structure, + b) the size field is initialized to the total size of the enclosing structure, + c) the flags field is set to either 0 if no helper functions are needed or (1<<25) if they are, + d) the helper functions are initialized (if present) + e) the variable itself is set to its initial value. + f) the isa field is set to NULL + +2.3.2 Access to __block variables from within its lexical scope. + +In order to "move" the variable to the heap upon a copy_helper operation the compiler must rewrite access to such a variable to be indirect through the structures forwarding pointer. For example: + + int __block i = 10; + i = 11; + +would be rewritten to be: + + struct _block_byref_i { + void *isa; + struct _block_byref_i *forwarding; + int flags; //refcount; + int size; + int captured_i; + } i = { NULL, &i, 0, sizeof(struct _block_byref_i), 10 }; + + i.forwarding->captured_i = 11; + +In the case of a Block reference variable being marked __block the helper code generated must use the _Block_object_assign and _Block_object_dispose routines supplied by the runtime to make the copies. For example: + + __block void (voidBlock)(void) = blockA; + voidBlock = blockB; + +would translate into + +struct _block_byref_voidBlock { + void *isa; + struct _block_byref_voidBlock *forwarding; + int flags; //refcount; + int size; + void (*byref_keep)(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src); + void (*byref_dispose)(struct _block_byref_voidBlock *); + void (^captured_voidBlock)(void); +}; + +void _block_byref_keep_helper(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src) { + //_Block_copy_assign(&dst->captured_voidBlock, src->captured_voidBlock, 0); + _Block_object_assign(&dst->captured_voidBlock, src->captured_voidBlock, BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER); +} + +void _block_byref_dispose_helper(struct _block_byref_voidBlock *param) { + //_Block_destroy(param->captured_voidBlock, 0); + _Block_object_dispose(param->captured_voidBlock, BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER)} + +and + struct _block_byref_voidBlock voidBlock = {( .forwarding=&voidBlock, .flags=(1<<25), .size=sizeof(struct _block_byref_voidBlock *), + .byref_keep=_block_byref_keep_helper, .byref_dispose=_block_byref_dispose_helper, + .captured_voidBlock=blockA )}; + + voidBlock.forwarding->captured_voidBlock = blockB; + + +2.3.3 Importing __block variables into Blocks + +A Block that uses a __block variable in its compound statement body must import the variable and emit copy_helper and dispose_helper helper functions that, in turn, call back into the runtime to actually copy or release the byref data block using the functions _Block_object_assign and _Block_object_dispose. + +For example: + + int __block i = 2; + functioncall(^{ i = 10; }); + +would translate to + +struct _block_byref_i { + void *isa; // set to NULL + struct _block_byref_voidBlock *forwarding; + int flags; //refcount; + int size; + void (*byref_keep)(struct _block_byref_i *dst, struct _block_byref_i *src); + void (*byref_dispose)(struct _block_byref_i *); + int captured_i; +}; + + +struct __block_literal_5 { + void *isa; + int flags; + int reserved; + void (*invoke)(struct __block_literal_5 *); + struct __block_descriptor_5 *descriptor; + struct _block_byref_i *i_holder; +}; + +void __block_invoke_5(struct __block_literal_5 *_block) { + _block->forwarding->captured_i = 10; +} + +void __block_copy_5(struct __block_literal_5 *dst, struct __block_literal_5 *src) { + //_Block_byref_assign_copy(&dst->captured_i, src->captured_i); + _Block_object_assign(&dst->captured_i, src->captured_i, BLOCK_FIELD_IS_BYREF | BLOCK_BYREF_CALLER); +} + +void __block_dispose_5(struct __block_literal_5 *src) { + //_Block_byref_release(src->captured_i); + _Block_object_dispose(src->captured_i, BLOCK_FIELD_IS_BYREF | BLOCK_BYREF_CALLER); +} + +static struct __block_descriptor_5 { + unsigned long int reserved; + unsigned long int Block_size; + void (*copy_helper)(struct __block_literal_5 *dst, struct __block_literal_5 *src); + void (*dispose_helper)(struct __block_literal_5 *); +} __block_descriptor_5 = { 0, sizeof(struct __block_literal_5) __block_copy_5, __block_dispose_5 }; + +and + + struct _block_byref_i i = {( .forwarding=&i, .flags=0, .size=sizeof(struct _block_byref_i) )}; + struct __block_literal_5 _block_literal = { + &_NSConcreteStackBlock, + (1<<25)|(1<<29), , + __block_invoke_5, + &__block_descriptor_5, + 2, + }; + +2.3.4 Importing __attribute__((NSObject)) __block variables + +A __block variable that is also marked __attribute__((NSObject)) should have byref_keep and byref_dispose helper functions that use _Block_object_assign and _Block_object_dispose. + +2.3.5 __block escapes + +Because Blocks referencing __block variables may have Block_copy() performed upon them the underlying storage for the variables may move to the heap. In Objective-C Garbage Collection Only compilation environments the heap used is the garbage collected one and no further action is required. Otherwise the compiler must issue a call to potentially release any heap storage for __block variables at all escapes or terminations of their scope. The call should be: + + _Block_object_dispose(&_block_byref_xxx, BLOCK_FIELD_IS_BYREF); + + +2.3.6 Nesting + +Blocks may contain Block literal expressions. Any variables used within inner blocks are imported into all enclosing Block scopes even if the variables are not used. This includes const imports as well as __block variables. + +3. Objective C Extensions to Blocks + +3.1 Importing Objects + +Objects should be treated as __attribute__((NSObject)) variables; all copy_helper, dispose_helper, byref_keep, and byref_dispose helper functions should use _Block_object_assign and _Block_object_dispose. There should be no code generated that uses -retain or -release methods. + + +3.2 Blocks as Objects + +The compiler will treat Blocks as objects when synthesizing property setters and getters, will characterize them as objects when generating garbage collection strong and weak layout information in the same manner as objects, and will issue strong and weak write-barrier assignments in the same manner as objects. + +3.3 __weak __block Support + +Objective-C (and Objective-C++) support the __weak attribute on __block variables. Under normal circumstances the compiler uses the Objective-C runtime helper support functions objc_assign_weak and objc_read_weak. Both should continue to be used for all reads and writes of __weak __block variables: + objc_read_weak(&block->byref_i->forwarding->i) + +The __weak variable is stored in a _block_byref_xxxx structure and the Block has copy and dispose helpers for this structure that call: + _Block_object_assign(&dest->_block_byref_i, src-> _block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BYREF); +and + _Block_object_dispose(src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BYREF); + + +In turn, the block_byref copy support helpers distinguish between whether the __block variable is a Block or not and should either call: + _Block_object_assign(&dest->_block_byref_i, src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_OBJECT | BLOCK_BYREF_CALLER); +for something declared as an object or + _Block_object_assign(&dest->_block_byref_i, src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER); +for something declared as a Block. + +A full example follows: + + + __block __weak id obj = ; + functioncall(^{ [obj somemessage]; }); + +would translate to + +struct _block_byref_obj { + void *isa; // uninitialized + struct _block_byref_obj *forwarding; + int flags; //refcount; + int size; + void (*byref_keep)(struct _block_byref_i *dst, struct _block_byref_i *src); + void (*byref_dispose)(struct _block_byref_i *); + id captured_obj; +}; + +void _block_byref_obj_keep(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src) { + //_Block_copy_assign(&dst->captured_obj, src->captured_obj, 0); + _Block_object_assign(&dst->captured_obj, src->captured_obj, BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK | BLOCK_BYREF_CALLER); +} + +void _block_byref_obj_dispose(struct _block_byref_voidBlock *param) { + //_Block_destroy(param->captured_obj, 0); + _Block_object_dispose(param->captured_obj, BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK | BLOCK_BYREF_CALLER); +}; + +for the block byref part and + +struct __block_literal_5 { + void *isa; + int flags; + int reserved; + void (*invoke)(struct __block_literal_5 *); + struct __block_descriptor_5 *descriptor; + struct _block_byref_obj *byref_obj; +}; + +void __block_invoke_5(struct __block_literal_5 *_block) { + [objc_read_weak(&_block->byref_obj->forwarding->captured_obj) somemessage]; +} + +void __block_copy_5(struct __block_literal_5 *dst, struct __block_literal_5 *src) { + //_Block_byref_assign_copy(&dst->byref_obj, src->byref_obj); + _Block_object_assign(&dst->byref_obj, src->byref_obj, BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK); +} + +void __block_dispose_5(struct __block_literal_5 *src) { + //_Block_byref_release(src->byref_obj); + _Block_object_dispose(src->byref_obj, BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK); +} + +static struct __block_descriptor_5 { + unsigned long int reserved; + unsigned long int Block_size; + void (*copy_helper)(struct __block_literal_5 *dst, struct __block_literal_5 *src); + void (*dispose_helper)(struct __block_literal_5 *); +} __block_descriptor_5 = { 0, sizeof(struct __block_literal_5), __block_copy_5, __block_dispose_5 }; + +and within the compound statement: + + struct _block_byref_obj obj = {( .forwarding=&obj, .flags=(1<<25), .size=sizeof(struct _block_byref_obj), + .byref_keep=_block_byref_obj_keep, .byref_dispose=_block_byref_obj_dispose, + .captured_obj = )}; + + struct __block_literal_5 _block_literal = { + &_NSConcreteStackBlock, + (1<<25)|(1<<29), , + __block_invoke_5, + &__block_descriptor_5, + &obj, // a reference to the on-stack structure containing "captured_obj" + }; + + + functioncall(_block_literal->invoke(&_block_literal)); + + +4.0 C++ Support + +Within a block stack based C++ objects are copied into const copies using the copy constructor. It is an error if a stack based C++ object is used within a block if it does not have a copy constructor. In addition both copy and destroy helper routines must be synthesized for the block to support the Block_copy() operation, and the flags work marked with the (1<<26) bit in addition to the (1<<25) bit. The copy helper should call the constructor using appropriate offsets of the variable within the supplied stack based block source and heap based destination for all const constructed copies, and similarly should call the destructor in the destroy routine. + +As an example, suppose a C++ class FOO existed with a copy constructor. Within a code block a stack version of a FOO object is declared and used within a Block literal expression: + +{ + FOO foo; + void (^block)(void) = ^{ printf("%d\n", foo.value()); }; +} + +The compiler would synthesize + +struct __block_literal_10 { + void *isa; + int flags; + int reserved; + void (*invoke)(struct __block_literal_10 *); + struct __block_descriptor_10 *descriptor; + const FOO foo; +}; + +void __block_invoke_10(struct __block_literal_10 *_block) { + printf("%d\n", _block->foo.value()); +} + +void __block_literal_10(struct __block_literal_10 *dst, struct __block_literal_10 *src) { + FOO_ctor(&dst->foo, &src->foo); +} + +void __block_dispose_10(struct __block_literal_10 *src) { + FOO_dtor(&src->foo); +} + +static struct __block_descriptor_10 { + unsigned long int reserved; + unsigned long int Block_size; + void (*copy_helper)(struct __block_literal_10 *dst, struct __block_literal_10 *src); + void (*dispose_helper)(struct __block_literal_10 *); +} __block_descriptor_10 = { 0, sizeof(struct __block_literal_10), __block_copy_10, __block_dispose_10 }; + +and the code would be: +{ + FOO foo; + comp_ctor(&foo); // default constructor + struct __block_literal_10 _block_literal = { + &_NSConcreteStackBlock, + (1<<25)|(1<<26)|(1<<29), , + __block_invoke_10, + &__block_descriptor_10, + }; + comp_ctor(&_block_literal->foo, &foo); // const copy into stack version + struct __block_literal_10 &block = &_block_literal; // assign literal to block variable + block->invoke(block); // invoke block + comp_dtor(&_block_literal->foo); // destroy stack version of const block copy + comp_dtor(&foo); // destroy original version +} + + +C++ objects stored in __block storage start out on the stack in a block_byref data structure as do other variables. Such objects (if not const objects) must support a regular copy constructor. The block_byref data structure will have copy and destroy helper routines synthesized by the compiler. The copy helper will have code created to perform the copy constructor based on the initial stack block_byref data structure, and will also set the (1<<26) bit in addition to the (1<<25) bit. The destroy helper will have code to do the destructor on the object stored within the supplied block_byref heap data structure. For example, + + __block FOO blockStorageFoo; + +requires the normal constructor for the embedded blockStorageFoo object + + FOO_ctor(& _block_byref_blockStorageFoo->blockStorageFoo); + +and at scope termination the destructor: + + FOO_dtor(& _block_byref_blockStorageFoo->blockStorageFoo); + +Note that the forwarding indirection is NOT used. + +The compiler would need to generate (if used from a block literal) the following copy/dispose helpers: + +void _block_byref_obj_keep(struct _block_byref_blockStorageFoo *dst, struct _block_byref_blockStorageFoo *src) { + FOO_ctor(&dst->blockStorageFoo, &src->blockStorageFoo); +} + +void _block_byref_obj_dispose(struct _block_byref_blockStorageFoo *src) { + FOO_dtor(&src->blockStorageFoo); +} + +for the appropriately named constructor and destructor for the class/struct FOO. + +To support member variable and function access the compiler will synthesize a const pointer to a block version of the "this" pointer. + +5.0 Runtime Helper Functions + +The runtime helper functions are described in /usr/local/include/Block_private.h. To summarize their use, a block requires copy/dispose helpers if it imports any block variables, __block storage variables, __attribute__((NSObject)) variables, or C++ const copied objects with constructor/destructors. The (1<<26) bit is set and functions are generated. + +The block copy helper function should, for each of the variables of the type mentioned above, call + _Block_object_assign(&dst->target, src->target, BLOCK_FIELD_); +in the copy helper and + _Block_object_dispose(->target, BLOCK_FIELD_); +in the dispose helper where + is + +enum { + BLOCK_FIELD_IS_OBJECT = 3, // id, NSObject, __attribute__((NSObject)), block, ... + BLOCK_FIELD_IS_BLOCK = 7, // a block variable + BLOCK_FIELD_IS_BYREF = 8, // the on stack structure holding the __block variable + + BLOCK_FIELD_IS_WEAK = 16, // declared __weak + + BLOCK_BYREF_CALLER = 128, // called from byref copy/dispose helpers +}; + +and of course the CTORs/DTORs for const copied C++ objects. + +The block_byref data structure similarly requires copy/dispose helpers for block variables, __attribute__((NSObject)) variables, or C++ const copied objects with constructor/destructors, and again the (1<<26) bit is set and functions are generated in the same manner. + +Under ObjC we allow __weak as an attribute on __block variables, and this causes the addition of BLOCK_FIELD_IS_WEAK orred onto the BLOCK_FIELD_IS_BYREF flag when copying the block_byref structure in the block copy helper, and onto the BLOCK_FIELD_ field within the block_byref copy/dispose helper calls. + +The prototypes, and summary, of the helper functions are + +/* Certain field types require runtime assistance when being copied to the heap. The following function is used + to copy fields of types: blocks, pointers to byref structures, and objects (including __attribute__((NSObject)) pointers. + BLOCK_FIELD_IS_WEAK is orthogonal to the other choices which are mutually exclusive. + Only in a Block copy helper will one see BLOCK_FIELD_IS_BYREF. + */ +void _Block_object_assign(void *destAddr, const void *object, const int flags); + +/* Similarly a compiler generated dispose helper needs to call back for each field of the byref data structure. + (Currently the implementation only packs one field into the byref structure but in principle there could be more). + The same flags used in the copy helper should be used for each call generated to this function: + */ +void _Block_object_dispose(const void *object, const int flags); diff --git a/cpp/llvm/tools/clang/docs/BlockLanguageSpec.txt b/cpp/llvm/tools/clang/docs/BlockLanguageSpec.txt new file mode 100644 index 00000000..f7bbda36 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/BlockLanguageSpec.txt @@ -0,0 +1,165 @@ +Language Specification for Blocks + +2008/2/25 — created +2008/7/28 — revised, __block syntax +2008/8/13 — revised, Block globals +2008/8/21 — revised, C++ elaboration +2008/11/1 — revised, __weak support +2009/1/12 — revised, explicit return types +2009/2/10 — revised, __block objects need retain + +Copyright 2008-2009 Apple, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +The Block Type + +A new derived type is introduced to C and, by extension, Objective-C, C++, and Objective-C++. Like function types, the Block type is a pair consisting of a result value type and a list of parameter types very similar to a function type. Blocks are intended to be used much like functions with the key distinction being that in addition to executable code they also contain various variable bindings to automatic (stack) or managed (heap) memory. + +The abstract declarator int (^)(char, float) describes a reference to a Block that, when invoked, takes two parameters, the first of type char and the second of type float, and returns a value of type int. The Block referenced is of opaque data that may reside in automatic (stack) memory, global memory, or heap memory. + + +Block Variable Declarations + +A variable with Block type is declared using function pointer style notation substituting ^ for *. The following are valid Block variable declarations: + void (^blockReturningVoidWithVoidArgument)(void); + int (^blockReturningIntWithIntAndCharArguments)(int, char); + void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int); + +Variadic ... arguments are supported. [variadic.c] A Block that takes no arguments must specify void in the argument list [voidarg.c]. An empty parameter list does not represent, as K&R provide, an unspecified argument list. Note: both gcc and clang support K&R style as a convenience. + +A Block reference may be cast to a pointer of arbitrary type and vice versa. [cast.c] A Block reference may not be dereferenced via the pointer dereference operator *, and thus a Block's size may not be computed at compile time. [sizeof.c] + + +Block Literal Expressions + +A Block literal expression produces a reference to a Block. It is introduced by the use of the ^ token as a unary operator. + Block_literal_expression ::= ^ block_decl compound_statement_body + block_decl ::= + block_decl ::= parameter_list + block_decl ::= type_expression + +...where type expression is extended to allow ^ as a Block reference (pointer) where * is allowed as a function reference (pointer). + +The following Block literal: + ^ void (void) { printf("hello world\n"); } + +...produces a reference to a Block with no arguments with no return value. + +The return type is optional and is inferred from the return statements. If the return statements return a value, they all must return a value of the same type. If there is no value returned the inferred type of the Block is void; otherwise it is the type of the return statement value. + +If the return type is omitted and the argument list is ( void ), the ( void ) argument list may also be omitted. + +So: + ^ ( void ) { printf("hello world\n"); } + +...and: + ^ { printf("hello world\n"); } + +...are exactly equivalent constructs for the same expression. + +The type_expression extends C expression parsing to accommodate Block reference declarations as it accommodates function pointer declarations. + +Given: + typedef int (*pointerToFunctionThatReturnsIntWithCharArg)(char); + pointerToFunctionThatReturnsIntWithCharArg functionPointer; + + ^ pointerToFunctionThatReturnsIntWithCharArg (float x) { return functionPointer; } + +...and: + ^ int ((*)(float x))(char) { return functionPointer; } + +...are equivalent expressions, as is: + + ^(float x) { return functionPointer; } + +[returnfunctionptr.c] + +The compound statement body establishes a new lexical scope within that of its parent. Variables used within the scope of the compound statement are bound to the Block in the normal manner with the exception of those in automatic (stack) storage. Thus one may access functions and global variables as one would expect, as well as static local variables. [testme] + +Local automatic (stack) variables referenced within the compound statement of a Block are imported and captured by the Block as const copies. The capture (binding) is performed at the time of the Block literal expression evaluation. + +The lifetime of variables declared in a Block is that of a function; each activation frame contains a new copy of variables declared within the local scope of the Block. Such variable declarations should be allowed anywhere [testme] rather than only when C99 parsing is requested, including for statements. [testme] + +Block literal expressions may occur within Block literal expressions (nest) and all variables captured by any nested blocks are implicitly also captured in the scopes of their enclosing Blocks. + +A Block literal expression may be used as the initialization value for Block variables at global or local static scope. + + +The Invoke Operator + +Blocks are invoked using function call syntax with a list of expression parameters of types corresponding to the declaration and returning a result type also according to the declaration. Given: + int (^x)(char); + void (^z)(void); + int (^(*y))(char) = &x; + +...the following are all legal Block invocations: + x('a'); + (*y)('a'); + (true ? x : *y)('a') + + +The Copy and Release Operations + +The compiler and runtime provide copy and release operations for Block references that create and, in matched use, release allocated storage for referenced Blocks. + +The copy operation Block_copy() is styled as a function that takes an arbitrary Block reference and returns a Block reference of the same type. The release operation, Block_release(), is styled as a function that takes an arbitrary Block reference and, if dynamically matched to a Block copy operation, allows recovery of the referenced allocated memory. + + +The __block Storage Qualifier + +In addition to the new Block type we also introduce a new storage qualifier, __block, for local variables. [testme: a __block declaration within a block literal] The __block storage qualifier is mutually exclusive to the existing local storage qualifiers auto, register, and static.[testme] Variables qualified by __block act as if they were in allocated storage and this storage is automatically recovered after last use of said variable. An implementation may choose an optimization where the storage is initially automatic and only "moved" to allocated (heap) storage upon a Block_copy of a referencing Block. Such variables may be mutated as normal variables are. + +In the case where a __block variable is a Block one must assume that the __block variable resides in allocated storage and as such is assumed to reference a Block that is also in allocated storage (that it is the result of a Block_copy operation). Despite this there is no provision to do a Block_copy or a Block_release if an implementation provides initial automatic storage for Blocks. This is due to the inherent race condition of potentially several threads trying to update the shared variable and the need for synchronization around disposing of older values and copying new ones. Such synchronization is beyond the scope of this language specification. + + +Control Flow + +The compound statement of a Block is treated much like a function body with respect to control flow in that goto, break, and continue do not escape the Block. Exceptions are treated "normally" in that when thrown they pop stack frames until a catch clause is found. + + +Objective-C Extensions + +Objective-C extends the definition of a Block reference type to be that also of id. A variable or expression of Block type may be messaged or used as a parameter wherever an id may be. The converse is also true. Block references may thus appear as properties and are subject to the assign, retain, and copy attribute logic that is reserved for objects. + +All Blocks are constructed to be Objective-C objects regardless of whether the Objective-C runtime is operational in the program or not. Blocks using automatic (stack) memory are objects and may be messaged, although they may not be assigned into __weak locations if garbage collection is enabled. + +Within a Block literal expression within a method definition references to instance variables are also imported into the lexical scope of the compound statement. These variables are implicitly qualified as references from self, and so self is imported as a const copy. The net effect is that instance variables can be mutated. + +The Block_copy operator retains all objects held in variables of automatic storage referenced within the Block expression (or form strong references if running under garbage collection). Object variables of __block storage type are assumed to hold normal pointers with no provision for retain and release messages. + +Foundation defines (and supplies) -copy and -release methods for Blocks. + +In the Objective-C and Objective-C++ languages, we allow the __weak specifier for __block variables of object type. If garbage collection is not enabled, this qualifier causes these variables to be kept without retain messages being sent. This knowingly leads to dangling pointers if the Block (or a copy) outlives the lifetime of this object. + +In garbage collected environments, the __weak variable is set to nil when the object it references is collected, as long as the __block variable resides in the heap (either by default or via Block_copy()). The initial Apple implementation does in fact start __block variables on the stack and migrate them to the heap only as a result of a Block_copy() operation. + +It is a runtime error to attempt to assign a reference to a stack-based Block into any storage marked __weak, including __weak __block variables. + + +C++ Extensions + +Block literal expressions within functions are extended to allow const use of C++ objects, pointers, or references held in automatic storage. + +For example, given class Foo with member function fighter(void): + Foo foo; + Foo &fooRef = foo; + Foo *fooPtr = &foo; + +...a Block that used foo would import the variables as const variations: + const Foo block_foo = foo; // const copy constructor + const Foo &block_fooRef = fooRef; + Foo *const block_fooPtr = fooPtr; + +Stack-local objects are copied into a Block via a copy const constructor. If no such constructor exists, it is considered an error to reference such objects from within the Block compound statements. A destructor is run as control leaves the compound statement that contains the Block literal expression. + +If a Block originates on the stack, a const copy constructor of the stack-based Block const copy is performed when a Block_copy operation is called; when the last Block_release (or subsequently GC) occurs, a destructor is run on the heap copy. + +Variables declared as residing in __block storage may be initially allocated in the heap or may first appear on the stack and be copied to the heap as a result of a Block_copy() operation. When copied from the stack, a normal copy constructor is used to initialize the heap-based version from the original stack version. The destructor for a const copied object is run at the normal end of scope. The destructor for any initial stack based version is also called at normal end of scope. + +Within a member function, access to member functions and variables is done via an implicit const copy of a this pointer. + +Member variables that are Blocks may not be overloaded by the types of their arguments. + diff --git a/cpp/llvm/tools/clang/docs/DriverArchitecture.png b/cpp/llvm/tools/clang/docs/DriverArchitecture.png new file mode 100644 index 00000000..056a70a9 Binary files /dev/null and b/cpp/llvm/tools/clang/docs/DriverArchitecture.png differ diff --git a/cpp/llvm/tools/clang/docs/DriverInternals.html b/cpp/llvm/tools/clang/docs/DriverInternals.html new file mode 100644 index 00000000..ce707b99 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/DriverInternals.html @@ -0,0 +1,523 @@ + + + + Clang Driver Manual + + + + + + + + +
+ +

Driver Design & Internals

+ + + + + +

Introduction

+ + +

This document describes the Clang driver. The purpose of this + document is to describe both the motivation and design goals + for the driver, as well as details of the internal + implementation.

+ + +

Features and Goals

+ + +

The Clang driver is intended to be a production quality + compiler driver providing access to the Clang compiler and + tools, with a command line interface which is compatible with + the gcc driver.

+ +

Although the driver is part of and driven by the Clang + project, it is logically a separate tool which shares many of + the same goals as Clang:

+ +

Features:

+ + + +

GCC Compatibility

+ + +

The number one goal of the driver is to ease the adoption of + Clang by allowing users to drop Clang into a build system + which was designed to call GCC. Although this makes the driver + much more complicated than might otherwise be necessary, we + decided that being very compatible with the gcc command line + interface was worth it in order to allow users to quickly test + clang on their projects.

+ + +

Flexible

+ + +

The driver was designed to be flexible and easily accommodate + new uses as we grow the clang and LLVM infrastructure. As one + example, the driver can easily support the introduction of + tools which have an integrated assembler; something we hope to + add to LLVM in the future.

+ +

Similarly, most of the driver functionality is kept in a + library which can be used to build other tools which want to + implement or accept a gcc like interface.

+ + +

Low Overhead

+ + +

The driver should have as little overhead as possible. In + practice, we found that the gcc driver by itself incurred a + small but meaningful overhead when compiling many small + files. The driver doesn't do much work compared to a + compilation, but we have tried to keep it as efficient as + possible by following a few simple principles:

+
    +
  • Avoid memory allocation and string copying when + possible.
  • + +
  • Don't parse arguments more than once.
  • + +
  • Provide a few simple interfaces for efficiently searching + arguments.
  • +
+ + +

Simple

+ + +

Finally, the driver was designed to be "as simple as + possible", given the other goals. Notably, trying to be + completely compatible with the gcc driver adds a significant + amount of complexity. However, the design of the driver + attempts to mitigate this complexity by dividing the process + into a number of independent stages instead of a single + monolithic task.

+ + +

Internal Design and Implementation

+ + + + + +

Internals Introduction

+ + +

In order to satisfy the stated goals, the driver was designed + to completely subsume the functionality of the gcc executable; + that is, the driver should not need to delegate to gcc to + perform subtasks. On Darwin, this implies that the Clang + driver also subsumes the gcc driver-driver, which is used to + implement support for building universal images (binaries and + object files). This also implies that the driver should be + able to call the language specific compilers (e.g. cc1) + directly, which means that it must have enough information to + forward command line arguments to child processes + correctly.

+ + +

Design Overview

+ + +

The diagram below shows the significant components of the + driver architecture and how they relate to one another. The + orange components represent concrete data structures built by + the driver, the green components indicate conceptually + distinct stages which manipulate these data structures, and + the blue components are important helper classes.

+ +
+ + Driver Architecture Diagram + +
+ + +

Driver Stages

+ + +

The driver functionality is conceptually divided into five stages:

+ +
    +
  1. + Parse: Option Parsing + +

    The command line argument strings are decomposed into + arguments (Arg instances). The driver expects to + understand all available options, although there is some + facility for just passing certain classes of options + through (like -Wl,).

    + +

    Each argument corresponds to exactly one + abstract Option definition, which describes how + the option is parsed along with some additional + metadata. The Arg instances themselves are lightweight and + merely contain enough information for clients to determine + which option they correspond to and their values (if they + have additional parameters).

    + +

    For example, a command line like "-Ifoo -I foo" would + parse to two Arg instances (a JoinedArg and a SeparateArg + instance), but each would refer to the same Option.

    + +

    Options are lazily created in order to avoid populating + all Option classes when the driver is loaded. Most of the + driver code only needs to deal with options by their + unique ID (e.g., options::OPT_I),

    + +

    Arg instances themselves do not generally store the + values of parameters. In many cases, this would + simply result in creating unnecessary string + copies. Instead, Arg instances are always embedded inside + an ArgList structure, which contains the original vector + of argument strings. Each Arg itself only needs to contain + an index into this vector instead of storing its values + directly.

    + +

    The clang driver can dump the results of this + stage using the -ccc-print-options flag (which + must precede any actual command line arguments). For + example:

    +
    +            $ clang -ccc-print-options -Xarch_i386 -fomit-frame-pointer -Wa,-fast -Ifoo -I foo t.c
    +            Option 0 - Name: "-Xarch_", Values: {"i386", "-fomit-frame-pointer"}
    +            Option 1 - Name: "-Wa,", Values: {"-fast"}
    +            Option 2 - Name: "-I", Values: {"foo"}
    +            Option 3 - Name: "-I", Values: {"foo"}
    +            Option 4 - Name: "<input>", Values: {"t.c"}
    +          
    + +

    After this stage is complete the command line should be + broken down into well defined option objects with their + appropriate parameters. Subsequent stages should rarely, + if ever, need to do any string processing.

    +
  2. + +
  3. + Pipeline: Compilation Job Construction + +

    Once the arguments are parsed, the tree of subprocess + jobs needed for the desired compilation sequence are + constructed. This involves determining the input files and + their types, what work is to be done on them (preprocess, + compile, assemble, link, etc.), and constructing a list of + Action instances for each task. The result is a list of + one or more top-level actions, each of which generally + corresponds to a single output (for example, an object or + linked executable).

    + +

    The majority of Actions correspond to actual tasks, + however there are two special Actions. The first is + InputAction, which simply serves to adapt an input + argument for use as an input to other Actions. The second + is BindArchAction, which conceptually alters the + architecture to be used for all of its input Actions.

    + +

    The clang driver can dump the results of this + stage using the -ccc-print-phases flag. For + example:

    +
    +            $ clang -ccc-print-phases -x c t.c -x assembler t.s
    +            0: input, "t.c", c
    +            1: preprocessor, {0}, cpp-output
    +            2: compiler, {1}, assembler
    +            3: assembler, {2}, object
    +            4: input, "t.s", assembler
    +            5: assembler, {4}, object
    +            6: linker, {3, 5}, image
    +          
    +

    Here the driver is constructing seven distinct actions, + four to compile the "t.c" input into an object file, two to + assemble the "t.s" input, and one to link them together.

    + +

    A rather different compilation pipeline is shown here; in + this example there are two top level actions to compile + the input files into two separate object files, where each + object file is built using lipo to merge results + built for two separate architectures.

    +
    +            $ clang -ccc-print-phases -c -arch i386 -arch x86_64 t0.c t1.c
    +            0: input, "t0.c", c
    +            1: preprocessor, {0}, cpp-output
    +            2: compiler, {1}, assembler
    +            3: assembler, {2}, object
    +            4: bind-arch, "i386", {3}, object
    +            5: bind-arch, "x86_64", {3}, object
    +            6: lipo, {4, 5}, object
    +            7: input, "t1.c", c
    +            8: preprocessor, {7}, cpp-output
    +            9: compiler, {8}, assembler
    +            10: assembler, {9}, object
    +            11: bind-arch, "i386", {10}, object
    +            12: bind-arch, "x86_64", {10}, object
    +            13: lipo, {11, 12}, object
    +          
    + +

    After this stage is complete the compilation process is + divided into a simple set of actions which need to be + performed to produce intermediate or final outputs (in + some cases, like -fsyntax-only, there is no + "real" final output). Phases are well known compilation + steps, such as "preprocess", "compile", "assemble", + "link", etc.

    +
  4. + +
  5. + Bind: Tool & Filename Selection + +

    This stage (in conjunction with the Translate stage) + turns the tree of Actions into a list of actual subprocess + to run. Conceptually, the driver performs a top down + matching to assign Action(s) to Tools. The ToolChain is + responsible for selecting the tool to perform a particular + action; once selected the driver interacts with the tool + to see if it can match additional actions (for example, by + having an integrated preprocessor). + +

    Once Tools have been selected for all actions, the driver + determines how the tools should be connected (for example, + using an inprocess module, pipes, temporary files, or user + provided filenames). If an output file is required, the + driver also computes the appropriate file name (the suffix + and file location depend on the input types and options + such as -save-temps). + +

    The driver interacts with a ToolChain to perform the Tool + bindings. Each ToolChain contains information about all + the tools needed for compilation for a particular + architecture, platform, and operating system. A single + driver invocation may query multiple ToolChains during one + compilation in order to interact with tools for separate + architectures.

    + +

    The results of this stage are not computed directly, but + the driver can print the results via + the -ccc-print-bindings option. For example:

    +
    +            $ clang -ccc-print-bindings -arch i386 -arch ppc t0.c
    +            # "i386-apple-darwin9" - "clang", inputs: ["t0.c"], output: "/tmp/cc-Sn4RKF.s"
    +            # "i386-apple-darwin9" - "darwin::Assemble", inputs: ["/tmp/cc-Sn4RKF.s"], output: "/tmp/cc-gvSnbS.o"
    +            # "i386-apple-darwin9" - "darwin::Link", inputs: ["/tmp/cc-gvSnbS.o"], output: "/tmp/cc-jgHQxi.out"
    +            # "ppc-apple-darwin9" - "gcc::Compile", inputs: ["t0.c"], output: "/tmp/cc-Q0bTox.s"
    +            # "ppc-apple-darwin9" - "gcc::Assemble", inputs: ["/tmp/cc-Q0bTox.s"], output: "/tmp/cc-WCdicw.o"
    +            # "ppc-apple-darwin9" - "gcc::Link", inputs: ["/tmp/cc-WCdicw.o"], output: "/tmp/cc-HHBEBh.out"
    +            # "i386-apple-darwin9" - "darwin::Lipo", inputs: ["/tmp/cc-jgHQxi.out", "/tmp/cc-HHBEBh.out"], output: "a.out"
    +          
    + +

    This shows the tool chain, tool, inputs and outputs which + have been bound for this compilation sequence. Here clang + is being used to compile t0.c on the i386 architecture and + darwin specific versions of the tools are being used to + assemble and link the result, but generic gcc versions of + the tools are being used on PowerPC.

    +
  6. + +
  7. + Translate: Tool Specific Argument Translation + +

    Once a Tool has been selected to perform a particular + Action, the Tool must construct concrete Jobs which will be + executed during compilation. The main work is in translating + from the gcc style command line options to whatever options + the subprocess expects.

    + +

    Some tools, such as the assembler, only interact with a + handful of arguments and just determine the path of the + executable to call and pass on their input and output + arguments. Others, like the compiler or the linker, may + translate a large number of arguments in addition.

    + +

    The ArgList class provides a number of simple helper + methods to assist with translating arguments; for example, + to pass on only the last of arguments corresponding to some + option, or all arguments for an option.

    + +

    The result of this stage is a list of Jobs (executable + paths and argument strings) to execute.

    +
  8. + +
  9. + Execute +

    Finally, the compilation pipeline is executed. This is + mostly straightforward, although there is some interaction + with options + like -pipe, -pass-exit-codes + and -time.

    +
  10. + +
+ + +

Additional Notes

+ + +

The Compilation Object

+ +

The driver constructs a Compilation object for each set of + command line arguments. The Driver itself is intended to be + invariant during construction of a Compilation; an IDE should be + able to construct a single long lived driver instance to use + for an entire build, for example.

+ +

The Compilation object holds information that is particular + to each compilation sequence. For example, the list of used + temporary files (which must be removed once compilation is + finished) and result files (which should be removed if + compilation fails).

+ +

Unified Parsing & Pipelining

+ +

Parsing and pipelining both occur without reference to a + Compilation instance. This is by design; the driver expects that + both of these phases are platform neutral, with a few very well + defined exceptions such as whether the platform uses a driver + driver.

+ +

ToolChain Argument Translation

+ +

In order to match gcc very closely, the clang driver + currently allows tool chains to perform their own translation of + the argument list (into a new ArgList data structure). Although + this allows the clang driver to match gcc easily, it also makes + the driver operation much harder to understand (since the Tools + stop seeing some arguments the user provided, and see new ones + instead).

+ +

For example, on Darwin -gfull gets translated into two + separate arguments, -g + and -fno-eliminate-unused-debug-symbols. Trying to write Tool + logic to do something with -gfull will not work, because Tool + argument translation is done after the arguments have been + translated.

+ +

A long term goal is to remove this tool chain specific + translation, and instead force each tool to change its own logic + to do the right thing on the untranslated original arguments.

+ +

Unused Argument Warnings

+

The driver operates by parsing all arguments but giving Tools + the opportunity to choose which arguments to pass on. One + downside of this infrastructure is that if the user misspells + some option, or is confused about which options to use, some + command line arguments the user really cared about may go + unused. This problem is particularly important when using + clang as a compiler, since the clang compiler does not support + anywhere near all the options that gcc does, and we want to make + sure users know which ones are being used.

+ +

To support this, the driver maintains a bit associated with + each argument of whether it has been used (at all) during the + compilation. This bit usually doesn't need to be set by hand, + as the key ArgList accessors will set it automatically.

+ +

When a compilation is successful (there are no errors), the + driver checks the bit and emits an "unused argument" warning for + any arguments which were never accessed. This is conservative + (the argument may not have been used to do what the user wanted) + but still catches the most obvious cases.

+ + +

Relation to GCC Driver Concepts

+ + +

For those familiar with the gcc driver, this section provides + a brief overview of how things from the gcc driver map to the + clang driver.

+ +
    +
  • + Driver Driver +

    The driver driver is fully integrated into the clang + driver. The driver simply constructs additional Actions to + bind the architecture during the Pipeline + phase. The tool chain specific argument translation is + responsible for handling -Xarch_.

    + +

    The one caveat is that this approach + requires -Xarch_ not be used to alter the + compilation itself (for example, one cannot + provide -S as an -Xarch_ argument). The + driver attempts to reject such invocations, and overall + there isn't a good reason to abuse -Xarch_ to + that end in practice.

    + +

    The upside is that the clang driver is more efficient and + does little extra work to support universal builds. It also + provides better error reporting and UI consistency.

    +
  • + +
  • + Specs +

    The clang driver has no direct correspondent for + "specs". The majority of the functionality that is + embedded in specs is in the Tool specific argument + translation routines. The parts of specs which control the + compilation pipeline are generally part of + the Pipeline stage.

    +
  • + +
  • + Toolchains +

    The gcc driver has no direct understanding of tool + chains. Each gcc binary roughly corresponds to the + information which is embedded inside a single + ToolChain.

    + +

    The clang driver is intended to be portable and support + complex compilation environments. All platform and tool + chain specific code should be protected behind either + abstract or well defined interfaces (such as whether the + platform supports use as a driver driver).

    +
  • +
+
+ + diff --git a/cpp/llvm/tools/clang/docs/InternalsManual.html b/cpp/llvm/tools/clang/docs/InternalsManual.html new file mode 100644 index 00000000..bd6af8d6 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/InternalsManual.html @@ -0,0 +1,2011 @@ + + + +"Clang" CFE Internals Manual + + + + + + + + +
+ +

"Clang" CFE Internals Manual

+ + + + + +

Introduction

+ + +

This document describes some of the more important APIs and internal design +decisions made in the Clang C front-end. The purpose of this document is to +both capture some of this high level information and also describe some of the +design decisions behind it. This is meant for people interested in hacking on +Clang, not for end-users. The description below is categorized by +libraries, and does not describe any of the clients of the libraries.

+ + +

LLVM Support Library

+ + +

The LLVM libsupport library provides many underlying libraries and +data-structures, +including command line option processing, various containers and a system +abstraction layer, which is used for file system access.

+ + +

The Clang 'Basic' Library

+ + +

This library certainly needs a better name. The 'basic' library contains a +number of low-level utilities for tracking and manipulating source buffers, +locations within the source buffers, diagnostics, tokens, target abstraction, +and information about the subset of the language being compiled for.

+ +

Part of this infrastructure is specific to C (such as the TargetInfo class), +other parts could be reused for other non-C-based languages (SourceLocation, +SourceManager, Diagnostics, FileManager). When and if there is future demand +we can figure out if it makes sense to introduce a new library, move the general +classes somewhere else, or introduce some other solution.

+ +

We describe the roles of these classes in order of their dependencies.

+ + + +

The Diagnostics Subsystem

+ + +

The Clang Diagnostics subsystem is an important part of how the compiler +communicates with the human. Diagnostics are the warnings and errors produced +when the code is incorrect or dubious. In Clang, each diagnostic produced has +(at the minimum) a unique ID, an English translation associated with it, a SourceLocation to "put the caret", and a severity (e.g. +WARNING or ERROR). They can also optionally include a number +of arguments to the dianostic (which fill in "%0"'s in the string) as well as a +number of source ranges that related to the diagnostic.

+ +

In this section, we'll be giving examples produced by the Clang command line +driver, but diagnostics can be rendered in many +different ways depending on how the DiagnosticClient interface is +implemented. A representative example of a diagnostic is:

+ +
+t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
+   P = (P-42) + Gamma*4;
+       ~~~~~~ ^ ~~~~~~~
+
+ +

In this example, you can see the English translation, the severity (error), +you can see the source location (the caret ("^") and file/line/column info), +the source ranges "~~~~", arguments to the diagnostic ("int*" and "_Complex +float"). You'll have to believe me that there is a unique ID backing the +diagnostic :).

+ +

Getting all of this to happen has several steps and involves many moving +pieces, this section describes them and talks about best practices when adding +a new diagnostic.

+ + +

The Diagnostic*Kinds.td files

+ + +

Diagnostics are created by adding an entry to one of the +clang/Basic/Diagnostic*Kinds.td files, depending on what library will +be using it. From this file, tblgen generates the unique ID of the diagnostic, +the severity of the diagnostic and the English translation + format string.

+ +

There is little sanity with the naming of the unique ID's right now. Some +start with err_, warn_, ext_ to encode the severity into the name. Since the +enum is referenced in the C++ code that produces the diagnostic, it is somewhat +useful for it to be reasonably short.

+ +

The severity of the diagnostic comes from the set {NOTE, +WARNING, EXTENSION, EXTWARN, ERROR}. The +ERROR severity is used for diagnostics indicating the program is never +acceptable under any circumstances. When an error is emitted, the AST for the +input code may not be fully built. The EXTENSION and EXTWARN +severities are used for extensions to the language that Clang accepts. This +means that Clang fully understands and can represent them in the AST, but we +produce diagnostics to tell the user their code is non-portable. The difference +is that the former are ignored by default, and the later warn by default. The +WARNING severity is used for constructs that are valid in the currently +selected source language but that are dubious in some way. The NOTE +level is used to staple more information onto previous diagnostics.

+ +

These severities are mapped into a smaller set (the +Diagnostic::Level enum, {Ignored, Note, Warning, +Error, Fatal }) of output levels by the diagnostics +subsystem based on various configuration options. Clang internally supports a +fully fine grained mapping mechanism that allows you to map almost any +diagnostic to the output level that you want. The only diagnostics that cannot +be mapped are NOTEs, which always follow the severity of the previously +emitted diagnostic and ERRORs, which can only be mapped to +Fatal (it is not possible to turn an error into a warning, +for example).

+ +

Diagnostic mappings are used in many ways. For example, if the user +specifies -pedantic, EXTENSION maps to Warning, if +they specify -pedantic-errors, it turns into Error. This is +used to implement options like -Wunused_macros, -Wundef etc. +

+ +

+Mapping to Fatal should only be used for diagnostics that are +considered so severe that error recovery won't be able to recover sensibly from +them (thus spewing a ton of bogus errors). One example of this class of error +are failure to #include a file. +

+ + +

The Format String

+ + +

The format string for the diagnostic is very simple, but it has some power. +It takes the form of a string in English with markers that indicate where and +how arguments to the diagnostic are inserted and formatted. For example, here +are some simple format strings:

+ +
+  "binary integer literals are an extension"
+  "format string contains '\\0' within the string body"
+  "more '%%' conversions than data arguments"
+  "invalid operands to binary expression (%0 and %1)"
+  "overloaded '%0' must be a %select{unary|binary|unary or binary}2 operator"
+       " (has %1 parameter%s1)"
+
+ +

These examples show some important points of format strings. You can use any + plain ASCII character in the diagnostic string except "%" without a problem, + but these are C strings, so you have to use and be aware of all the C escape + sequences (as in the second example). If you want to produce a "%" in the + output, use the "%%" escape sequence, like the third diagnostic. Finally, + Clang uses the "%...[digit]" sequences to specify where and how arguments to + the diagnostic are formatted.

+ +

Arguments to the diagnostic are numbered according to how they are specified + by the C++ code that produces them, and are + referenced by %0 .. %9. If you have more than 10 arguments + to your diagnostic, you are doing something wrong :). Unlike printf, there + is no requirement that arguments to the diagnostic end up in the output in + the same order as they are specified, you could have a format string with + "%1 %0" that swaps them, for example. The text in between the + percent and digit are formatting instructions. If there are no instructions, + the argument is just turned into a string and substituted in.

+ +

Here are some "best practices" for writing the English format string:

+ +
    +
  • Keep the string short. It should ideally fit in the 80 column limit of the + DiagnosticKinds.td file. This avoids the diagnostic wrapping when + printed, and forces you to think about the important point you are conveying + with the diagnostic.
  • +
  • Take advantage of location information. The user will be able to see the + line and location of the caret, so you don't need to tell them that the + problem is with the 4th argument to the function: just point to it.
  • +
  • Do not capitalize the diagnostic string, and do not end it with a + period.
  • +
  • If you need to quote something in the diagnostic string, use single + quotes.
  • +
+ +

Diagnostics should never take random English strings as arguments: you +shouldn't use "you have a problem with %0" and pass in things like +"your argument" or "your return value" as arguments. Doing +this prevents translating the Clang diagnostics to +other languages (because they'll get random English words in their otherwise +localized diagnostic). The exceptions to this are C/C++ language keywords +(e.g. auto, const, mutable, etc) and C/C++ operators (/=). Note +that things like "pointer" and "reference" are not keywords. On the other +hand, you can include anything that comes from the user's source code, +including variable names, types, labels, etc. The 'select' format can be +used to achieve this sort of thing in a localizable way, see below.

+ + +

Formatting a Diagnostic Argument

+ + +

Arguments to diagnostics are fully typed internally, and come from a couple +different classes: integers, types, names, and random strings. Depending on +the class of the argument, it can be optionally formatted in different ways. +This gives the DiagnosticClient information about what the argument means +without requiring it to use a specific presentation (consider this MVC for +Clang :).

+ +

Here are the different diagnostic argument formats currently supported by +Clang:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
"s" format
Example:"requires %1 parameter%s1"
Class:Integers
Description:This is a simple formatter for integers that is + useful when producing English diagnostics. When the integer is 1, it prints + as nothing. When the integer is not 1, it prints as "s". This allows some + simple grammatical forms to be to be handled correctly, and eliminates the + need to use gross things like "requires %1 parameter(s)".
"select" format
Example:"must be a %select{unary|binary|unary or binary}2 + operator"
Class:Integers
Description:

This format specifier is used to merge multiple + related diagnostics together into one common one, without requiring the + difference to be specified as an English string argument. Instead of + specifying the string, the diagnostic gets an integer argument and the + format string selects the numbered option. In this case, the "%2" value + must be an integer in the range [0..2]. If it is 0, it prints 'unary', if + it is 1 it prints 'binary' if it is 2, it prints 'unary or binary'. This + allows other language translations to substitute reasonable words (or entire + phrases) based on the semantics of the diagnostic instead of having to do + things textually.

+

The selected string does undergo formatting.

"plural" format
Example:"you have %1 %plural{1:mouse|:mice}1 connected to + your computer"
Class:Integers
Description:

This is a formatter for complex plural forms. + It is designed to handle even the requirements of languages with very + complex plural forms, as many Baltic languages have. The argument consists + of a series of expression/form pairs, separated by ':', where the first form + whose expression evaluates to true is the result of the modifier.

+

An expression can be empty, in which case it is always true. See the + example at the top. Otherwise, it is a series of one or more numeric + conditions, separated by ','. If any condition matches, the expression + matches. Each numeric condition can take one of three forms.

+
    +
  • number: A simple decimal number matches if the argument is the same + as the number. Example: "%plural{1:mouse|:mice}4"
  • +
  • range: A range in square brackets matches if the argument is within + the range. Then range is inclusive on both ends. Example: + "%plural{0:none|1:one|[2,5]:some|:many}2"
  • +
  • modulo: A modulo operator is followed by a number, and + equals sign and either a number or a range. The tests are the + same as for plain + numbers and ranges, but the argument is taken modulo the number first. + Example: "%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything + else}1"
  • +
+

The parser is very unforgiving. A syntax error, even whitespace, will + abort, as will a failure to match the argument against any + expression.

"ordinal" format
Example:"ambiguity in %ordinal0 argument"
Class:Integers
Description:

This is a formatter which represents the + argument number as an ordinal: the value 1 becomes 1st, + 3 becomes 3rd, and so on. Values less than 1 + are not supported.

+

This formatter is currently hard-coded to use English ordinals.

"objcclass" format
Example:"method %objcclass0 not found"
Class:DeclarationName
Description:

This is a simple formatter that indicates the + DeclarationName corresponds to an Objective-C class method selector. As + such, it prints the selector with a leading '+'.

"objcinstance" format
Example:"method %objcinstance0 not found"
Class:DeclarationName
Description:

This is a simple formatter that indicates the + DeclarationName corresponds to an Objective-C instance method selector. As + such, it prints the selector with a leading '-'.

"q" format
Example:"candidate found by name lookup is %q0"
Class:NamedDecl*
Description

This formatter indicates that the fully-qualified name of the declaration should be printed, e.g., "std::vector" rather than "vector".

+ +

It is really easy to add format specifiers to the Clang diagnostics system, +but they should be discussed before they are added. If you are creating a lot +of repetitive diagnostics and/or have an idea for a useful formatter, please +bring it up on the cfe-dev mailing list.

+ + +

Producing the Diagnostic

+ + +

Now that you've created the diagnostic in the DiagnosticKinds.td file, you +need to write the code that detects the condition in question and emits the +new diagnostic. Various components of Clang (e.g. the preprocessor, Sema, +etc) provide a helper function named "Diag". It creates a diagnostic and +accepts the arguments, ranges, and other information that goes along with +it.

+ +

For example, the binary expression error comes from code like this:

+ +
+  if (various things that are bad)
+    Diag(Loc, diag::err_typecheck_invalid_operands)
+      << lex->getType() << rex->getType()
+      << lex->getSourceRange() << rex->getSourceRange();
+
+ +

This shows that use of the Diag method: they take a location (a SourceLocation object) and a diagnostic enum value +(which matches the name from DiagnosticKinds.td). If the diagnostic takes +arguments, they are specified with the << operator: the first argument +becomes %0, the second becomes %1, etc. The diagnostic interface allows you to +specify arguments of many different types, including int and +unsigned for integer arguments, const char* and +std::string for string arguments, DeclarationName and +const IdentifierInfo* for names, QualType for types, etc. +SourceRanges are also specified with the << operator, but do not have a +specific ordering requirement.

+ +

As you can see, adding and producing a diagnostic is pretty straightforward. +The hard part is deciding exactly what you need to say to help the user, picking +a suitable wording, and providing the information needed to format it correctly. +The good news is that the call site that issues a diagnostic should be +completely independent of how the diagnostic is formatted and in what language +it is rendered. +

+ + +

Fix-It Hints

+ + +

In some cases, the front end emits diagnostics when it is clear +that some small change to the source code would fix the problem. For +example, a missing semicolon at the end of a statement or a use of +deprecated syntax that is easily rewritten into a more modern form. +Clang tries very hard to emit the diagnostic and recover gracefully +in these and other cases.

+ +

However, for these cases where the fix is obvious, the diagnostic +can be annotated with a hint (referred to as a "fix-it hint") that +describes how to change the code referenced by the diagnostic to fix +the problem. For example, it might add the missing semicolon at the +end of the statement or rewrite the use of a deprecated construct +into something more palatable. Here is one such example from the C++ +front end, where we warn about the right-shift operator changing +meaning from C++98 to C++11:

+ +
+test.cpp:3:7: warning: use of right-shift operator ('>>') in template argument will require parentheses in C++11
+A<100 >> 2> *a;
+      ^
+  (       )
+
+ +

Here, the fix-it hint is suggesting that parentheses be added, +and showing exactly where those parentheses would be inserted into the +source code. The fix-it hints themselves describe what changes to make +to the source code in an abstract manner, which the text diagnostic +printer renders as a line of "insertions" below the caret line. Other diagnostic clients might choose +to render the code differently (e.g., as markup inline) or even give +the user the ability to automatically fix the problem.

+ +

All fix-it hints are described by the FixItHint class, +instances of which should be attached to the diagnostic using the +<< operator in the same way that highlighted source ranges and +arguments are passed to the diagnostic. Fix-it hints can be created +with one of three constructors:

+ +
+
FixItHint::CreateInsertion(Loc, Code)
+
Specifies that the given Code (a string) should be inserted + before the source location Loc.
+ +
FixItHint::CreateRemoval(Range)
+
Specifies that the code in the given source Range + should be removed.
+ +
FixItHint::CreateReplacement(Range, Code)
+
Specifies that the code in the given source Range + should be removed, and replaced with the given Code string.
+
+ + +

The DiagnosticClient Interface

+ + +

Once code generates a diagnostic with all of the arguments and the rest of +the relevant information, Clang needs to know what to do with it. As previously +mentioned, the diagnostic machinery goes through some filtering to map a +severity onto a diagnostic level, then (assuming the diagnostic is not mapped to +"Ignore") it invokes an object that implements the DiagnosticClient +interface with the information.

+ +

It is possible to implement this interface in many different ways. For +example, the normal Clang DiagnosticClient (named 'TextDiagnosticPrinter') turns +the arguments into strings (according to the various formatting rules), prints +out the file/line/column information and the string, then prints out the line of +code, the source ranges, and the caret. However, this behavior isn't required. +

+ +

Another implementation of the DiagnosticClient interface is the +'TextDiagnosticBuffer' class, which is used when Clang is in -verify mode. +Instead of formatting and printing out the diagnostics, this implementation just +captures and remembers the diagnostics as they fly by. Then -verify compares +the list of produced diagnostics to the list of expected ones. If they disagree, +it prints out its own output. +

+ +

There are many other possible implementations of this interface, and this is +why we prefer diagnostics to pass down rich structured information in arguments. +For example, an HTML output might want declaration names be linkified to where +they come from in the source. Another example is that a GUI might let you click +on typedefs to expand them. This application would want to pass significantly +more information about types through to the GUI than a simple flat string. The +interface allows this to happen.

+ + +

Adding Translations to Clang

+ + +

Not possible yet! Diagnostic strings should be written in UTF-8, the client +can translate to the relevant code page if needed. Each translation completely +replaces the format string for the diagnostic.

+ + + +

The SourceLocation and SourceManager classes

+ + +

Strangely enough, the SourceLocation class represents a location within the +source code of the program. Important design points include:

+ +
    +
  1. sizeof(SourceLocation) must be extremely small, as these are embedded into + many AST nodes and are passed around often. Currently it is 32 bits.
  2. +
  3. SourceLocation must be a simple value object that can be efficiently + copied.
  4. +
  5. We should be able to represent a source location for any byte of any input + file. This includes in the middle of tokens, in whitespace, in trigraphs, + etc.
  6. +
  7. A SourceLocation must encode the current #include stack that was active when + the location was processed. For example, if the location corresponds to a + token, it should contain the set of #includes active when the token was + lexed. This allows us to print the #include stack for a diagnostic.
  8. +
  9. SourceLocation must be able to describe macro expansions, capturing both + the ultimate instantiation point and the source of the original character + data.
  10. +
+ +

In practice, the SourceLocation works together with the SourceManager class +to encode two pieces of information about a location: its spelling location +and its instantiation location. For most tokens, these will be the same. +However, for a macro expansion (or tokens that came from a _Pragma directive) +these will describe the location of the characters corresponding to the token +and the location where the token was used (i.e. the macro instantiation point +or the location of the _Pragma itself).

+ +

The Clang front-end inherently depends on the location of a token being +tracked correctly. If it is ever incorrect, the front-end may get confused and +die. The reason for this is that the notion of the 'spelling' of a Token in +Clang depends on being able to find the original input characters for the token. +This concept maps directly to the "spelling location" for the token.

+ + + +

SourceRange and CharSourceRange

+ + + +

Clang represents most source ranges by [first, last], where first and last +each point to the beginning of their respective tokens. For example +consider the SourceRange of the following statement:

+
+x = foo + bar;
+^first    ^last
+
+ +

To map from this representation to a character-based +representation, the 'last' location needs to be adjusted to point to +(or past) the end of that token with either +Lexer::MeasureTokenLength() or +Lexer::getLocForEndOfToken(). For the rare cases +where character-level source ranges information is needed we use +the CharSourceRange class.

+ + + +

The Driver Library

+ + +

The clang Driver and library are documented here.

+ + +

Precompiled Headers

+ + +

Clang supports two implementations of precompiled headers. The + default implementation, precompiled headers (PCH) uses a serialized representation + of Clang's internal data structures, encoded with the LLVM bitstream + format. Pretokenized headers (PTH), on the other hand, contain a + serialized representation of the tokens encountered when + preprocessing a header (and anything that header includes).

+ + + +

The Frontend Library

+ + +

The Frontend library contains functionality useful for building +tools on top of the clang libraries, for example several methods for +outputting diagnostics.

+ + +

The Lexer and Preprocessor Library

+ + +

The Lexer library contains several tightly-connected classes that are involved +with the nasty process of lexing and preprocessing C source code. The main +interface to this library for outside clients is the large Preprocessor class. +It contains the various pieces of state that are required to coherently read +tokens out of a translation unit.

+ +

The core interface to the Preprocessor object (once it is set up) is the +Preprocessor::Lex method, which returns the next Token from +the preprocessor stream. There are two types of token providers that the +preprocessor is capable of reading from: a buffer lexer (provided by the Lexer class) and a buffered token stream (provided by the TokenLexer class). + + + +

The Token class

+ + +

The Token class is used to represent a single lexed token. Tokens are +intended to be used by the lexer/preprocess and parser libraries, but are not +intended to live beyond them (for example, they should not live in the ASTs).

+ +

Tokens most often live on the stack (or some other location that is efficient +to access) as the parser is running, but occasionally do get buffered up. For +example, macro definitions are stored as a series of tokens, and the C++ +front-end periodically needs to buffer tokens up for tentative parsing and +various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit +system, sizeof(Token) is currently 16 bytes.

+ +

Tokens occur in two forms: "Annotation +Tokens" and normal tokens. Normal tokens are those returned by the lexer, +annotation tokens represent semantic information and are produced by the parser, +replacing normal tokens in the token stream. Normal tokens contain the +following information:

+ +
    +
  • A SourceLocation - This indicates the location of the start of the +token.
  • + +
  • A length - This stores the length of the token as stored in the +SourceBuffer. For tokens that include them, this length includes trigraphs and +escaped newlines which are ignored by later phases of the compiler. By pointing +into the original source buffer, it is always possible to get the original +spelling of a token completely accurately.
  • + +
  • IdentifierInfo - If a token takes the form of an identifier, and if +identifier lookup was enabled when the token was lexed (e.g. the lexer was not +reading in 'raw' mode) this contains a pointer to the unique hash value for the +identifier. Because the lookup happens before keyword identification, this +field is set even for language keywords like 'for'.
  • + +
  • TokenKind - This indicates the kind of token as classified by the +lexer. This includes things like tok::starequal (for the "*=" +operator), tok::ampamp for the "&&" token, and keyword values +(e.g. tok::kw_for) for identifiers that correspond to keywords. Note +that some tokens can be spelled multiple ways. For example, C++ supports +"operator keywords", where things like "and" are treated exactly like the +"&&" operator. In these cases, the kind value is set to +tok::ampamp, which is good for the parser, which doesn't have to +consider both forms. For something that cares about which form is used (e.g. +the preprocessor 'stringize' operator) the spelling indicates the original +form.
  • + +
  • Flags - There are currently four flags tracked by the +lexer/preprocessor system on a per-token basis: + +
      +
    1. StartOfLine - This was the first token that occurred on its input + source line.
    2. +
    3. LeadingSpace - There was a space character either immediately + before the token or transitively before the token as it was expanded + through a macro. The definition of this flag is very closely defined by + the stringizing requirements of the preprocessor.
    4. +
    5. DisableExpand - This flag is used internally to the preprocessor to + represent identifier tokens which have macro expansion disabled. This + prevents them from being considered as candidates for macro expansion ever + in the future.
    6. +
    7. NeedsCleaning - This flag is set if the original spelling for the + token includes a trigraph or escaped newline. Since this is uncommon, + many pieces of code can fast-path on tokens that did not need cleaning. +
    +
  • +
+ +

One interesting (and somewhat unusual) aspect of normal tokens is that they +don't contain any semantic information about the lexed value. For example, if +the token was a pp-number token, we do not represent the value of the number +that was lexed (this is left for later pieces of code to decide). Additionally, +the lexer library has no notion of typedef names vs variable names: both are +returned as identifiers, and the parser is left to decide whether a specific +identifier is a typedef or a variable (tracking this requires scope information +among other things). The parser can do this translation by replacing tokens +returned by the preprocessor with "Annotation Tokens".

+ + +

Annotation Tokens

+ + +

Annotation Tokens are tokens that are synthesized by the parser and injected +into the preprocessor's token stream (replacing existing tokens) to record +semantic information found by the parser. For example, if "foo" is found to be +a typedef, the "foo" tok::identifier token is replaced with an +tok::annot_typename. This is useful for a couple of reasons: 1) this +makes it easy to handle qualified type names (e.g. "foo::bar::baz<42>::t") +in C++ as a single "token" in the parser. 2) if the parser backtracks, the +reparse does not need to redo semantic analysis to determine whether a token +sequence is a variable, type, template, etc.

+ +

Annotation Tokens are created by the parser and reinjected into the parser's +token stream (when backtracking is enabled). Because they can only exist in +tokens that the preprocessor-proper is done with, it doesn't need to keep around +flags like "start of line" that the preprocessor uses to do its job. +Additionally, an annotation token may "cover" a sequence of preprocessor tokens +(e.g. a::b::c is five preprocessor tokens). As such, the valid fields +of an annotation token are different than the fields for a normal token (but +they are multiplexed into the normal Token fields):

+ +
    +
  • SourceLocation "Location" - The SourceLocation for the annotation +token indicates the first token replaced by the annotation token. In the example +above, it would be the location of the "a" identifier.
  • + +
  • SourceLocation "AnnotationEndLoc" - This holds the location of the +last token replaced with the annotation token. In the example above, it would +be the location of the "c" identifier.
  • + +
  • void* "AnnotationValue" - This contains an opaque object +that the parser gets from Sema. The parser merely preserves the +information for Sema to later interpret based on the annotation token +kind.
  • + +
  • TokenKind "Kind" - This indicates the kind of Annotation token this +is. See below for the different valid kinds.
  • +
+ +

Annotation tokens currently come in three kinds:

+ +
    +
  1. tok::annot_typename: This annotation token represents a +resolved typename token that is potentially qualified. The +AnnotationValue field contains the QualType returned by +Sema::getTypeName(), possibly with source location information +attached.
  2. + +
  3. tok::annot_cxxscope: This annotation token represents a C++ +scope specifier, such as "A::B::". This corresponds to the grammar +productions "::" and ":: [opt] nested-name-specifier". The +AnnotationValue pointer is a NestedNameSpecifier* returned by +the Sema::ActOnCXXGlobalScopeSpecifier and +Sema::ActOnCXXNestedNameSpecifier callbacks.
  4. + +
  5. tok::annot_template_id: This annotation token represents a +C++ template-id such as "foo<int, 4>", where "foo" is the name +of a template. The AnnotationValue pointer is a pointer to a malloc'd +TemplateIdAnnotation object. Depending on the context, a parsed +template-id that names a type might become a typename annotation token +(if all we care about is the named type, e.g., because it occurs in a +type specifier) or might remain a template-id token (if we want to +retain more source location information or produce a new type, e.g., +in a declaration of a class template specialization). template-id +annotation tokens that refer to a type can be "upgraded" to typename +annotation tokens by the parser.
  6. + +
+ +

As mentioned above, annotation tokens are not returned by the preprocessor, +they are formed on demand by the parser. This means that the parser has to be +aware of cases where an annotation could occur and form it where appropriate. +This is somewhat similar to how the parser handles Translation Phase 6 of C99: +String Concatenation (see C99 5.1.1.2). In the case of string concatenation, +the preprocessor just returns distinct tok::string_literal and +tok::wide_string_literal tokens and the parser eats a sequence of them wherever +the grammar indicates that a string literal can occur.

+ +

In order to do this, whenever the parser expects a tok::identifier or +tok::coloncolon, it should call the TryAnnotateTypeOrScopeToken or +TryAnnotateCXXScopeToken methods to form the annotation token. These methods +will maximally form the specified annotation tokens and replace the current +token with them, if applicable. If the current tokens is not valid for an +annotation token, it will remain an identifier or :: token.

+ + + + +

The Lexer class

+ + +

The Lexer class provides the mechanics of lexing tokens out of a source +buffer and deciding what they mean. The Lexer is complicated by the fact that +it operates on raw buffers that have not had spelling eliminated (this is a +necessity to get decent performance), but this is countered with careful coding +as well as standard performance techniques (for example, the comment handling +code is vectorized on X86 and PowerPC hosts).

+ +

The lexer has a couple of interesting modal features:

+ +
    +
  • The lexer can operate in 'raw' mode. This mode has several features that + make it possible to quickly lex the file (e.g. it stops identifier lookup, + doesn't specially handle preprocessor tokens, handles EOF differently, etc). + This mode is used for lexing within an "#if 0" block, for + example.
  • +
  • The lexer can capture and return comments as tokens. This is required to + support the -C preprocessor mode, which passes comments through, and is + used by the diagnostic checker to identifier expect-error annotations.
  • +
  • The lexer can be in ParsingFilename mode, which happens when preprocessing + after reading a #include directive. This mode changes the parsing of '<' + to return an "angled string" instead of a bunch of tokens for each thing + within the filename.
  • +
  • When parsing a preprocessor directive (after "#") the + ParsingPreprocessorDirective mode is entered. This changes the parser to + return EOD at a newline.
  • +
  • The Lexer uses a LangOptions object to know whether trigraphs are enabled, + whether C++ or ObjC keywords are recognized, etc.
  • +
+ +

In addition to these modes, the lexer keeps track of a couple of other + features that are local to a lexed buffer, which change as the buffer is + lexed:

+ +
    +
  • The Lexer uses BufferPtr to keep track of the current character being + lexed.
  • +
  • The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token + will start with its "start of line" bit set.
  • +
  • The Lexer keeps track of the current #if directives that are active (which + can be nested).
  • +
  • The Lexer keeps track of an + MultipleIncludeOpt object, which is used to + detect whether the buffer uses the standard "#ifndef XX / + #define XX" idiom to prevent multiple inclusion. If a buffer does, + subsequent includes can be ignored if the XX macro is defined.
  • +
+ + +

The TokenLexer class

+ + +

The TokenLexer class is a token provider that returns tokens from a list +of tokens that came from somewhere else. It typically used for two things: 1) +returning tokens from a macro definition as it is being expanded 2) returning +tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and +will most likely be used to handle unbounded look-ahead for the C++ parser.

+ + +

The MultipleIncludeOpt class

+ + +

The MultipleIncludeOpt class implements a really simple little state machine +that is used to detect the standard "#ifndef XX / #define XX" +idiom that people typically use to prevent multiple inclusion of headers. If a +buffer uses this idiom and is subsequently #include'd, the preprocessor can +simply check to see whether the guarding condition is defined or not. If so, +the preprocessor can completely ignore the include of the header.

+ + + + +

The Parser Library

+ + + +

The AST Library

+ + + +

The Type class and its subclasses

+ + +

The Type class (and its subclasses) are an important part of the AST. Types +are accessed through the ASTContext class, which implicitly creates and uniques +them as they are needed. Types have a couple of non-obvious features: 1) they +do not capture type qualifiers like const or volatile (See +QualType), and 2) they implicitly capture typedef +information. Once created, types are immutable (unlike decls).

+ +

Typedefs in C make semantic analysis a bit more complex than it would +be without them. The issue is that we want to capture typedef information +and represent it in the AST perfectly, but the semantics of operations need to +"see through" typedefs. For example, consider this code:

+ + +void func() {
+  typedef int foo;
+  foo X, *Y;
+  typedef foo* bar;
+  bar Z;
+  *X; // error
+  **Y; // error
+  **Z; // error
+}
+
+ +

The code above is illegal, and thus we expect there to be diagnostics emitted +on the annotated lines. In this example, we expect to get:

+ +
+test.c:6:1: error: indirection requires pointer operand ('foo' invalid)
+*X; // error
+^~
+test.c:7:1: error: indirection requires pointer operand ('foo' invalid)
+**Y; // error
+^~~
+test.c:8:1: error: indirection requires pointer operand ('foo' invalid)
+**Z; // error
+^~~
+
+ +

While this example is somewhat silly, it illustrates the point: we want to +retain typedef information where possible, so that we can emit errors about +"std::string" instead of "std::basic_string<char, std:...". +Doing this requires properly keeping typedef information (for example, the type +of "X" is "foo", not "int"), and requires properly propagating it through the +various operators (for example, the type of *Y is "foo", not "int"). In order +to retain this information, the type of these expressions is an instance of the +TypedefType class, which indicates that the type of these expressions is a +typedef for foo. +

+ +

Representing types like this is great for diagnostics, because the +user-specified type is always immediately available. There are two problems +with this: first, various semantic checks need to make judgements about the +actual structure of a type, ignoring typedefs. Second, we need an +efficient way to query whether two types are structurally identical to each +other, ignoring typedefs. The solution to both of these problems is the idea of +canonical types.

+ + +

Canonical Types

+ + +

Every instance of the Type class contains a canonical type pointer. For +simple types with no typedefs involved (e.g. "int", "int*", +"int**"), the type just points to itself. For types that have a +typedef somewhere in their structure (e.g. "foo", "foo*", +"foo**", "bar"), the canonical type pointer points to their +structurally equivalent type without any typedefs (e.g. "int", +"int*", "int**", and "int*" respectively).

+ +

This design provides a constant time operation (dereferencing the canonical +type pointer) that gives us access to the structure of types. For example, +we can trivially tell that "bar" and "foo*" are the same type by dereferencing +their canonical type pointers and doing a pointer comparison (they both point +to the single "int*" type).

+ +

Canonical types and typedef types bring up some complexities that must be +carefully managed. Specifically, the "isa/cast/dyncast" operators generally +shouldn't be used in code that is inspecting the AST. For example, when type +checking the indirection operator (unary '*' on a pointer), the type checker +must verify that the operand has a pointer type. It would not be correct to +check that with "isa<PointerType>(SubExpr->getType())", +because this predicate would fail if the subexpression had a typedef type.

+ +

The solution to this problem are a set of helper methods on Type, used to +check their properties. In this case, it would be correct to use +"SubExpr->getType()->isPointerType()" to do the check. This +predicate will return true if the canonical type is a pointer, which is +true any time the type is structurally a pointer type. The only hard part here +is remembering not to use the isa/cast/dyncast operations.

+ +

The second problem we face is how to get access to the pointer type once we +know it exists. To continue the example, the result type of the indirection +operator is the pointee type of the subexpression. In order to determine the +type, we need to get the instance of PointerType that best captures the typedef +information in the program. If the type of the expression is literally a +PointerType, we can return that, otherwise we have to dig through the +typedefs to find the pointer type. For example, if the subexpression had type +"foo*", we could return that type as the result. If the subexpression +had type "bar", we want to return "foo*" (note that we do +not want "int*"). In order to provide all of this, Type has +a getAsPointerType() method that checks whether the type is structurally a +PointerType and, if so, returns the best one. If not, it returns a null +pointer.

+ +

This structure is somewhat mystical, but after meditating on it, it will +make sense to you :).

+ + +

The QualType class

+ + +

The QualType class is designed as a trivial value class that is +small, passed by-value and is efficient to query. The idea of +QualType is that it stores the type qualifiers (const, volatile, +restrict, plus some extended qualifiers required by language +extensions) separately from the types themselves. QualType is +conceptually a pair of "Type*" and the bits for these type qualifiers.

+ +

By storing the type qualifiers as bits in the conceptual pair, it is +extremely efficient to get the set of qualifiers on a QualType (just return the +field of the pair), add a type qualifier (which is a trivial constant-time +operation that sets a bit), and remove one or more type qualifiers (just return +a QualType with the bitfield set to empty).

+ +

Further, because the bits are stored outside of the type itself, we do not +need to create duplicates of types with different sets of qualifiers (i.e. there +is only a single heap allocated "int" type: "const int" and "volatile const int" +both point to the same heap allocated "int" type). This reduces the heap size +used to represent bits and also means we do not have to consider qualifiers when +uniquing types (Type does not even contain qualifiers).

+ +

In practice, the two most common type qualifiers (const and +restrict) are stored in the low bits of the pointer to the Type +object, together with a flag indicating whether extended qualifiers +are present (which must be heap-allocated). This means that QualType +is exactly the same size as a pointer.

+ + +

Declaration names

+ + +

The DeclarationName class represents the name of a + declaration in Clang. Declarations in the C family of languages can + take several different forms. Most declarations are named by + simple identifiers, e.g., "f" and "x" in + the function declaration f(int x). In C++, declaration + names can also name class constructors ("Class" + in struct Class { Class(); }), class destructors + ("~Class"), overloaded operator names ("operator+"), + and conversion functions ("operator void const *"). In + Objective-C, declaration names can refer to the names of Objective-C + methods, which involve the method name and the parameters, + collectively called a selector, e.g., + "setWidth:height:". Since all of these kinds of + entities - variables, functions, Objective-C methods, C++ + constructors, destructors, and operators - are represented as + subclasses of Clang's common NamedDecl + class, DeclarationName is designed to efficiently + represent any kind of name.

+ +

Given + a DeclarationName N, N.getNameKind() + will produce a value that describes what kind of name N + stores. There are 8 options (all of the names are inside + the DeclarationName class)

+
+
Identifier
+
The name is a simple + identifier. Use N.getAsIdentifierInfo() to retrieve the + corresponding IdentifierInfo* pointing to the actual + identifier. Note that C++ overloaded operators (e.g., + "operator+") are represented as special kinds of + identifiers. Use IdentifierInfo's getOverloadedOperatorID + function to determine whether an identifier is an overloaded + operator name.
+ +
ObjCZeroArgSelector, ObjCOneArgSelector, + ObjCMultiArgSelector
+
The name is an Objective-C selector, which can be retrieved as a + Selector instance + via N.getObjCSelector(). The three possible name + kinds for Objective-C reflect an optimization within + the DeclarationName class: both zero- and + one-argument selectors are stored as a + masked IdentifierInfo pointer, and therefore require + very little space, since zero- and one-argument selectors are far + more common than multi-argument selectors (which use a different + structure).
+ +
CXXConstructorName
+
The name is a C++ constructor + name. Use N.getCXXNameType() to retrieve + the type that this constructor is meant to + construct. The type is always the canonical type, since all + constructors for a given type have the same name.
+ +
CXXDestructorName
+
The name is a C++ destructor + name. Use N.getCXXNameType() to retrieve + the type whose destructor is being + named. This type is always a canonical type.
+ +
CXXConversionFunctionName
+
The name is a C++ conversion function. Conversion functions are + named according to the type they convert to, e.g., "operator void + const *". Use N.getCXXNameType() to retrieve + the type that this conversion function converts to. This type is + always a canonical type.
+ +
CXXOperatorName
+
The name is a C++ overloaded operator name. Overloaded operators + are named according to their spelling, e.g., + "operator+" or "operator new + []". Use N.getCXXOverloadedOperator() to + retrieve the overloaded operator (a value of + type OverloadedOperatorKind).
+
+ +

DeclarationNames are cheap to create, copy, and + compare. They require only a single pointer's worth of storage in + the common cases (identifiers, zero- + and one-argument Objective-C selectors) and use dense, uniqued + storage for the other kinds of + names. Two DeclarationNames can be compared for + equality (==, !=) using a simple bitwise + comparison, can be ordered + with <, >, <=, + and >= (which provide a lexicographical ordering for + normal identifiers but an unspecified ordering for other kinds of + names), and can be placed into LLVM DenseMaps + and DenseSets.

+ +

DeclarationName instances can be created in different + ways depending on what kind of name the instance will store. Normal + identifiers (IdentifierInfo pointers) and Objective-C selectors + (Selector) can be implicitly converted + to DeclarationNames. Names for C++ constructors, + destructors, conversion functions, and overloaded operators can be retrieved from + the DeclarationNameTable, an instance of which is + available as ASTContext::DeclarationNames. The member + functions getCXXConstructorName, getCXXDestructorName, + getCXXConversionFunctionName, and getCXXOperatorName, respectively, + return DeclarationName instances for the four kinds of + C++ special function names.

+ + +

Declaration contexts

+ +

Every declaration in a program exists within some declaration + context, such as a translation unit, namespace, class, or + function. Declaration contexts in Clang are represented by + the DeclContext class, from which the various + declaration-context AST nodes + (TranslationUnitDecl, NamespaceDecl, RecordDecl, FunctionDecl, + etc.) will derive. The DeclContext class provides + several facilities common to each declaration context:

+
+
Source-centric vs. Semantics-centric View of Declarations
+
DeclContext provides two views of the declarations + stored within a declaration context. The source-centric view + accurately represents the program source code as written, including + multiple declarations of entities where present (see the + section Redeclarations and + Overloads), while the semantics-centric view represents the + program semantics. The two views are kept synchronized by semantic + analysis while the ASTs are being constructed.
+ +
Storage of declarations within that context
+
Every declaration context can contain some number of + declarations. For example, a C++ class (represented + by RecordDecl) contains various member functions, + fields, nested types, and so on. All of these declarations will be + stored within the DeclContext, and one can iterate + over the declarations via + [DeclContext::decls_begin(), + DeclContext::decls_end()). This mechanism provides + the source-centric view of declarations in the context.
+ +
Lookup of declarations within that context
+
The DeclContext structure provides efficient name + lookup for names within that declaration context. For example, + if N is a namespace we can look for the + name N::f + using DeclContext::lookup. The lookup itself is + based on a lazily-constructed array (for declaration contexts + with a small number of declarations) or hash table (for + declaration contexts with more declarations). The lookup + operation provides the semantics-centric view of the declarations + in the context.
+ +
Ownership of declarations
+
The DeclContext owns all of the declarations that + were declared within its declaration context, and is responsible + for the management of their memory as well as their + (de-)serialization.
+
+ +

All declarations are stored within a declaration context, and one + can query + information about the context in which each declaration lives. One + can retrieve the DeclContext that contains a + particular Decl + using Decl::getDeclContext. However, see the + section Lexical and Semantic + Contexts for more information about how to interpret this + context information.

+ +

Redeclarations and Overloads

+

Within a translation unit, it is common for an entity to be +declared several times. For example, we might declare a function "f" + and then later re-declare it as part of an inlined definition:

+ +
+void f(int x, int y, int z = 1);
+
+inline void f(int x, int y, int z) { /* ... */ }
+
+ +

The representation of "f" differs in the source-centric and + semantics-centric views of a declaration context. In the + source-centric view, all redeclarations will be present, in the + order they occurred in the source code, making + this view suitable for clients that wish to see the structure of + the source code. In the semantics-centric view, only the most recent "f" + will be found by the lookup, since it effectively replaces the first + declaration of "f".

+ +

In the semantics-centric view, overloading of functions is + represented explicitly. For example, given two declarations of a + function "g" that are overloaded, e.g.,

+
+void g();
+void g(int);
+
+

the DeclContext::lookup operation will return + a DeclContext::lookup_result that contains a range of iterators + over declarations of "g". Clients that perform semantic analysis on a + program that is not concerned with the actual source code will + primarily use this semantics-centric view.

+ +

Lexical and Semantic Contexts

+

Each declaration has two potentially different + declaration contexts: a lexical context, which corresponds to + the source-centric view of the declaration context, and + a semantic context, which corresponds to the + semantics-centric view. The lexical context is accessible + via Decl::getLexicalDeclContext while the + semantic context is accessible + via Decl::getDeclContext, both of which return + DeclContext pointers. For most declarations, the two + contexts are identical. For example:

+ +
+class X {
+public:
+  void f(int x);
+};
+
+ +

Here, the semantic and lexical contexts of X::f are + the DeclContext associated with the + class X (itself stored as a RecordDecl AST + node). However, we can now define X::f out-of-line:

+ +
+void X::f(int x = 17) { /* ... */ }
+
+ +

This definition of has different lexical and semantic + contexts. The lexical context corresponds to the declaration + context in which the actual declaration occurred in the source + code, e.g., the translation unit containing X. Thus, + this declaration of X::f can be found by traversing + the declarations provided by + [decls_begin(), decls_end()) in the + translation unit.

+ +

The semantic context of X::f corresponds to the + class X, since this member function is (semantically) a + member of X. Lookup of the name f into + the DeclContext associated with X will + then return the definition of X::f (including + information about the default argument).

+ +

Transparent Declaration Contexts

+

In C and C++, there are several contexts in which names that are + logically declared inside another declaration will actually "leak" + out into the enclosing scope from the perspective of name + lookup. The most obvious instance of this behavior is in + enumeration types, e.g.,

+
+enum Color {
+  Red, 
+  Green,
+  Blue
+};
+
+ +

Here, Color is an enumeration, which is a declaration + context that contains the + enumerators Red, Green, + and Blue. Thus, traversing the list of declarations + contained in the enumeration Color will + yield Red, Green, + and Blue. However, outside of the scope + of Color one can name the enumerator Red + without qualifying the name, e.g.,

+ +
+Color c = Red;
+
+ +

There are other entities in C++ that provide similar behavior. For + example, linkage specifications that use curly braces:

+ +
+extern "C" {
+  void f(int);
+  void g(int);
+}
+// f and g are visible here
+
+ +

For source-level accuracy, we treat the linkage specification and + enumeration type as a + declaration context in which its enclosed declarations ("Red", + "Green", and "Blue"; "f" and "g") + are declared. However, these declarations are visible outside of the + scope of the declaration context.

+ +

These language features (and several others, described below) have + roughly the same set of + requirements: declarations are declared within a particular lexical + context, but the declarations are also found via name lookup in + scopes enclosing the declaration itself. This feature is implemented + via transparent declaration contexts + (see DeclContext::isTransparentContext()), whose + declarations are visible in the nearest enclosing non-transparent + declaration context. This means that the lexical context of the + declaration (e.g., an enumerator) will be the + transparent DeclContext itself, as will the semantic + context, but the declaration will be visible in every outer context + up to and including the first non-transparent declaration context (since + transparent declaration contexts can be nested).

+ +

The transparent DeclContexts are:

+
    +
  • Enumerations (but not C++11 "scoped enumerations"): +
    +enum Color { 
    +  Red, 
    +  Green, 
    +  Blue 
    +};
    +// Red, Green, and Blue are in scope
    +  
  • +
  • C++ linkage specifications: +
    +extern "C" {
    +  void f(int);
    +  void g(int);
    +}
    +// f and g are in scope
    +  
  • +
  • Anonymous unions and structs: +
    +struct LookupTable {
    +  bool IsVector;
    +  union {
    +    std::vector<Item> *Vector;
    +    std::set<Item> *Set;
    +  };
    +};
    +
    +LookupTable LT;
    +LT.Vector = 0; // Okay: finds Vector inside the unnamed union
    +    
    +
  • +
  • C++11 inline namespaces: +
    +namespace mylib {
    +  inline namespace debug {
    +    class X;
    +  }
    +}
    +mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
    +
    +
  • +
+ + +

Multiply-Defined Declaration Contexts

+

C++ namespaces have the interesting--and, so far, unique--property that +the namespace can be defined multiple times, and the declarations +provided by each namespace definition are effectively merged (from +the semantic point of view). For example, the following two code +snippets are semantically indistinguishable:

+
+// Snippet #1:
+namespace N {
+  void f();
+}
+namespace N {
+  void f(int);
+}
+
+// Snippet #2:
+namespace N {
+  void f();
+  void f(int);
+}
+
+ +

In Clang's representation, the source-centric view of declaration + contexts will actually have two separate NamespaceDecl + nodes in Snippet #1, each of which is a declaration context that + contains a single declaration of "f". However, the semantics-centric + view provided by name lookup into the namespace N for + "f" will return a DeclContext::lookup_result that contains + a range of iterators over declarations of "f".

+ +

DeclContext manages multiply-defined declaration + contexts internally. The + function DeclContext::getPrimaryContext retrieves the + "primary" context for a given DeclContext instance, + which is the DeclContext responsible for maintaining + the lookup table used for the semantics-centric view. Given the + primary context, one can follow the chain + of DeclContext nodes that define additional + declarations via DeclContext::getNextContext. Note that + these functions are used internally within the lookup and insertion + methods of the DeclContext, so the vast majority of + clients can ignore them.

+ + +

The CFG class

+ + +

The CFG class is designed to represent a source-level +control-flow graph for a single statement (Stmt*). Typically +instances of CFG are constructed for function bodies (usually +an instance of CompoundStmt), but can also be instantiated to +represent the control-flow of any class that subclasses Stmt, +which includes simple expressions. Control-flow graphs are especially +useful for performing +flow- +or path-sensitive program analyses on a given function.

+ + +

Basic Blocks

+ + +

Concretely, an instance of CFG is a collection of basic +blocks. Each basic block is an instance of CFGBlock, which +simply contains an ordered sequence of Stmt* (each referring +to statements in the AST). The ordering of statements within a block +indicates unconditional flow of control from one statement to the +next. Conditional control-flow +is represented using edges between basic blocks. The statements +within a given CFGBlock can be traversed using +the CFGBlock::*iterator interface.

+ +

+A CFG object owns the instances of CFGBlock within +the control-flow graph it represents. Each CFGBlock within a +CFG is also uniquely numbered (accessible +via CFGBlock::getBlockID()). Currently the number is +based on the ordering the blocks were created, but no assumptions +should be made on how CFGBlocks are numbered other than their +numbers are unique and that they are numbered from 0..N-1 (where N is +the number of basic blocks in the CFG).

+ + +

Entry and Exit Blocks

+ + +Each instance of CFG contains two special blocks: +an entry block (accessible via CFG::getEntry()), which +has no incoming edges, and an exit block (accessible +via CFG::getExit()), which has no outgoing edges. Neither +block contains any statements, and they serve the role of providing a +clear entrance and exit for a body of code such as a function body. +The presence of these empty blocks greatly simplifies the +implementation of many analyses built on top of CFGs. + + +

Conditional Control-Flow

+ + +

Conditional control-flow (such as those induced by if-statements +and loops) is represented as edges between CFGBlocks. +Because different C language constructs can induce control-flow, +each CFGBlock also records an extra Stmt* that +represents the terminator of the block. A terminator is simply +the statement that caused the control-flow, and is used to identify +the nature of the conditional control-flow between blocks. For +example, in the case of an if-statement, the terminator refers to +the IfStmt object in the AST that represented the given +branch.

+ +

To illustrate, consider the following code example:

+ + +int foo(int x) {
+  x = x + 1;
+
+  if (x > 2) x++;
+  else {
+    x += 2;
+    x *= 2;
+  }
+
+  return x;
+} +
+ +

After invoking the parser+semantic analyzer on this code fragment, +the AST of the body of foo is referenced by a +single Stmt*. We can then construct an instance +of CFG representing the control-flow graph of this function +body by single call to a static class method:

+ + +  Stmt* FooBody = ...
+  CFG* FooCFG = CFG::buildCFG(FooBody); +
+ +

It is the responsibility of the caller of CFG::buildCFG +to delete the returned CFG* when the CFG is no +longer needed.

+ +

Along with providing an interface to iterate over +its CFGBlocks, the CFG class also provides methods +that are useful for debugging and visualizing CFGs. For example, the +method +CFG::dump() dumps a pretty-printed version of the CFG to +standard error. This is especially useful when one is using a +debugger such as gdb. For example, here is the output +of FooCFG->dump():

+ + + [ B5 (ENTRY) ]
+    Predecessors (0):
+    Successors (1): B4
+
+ [ B4 ]
+    1: x = x + 1
+    2: (x > 2)
+    T: if [B4.2]
+    Predecessors (1): B5
+    Successors (2): B3 B2
+
+ [ B3 ]
+    1: x++
+    Predecessors (1): B4
+    Successors (1): B1
+
+ [ B2 ]
+    1: x += 2
+    2: x *= 2
+    Predecessors (1): B4
+    Successors (1): B1
+
+ [ B1 ]
+    1: return x;
+    Predecessors (2): B2 B3
+    Successors (1): B0
+
+ [ B0 (EXIT) ]
+    Predecessors (1): B1
+    Successors (0): +
+ +

For each block, the pretty-printed output displays for each block +the number of predecessor blocks (blocks that have outgoing +control-flow to the given block) and successor blocks (blocks +that have control-flow that have incoming control-flow from the given +block). We can also clearly see the special entry and exit blocks at +the beginning and end of the pretty-printed output. For the entry +block (block B5), the number of predecessor blocks is 0, while for the +exit block (block B0) the number of successor blocks is 0.

+ +

The most interesting block here is B4, whose outgoing control-flow +represents the branching caused by the sole if-statement +in foo. Of particular interest is the second statement in +the block, (x > 2), and the terminator, printed +as if [B4.2]. The second statement represents the +evaluation of the condition of the if-statement, which occurs before +the actual branching of control-flow. Within the CFGBlock +for B4, the Stmt* for the second statement refers to the +actual expression in the AST for (x > 2). Thus +pointers to subclasses of Expr can appear in the list of +statements in a block, and not just subclasses of Stmt that +refer to proper C statements.

+ +

The terminator of block B4 is a pointer to the IfStmt +object in the AST. The pretty-printer outputs if +[B4.2] because the condition expression of the if-statement +has an actual place in the basic block, and thus the terminator is +essentially +referring to the expression that is the second statement of +block B4 (i.e., B4.2). In this manner, conditions for control-flow +(which also includes conditions for loops and switch statements) are +hoisted into the actual basic block.

+ + + + + + + + + +

Constant Folding in the Clang AST

+ + +

There are several places where constants and constant folding matter a lot to +the Clang front-end. First, in general, we prefer the AST to retain the source +code as close to how the user wrote it as possible. This means that if they +wrote "5+4", we want to keep the addition and two constants in the AST, we don't +want to fold to "9". This means that constant folding in various ways turns +into a tree walk that needs to handle the various cases.

+ +

However, there are places in both C and C++ that require constants to be +folded. For example, the C standard defines what an "integer constant +expression" (i-c-e) is with very precise and specific requirements. The +language then requires i-c-e's in a lot of places (for example, the size of a +bitfield, the value for a case statement, etc). For these, we have to be able +to constant fold the constants, to do semantic checks (e.g. verify bitfield size +is non-negative and that case statements aren't duplicated). We aim for Clang +to be very pedantic about this, diagnosing cases when the code does not use an +i-c-e where one is required, but accepting the code unless running with +-pedantic-errors.

+ +

Things get a little bit more tricky when it comes to compatibility with +real-world source code. Specifically, GCC has historically accepted a huge +superset of expressions as i-c-e's, and a lot of real world code depends on this +unfortuate accident of history (including, e.g., the glibc system headers). GCC +accepts anything its "fold" optimizer is capable of reducing to an integer +constant, which means that the definition of what it accepts changes as its +optimizer does. One example is that GCC accepts things like "case X-X:" even +when X is a variable, because it can fold this to 0.

+ +

Another issue are how constants interact with the extensions we support, such +as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99 +obviously does not specify the semantics of any of these extensions, and the +definition of i-c-e does not include them. However, these extensions are often +used in real code, and we have to have a way to reason about them.

+ +

Finally, this is not just a problem for semantic analysis. The code +generator and other clients have to be able to fold constants (e.g. to +initialize global variables) and has to handle a superset of what C99 allows. +Further, these clients can benefit from extended information. For example, we +know that "foo()||1" always evaluates to true, but we can't replace the +expression with true because it has side effects.

+ + +

Implementation Approach

+ + +

After trying several different approaches, we've finally converged on a +design (Note, at the time of this writing, not all of this has been implemented, +consider this a design goal!). Our basic approach is to define a single +recursive method evaluation method (Expr::Evaluate), which is +implemented in AST/ExprConstant.cpp. Given an expression with 'scalar' +type (integer, fp, complex, or pointer) this method returns the following +information:

+ +
    +
  • Whether the expression is an integer constant expression, a general + constant that was folded but has no side effects, a general constant that + was folded but that does have side effects, or an uncomputable/unfoldable + value. +
  • +
  • If the expression was computable in any way, this method returns the APValue + for the result of the expression.
  • +
  • If the expression is not evaluatable at all, this method returns + information on one of the problems with the expression. This includes a + SourceLocation for where the problem is, and a diagnostic ID that explains + the problem. The diagnostic should be have ERROR type.
  • +
  • If the expression is not an integer constant expression, this method returns + information on one of the problems with the expression. This includes a + SourceLocation for where the problem is, and a diagnostic ID that explains + the problem. The diagnostic should be have EXTENSION type.
  • +
+ +

This information gives various clients the flexibility that they want, and we +will eventually have some helper methods for various extensions. For example, +Sema should have a Sema::VerifyIntegerConstantExpression method, which +calls Evaluate on the expression. If the expression is not foldable, the error +is emitted, and it would return true. If the expression is not an i-c-e, the +EXTENSION diagnostic is emitted. Finally it would return false to indicate that +the AST is ok.

+ +

Other clients can use the information in other ways, for example, codegen can +just use expressions that are foldable in any way.

+ + +

Extensions

+ + +

This section describes how some of the various extensions Clang supports +interacts with constant evaluation:

+ +
    +
  • __extension__: The expression form of this extension causes + any evaluatable subexpression to be accepted as an integer constant + expression.
  • +
  • __builtin_constant_p: This returns true (as a integer + constant expression) if the operand evaluates to either a numeric value + (that is, not a pointer cast to integral type) of integral, enumeration, + floating or complex type, or if it evaluates to the address of the first + character of a string literal (possibly cast to some other type). As a + special case, if __builtin_constant_p is the (potentially + parenthesized) condition of a conditional operator expression ("?:"), only + the true side of the conditional operator is considered, and it is evaluated + with full constant folding.
  • +
  • __builtin_choose_expr: The condition is required to be an + integer constant expression, but we accept any constant as an "extension of + an extension". This only evaluates one operand depending on which way the + condition evaluates.
  • +
  • __builtin_classify_type: This always returns an integer + constant expression.
  • +
  • __builtin_inf,nan,..: These are treated just like a + floating-point literal.
  • +
  • __builtin_abs,copysign,..: These are constant folded as + general constant expressions.
  • +
  • __builtin_strlen and strlen: These are + constant folded as integer constant expressions if the argument is a string + literal.
  • +
+ + + +

How to change Clang

+ + + +

How to add an attribute

+ + +

To add an attribute, you'll have to add it to the list of attributes, add it +to the parsing phase, and look for it in the AST scan. +r124217 +has a good example of adding a warning attribute.

+ +

(Beware that this hasn't been reviewed/fixed by the people who designed the +attributes system yet.)

+ +

include/clang/Basic/Attr.td

+ +

Each attribute gets a def inheriting from Attr or one of +its subclasses. InheritableAttr means that the attribute also applies +to subsequent declarations of the same name.

+ +

Spellings lists the strings that can appear in +__attribute__((here)) or [[here]]. All such strings +will be synonymous. If you want to allow the [[]] C++11 +syntax, you have to define a list of Namespaces, which will +let users write [[namespace:spelling]]. Using the empty +string for a namespace will allow users to write just the spelling +with no ":".

+ +

Subjects restricts what kinds of AST node to which this attribute +can appertain (roughly, attach).

+ +

Args names the arguments the attribute takes, in order. If +Args is [StringArgument<"Arg1">, IntArgument<"Arg2">] +then __attribute__((myattribute("Hello", 3))) will be a valid use.

+ +

Boilerplate

+ +

Add an element to the AttributeList::Kind enum in include/clang/Sema/AttributeList.h +named AT_lower_with_underscores. That is, a CamelCased +AttributeName in Attr.td name should become +AT_attribute_name.

+ +

Add a case to the StringSwitch in AttributeList::getKind() +in lib/Sema/AttributeList.cpp +for each spelling of your attribute. Less common attributes should come toward +the end of that list.

+ +

Write a new HandleYourAttr() function in lib/Sema/SemaDeclAttr.cpp, +and add a case to the switch in ProcessNonInheritableDeclAttr() or +ProcessInheritableDeclAttr() forwarding to it.

+ +

If your attribute causes extra warnings to fire, define a DiagGroup +in include/clang/Basic/DiagnosticGroups.td +named after the attribute's Spelling with "_"s replaced by "-"s. If +you're only defining one diagnostic, you can skip DiagnosticGroups.td +and use InGroup<DiagGroup<"your-attribute">> directly in DiagnosticSemaKinds.td

+ +

The meat of your attribute

+ +

Find an appropriate place in Clang to do whatever your attribute needs to do. +Check for the attribute's presence using Decl::getAttr<YourAttr>().

+ +

Update the Clang Language Extensions +document to describe your new attribute.

+ + +

How to add an expression or statement

+ + +

Expressions and statements are one of the most fundamental constructs within a +compiler, because they interact with many different parts of the AST, +semantic analysis, and IR generation. Therefore, adding a new +expression or statement kind into Clang requires some care. The following list +details the various places in Clang where an expression or statement needs to be +introduced, along with patterns to follow to ensure that the new +expression or statement works well across all of the C languages. We +focus on expressions, but statements are similar.

+ +
    +
  1. Introduce parsing actions into the parser. Recursive-descent + parsing is mostly self-explanatory, but there are a few things that + are worth keeping in mind: +
      +
    • Keep as much source location information as possible! You'll + want it later to produce great diagnostics and support Clang's + various features that map between source code and the AST.
    • +
    • Write tests for all of the "bad" parsing cases, to make sure + your recovery is good. If you have matched delimiters (e.g., + parentheses, square brackets, etc.), use + Parser::BalancedDelimiterTracker to give nice diagnostics when + things go wrong.
    • +
    +
  2. + +
  3. Introduce semantic analysis actions into Sema. Semantic + analysis should always involve two functions: an ActOnXXX + function that will be called directly from the parser, and a + BuildXXX function that performs the actual semantic + analysis and will (eventually!) build the AST node. It's fairly + common for the ActOnCXX function to do very little (often + just some minor translation from the parser's representation to + Sema's representation of the same thing), but the separation + is still important: C++ template instantiation, for example, + should always call the BuildXXX variant. Several notes on + semantic analysis before we get into construction of the AST: +
      +
    • Your expression probably involves some types and some + subexpressions. Make sure to fully check that those types, and the + types of those subexpressions, meet your expectations. Add + implicit conversions where necessary to make sure that all of the + types line up exactly the way you want them. Write extensive tests + to check that you're getting good diagnostics for mistakes and + that you can use various forms of subexpressions with your + expression.
    • +
    • When type-checking a type or subexpression, make sure to first + check whether the type is "dependent" + (Type::isDependentType()) or whether a subexpression is + type-dependent (Expr::isTypeDependent()). If any of these + return true, then you're inside a template and you can't do much + type-checking now. That's normal, and your AST node (when you get + there) will have to deal with this case. At this point, you can + write tests that use your expression within templates, but don't + try to instantiate the templates.
    • +
    • For each subexpression, be sure to call + Sema::CheckPlaceholderExpr() to deal with "weird" + expressions that don't behave well as subexpressions. Then, + determine whether you need to perform + lvalue-to-rvalue conversions + (Sema::DefaultLvalueConversione) or + the usual unary conversions + (Sema::UsualUnaryConversions), for places where the + subexpression is producing a value you intend to use.
    • +
    • Your BuildXXX function will probably just return + ExprError() at this point, since you don't have an AST. + That's perfectly fine, and shouldn't impact your testing.
    • +
    +
  4. + +
  5. Introduce an AST node for your new expression. This starts with + declaring the node in include/Basic/StmtNodes.td and + creating a new class for your expression in the appropriate + include/AST/Expr*.h header. It's best to look at the class + for a similar expression to get ideas, and there are some specific + things to watch for: +
      +
    • If you need to allocate memory, use the ASTContext + allocator to allocate memory. Never use raw malloc or + new, and never hold any resources in an AST node, because + the destructor of an AST node is never called.
    • + +
    • Make sure that getSourceRange() covers the exact + source range of your expression. This is needed for diagnostics + and for IDE support.
    • + +
    • Make sure that children() visits all of the + subexpressions. This is important for a number of features (e.g., IDE + support, C++ variadic templates). If you have sub-types, you'll + also need to visit those sub-types in the + RecursiveASTVisitor.
    • + +
    • Add printing support (StmtPrinter.cpp) and dumping + support (StmtDumper.cpp) for your expression.
    • + +
    • Add profiling support (StmtProfile.cpp) for your AST + node, noting the distinguishing (non-source location) + characteristics of an instance of your expression. Omitting this + step will lead to hard-to-diagnose failures regarding matching of + template declarations.
    • +
    +
  6. + +
  7. Teach semantic analysis to build your AST node! At this point, + you can wire up your Sema::BuildXXX function to actually + create your AST. A few things to check at this point: +
      +
    • If your expression can construct a new C++ class or return a + new Objective-C object, be sure to update and then call + Sema::MaybeBindToTemporary for your just-created AST node + to be sure that the object gets properly destructed. An easy way + to test this is to return a C++ class with a private destructor: + semantic analysis should flag an error here with the attempt to + call the destructor.
    • +
    • Inspect the generated AST by printing it using clang -cc1 + -ast-print, to make sure you're capturing all of the + important information about how the AST was written.
    • +
    • Inspect the generated AST under clang -cc1 -ast-dump + to verify that all of the types in the generated AST line up the + way you want them. Remember that clients of the AST should never + have to "think" to understand what's going on. For example, all + implicit conversions should show up explicitly in the AST.
    • +
    • Write tests that use your expression as a subexpression of + other, well-known expressions. Can you call a function using your + expression as an argument? Can you use the ternary operator?
    • +
    +
  8. + +
  9. Teach code generation to create IR to your AST node. This step + is the first (and only) that requires knowledge of LLVM IR. There + are several things to keep in mind: +
      +
    • Code generation is separated into scalar/aggregate/complex and + lvalue/rvalue paths, depending on what kind of result your + expression produces. On occasion, this requires some careful + factoring of code to avoid duplication.
    • + +
    • CodeGenFunction contains functions + ConvertType and ConvertTypeForMem that convert + Clang's types (clang::Type* or clang::QualType) + to LLVM types. + Use the former for values, and the later for memory locations: + test with the C++ "bool" type to check this. If you find + that you are having to use LLVM bitcasts to make + the subexpressions of your expression have the type that your + expression expects, STOP! Go fix semantic analysis and the AST so + that you don't need these bitcasts.
    • + +
    • The CodeGenFunction class has a number of helper + functions to make certain operations easy, such as generating code + to produce an lvalue or an rvalue, or to initialize a memory + location with a given value. Prefer to use these functions rather + than directly writing loads and stores, because these functions + take care of some of the tricky details for you (e.g., for + exceptions).
    • + +
    • If your expression requires some special behavior in the event + of an exception, look at the push*Cleanup functions in + CodeGenFunction to introduce a cleanup. You shouldn't + have to deal with exception-handling directly.
    • + +
    • Testing is extremely important in IR generation. Use clang + -cc1 -emit-llvm and FileCheck to verify + that you're generating the right IR.
    • +
    +
  10. + +
  11. Teach template instantiation how to cope with your AST + node, which requires some fairly simple code: +
      +
    • Make sure that your expression's constructor properly + computes the flags for type dependence (i.e., the type your + expression produces can change from one instantiation to the + next), value dependence (i.e., the constant value your expression + produces can change from one instantiation to the next), + instantiation dependence (i.e., a template parameter occurs + anywhere in your expression), and whether your expression contains + a parameter pack (for variadic templates). Often, computing these + flags just means combining the results from the various types and + subexpressions.
    • + +
    • Add TransformXXX and RebuildXXX functions to + the + TreeTransform class template in Sema. + TransformXXX should (recursively) transform all of the + subexpressions and types + within your expression, using getDerived().TransformYYY. + If all of the subexpressions and types transform without error, it + will then call the RebuildXXX function, which will in + turn call getSema().BuildXXX to perform semantic analysis + and build your expression.
    • + +
    • To test template instantiation, take those tests you wrote to + make sure that you were type checking with type-dependent + expressions and dependent types (from step #2) and instantiate + those templates with various types, some of which type-check and + some that don't, and test the error messages in each case.
    • +
    +
  12. + +
  13. There are some "extras" that make other features work better. + It's worth handling these extras to give your expression complete + integration into Clang: +
      +
    • Add code completion support for your expression in + SemaCodeComplete.cpp.
    • + +
    • If your expression has types in it, or has any "interesting" + features other than subexpressions, extend libclang's + CursorVisitor to provide proper visitation for your + expression, enabling various IDE features such as syntax + highlighting, cross-referencing, and so on. The + c-index-test helper program can be used to test these + features.
    • +
    +
  14. +
+ +
+ + diff --git a/cpp/llvm/tools/clang/docs/LanguageExtensions.html b/cpp/llvm/tools/clang/docs/LanguageExtensions.html new file mode 100644 index 00000000..68f0afc1 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/LanguageExtensions.html @@ -0,0 +1,1810 @@ + + + + + + Clang Language Extensions + + + + + + + + +
+ +

Clang Language Extensions

+ + + + +

Introduction

+ + +

This document describes the language extensions provided by Clang. In +addition to the language extensions listed here, Clang aims to support a broad +range of GCC extensions. Please see the GCC manual for +more information on these extensions.

+ + +

Feature Checking Macros

+ + +

Language extensions can be very useful, but only if you know you can depend +on them. In order to allow fine-grain features checks, we support three builtin +function-like macros. This allows you to directly test for a feature in your +code without having to resort to something like autoconf or fragile "compiler +version checks".

+ + +

__has_builtin

+ + +

This function-like macro takes a single identifier argument that is the name +of a builtin function. It evaluates to 1 if the builtin is supported or 0 if +not. It can be used like this:

+ +
+
+#ifndef __has_builtin         // Optional of course.
+  #define __has_builtin(x) 0  // Compatibility with non-clang compilers.
+#endif
+
+...
+#if __has_builtin(__builtin_trap)
+  __builtin_trap();
+#else
+  abort();
+#endif
+...
+
+
+ + + +

__has_feature and __has_extension

+ + +

These function-like macros take a single identifier argument that is the +name of a feature. __has_feature evaluates to 1 if the feature +is both supported by Clang and standardized in the current language standard +or 0 if not (but see below), while +__has_extension evaluates to 1 if the feature is supported by +Clang in the current language (either as a language extension or a standard +language feature) or 0 if not. They can be used like this:

+ +
+
+#ifndef __has_feature         // Optional of course.
+  #define __has_feature(x) 0  // Compatibility with non-clang compilers.
+#endif
+#ifndef __has_extension
+  #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
+#endif
+
+...
+#if __has_feature(cxx_rvalue_references)
+// This code will only be compiled with the -std=c++11 and -std=gnu++11
+// options, because rvalue references are only standardized in C++11.
+#endif
+
+#if __has_extension(cxx_rvalue_references)
+// This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
+// and -std=gnu++98 options, because rvalue references are supported as a
+// language extension in C++98.
+#endif
+
+
+ +

For backwards compatibility reasons, +__has_feature can also be used to test for support for +non-standardized features, i.e. features not prefixed c_, +cxx_ or objc_.

+ +

+Another use of __has_feature is to check for compiler features +not related to the language standard, such as e.g. +AddressSanitizer. + +

If the -pedantic-errors option is given, +__has_extension is equivalent to __has_feature.

+ +

The feature tag is described along with the language feature below.

+ +

The feature name or extension name can also be specified with a preceding and +following __ (double underscore) to avoid interference from a macro +with the same name. For instance, __cxx_rvalue_references__ can be +used instead of cxx_rvalue_references.

+ + +

__has_attribute

+ + +

This function-like macro takes a single identifier argument that is the name +of an attribute. It evaluates to 1 if the attribute is supported or 0 if not. It +can be used like this:

+ +
+
+#ifndef __has_attribute         // Optional of course.
+  #define __has_attribute(x) 0  // Compatibility with non-clang compilers.
+#endif
+
+...
+#if __has_attribute(always_inline)
+#define ALWAYS_INLINE __attribute__((always_inline))
+#else
+#define ALWAYS_INLINE
+#endif
+...
+
+
+ +

The attribute name can also be specified with a preceding and +following __ (double underscore) to avoid interference from a macro +with the same name. For instance, __always_inline__ can be used +instead of always_inline.

+ + +

Include File Checking Macros

+ + +

Not all developments systems have the same include files. +The __has_include and +__has_include_next macros allow you to +check for the existence of an include file before doing +a possibly failing #include directive.

+ + +

__has_include

+ + +

This function-like macro takes a single file name string argument that +is the name of an include file. It evaluates to 1 if the file can +be found using the include paths, or 0 otherwise:

+ +
+
+// Note the two possible file name string formats.
+#if __has_include("myinclude.h") && __has_include(<stdint.h>)
+# include "myinclude.h"
+#endif
+
+// To avoid problem with non-clang compilers not having this macro.
+#if defined(__has_include) && __has_include("myinclude.h")
+# include "myinclude.h"
+#endif
+
+
+ +

To test for this feature, use #if defined(__has_include).

+ + +

__has_include_next

+ + +

This function-like macro takes a single file name string argument that +is the name of an include file. It is like __has_include except that it +looks for the second instance of the given file found in the include +paths. It evaluates to 1 if the second instance of the file can +be found using the include paths, or 0 otherwise:

+ +
+
+// Note the two possible file name string formats.
+#if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
+# include_next "myinclude.h"
+#endif
+
+// To avoid problem with non-clang compilers not having this macro.
+#if defined(__has_include_next) && __has_include_next("myinclude.h")
+# include_next "myinclude.h"
+#endif
+
+
+ +

Note that __has_include_next, like the GNU extension +#include_next directive, is intended for use in headers only, +and will issue a warning if used in the top-level compilation +file. A warning will also be issued if an absolute path +is used in the file argument.

+ + + +

__has_warning

+ + +

This function-like macro takes a string literal that represents a command + line option for a warning and returns true if that is a valid warning + option.

+ +
+
+#if __has_warning("-Wformat")
+...
+#endif
+
+
+ + +

Builtin Macros

+ + +
+
__BASE_FILE__
+
Defined to a string that contains the name of the main input + file passed to Clang.
+ +
__COUNTER__
+
Defined to an integer value that starts at zero and is + incremented each time the __COUNTER__ macro is + expanded.
+ +
__INCLUDE_LEVEL__
+
Defined to an integral value that is the include depth of the + file currently being translated. For the main file, this value is + zero.
+ +
__TIMESTAMP__
+
Defined to the date and time of the last modification of the + current source file.
+ +
__clang__
+
Defined when compiling with Clang
+ +
__clang_major__
+
Defined to the major marketing version number of Clang (e.g., the + 2 in 2.0.1). Note that marketing version numbers should not be used to + check for language features, as different vendors use different numbering + schemes. Instead, use the feature checking + macros.
+ +
__clang_minor__
+
Defined to the minor version number of Clang (e.g., the 0 in + 2.0.1). Note that marketing version numbers should not be used to + check for language features, as different vendors use different numbering + schemes. Instead, use the feature checking + macros.
+ +
__clang_patchlevel__
+
Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
+ +
__clang_version__
+
Defined to a string that captures the Clang marketing version, including + the Subversion tag or revision number, e.g., "1.5 (trunk 102332)".
+
+ + +

Vectors and Extended Vectors

+ + +

Supports the GCC, OpenCL, AltiVec and NEON vector extensions.

+ +

OpenCL vector types are created using ext_vector_type attribute. It +support for V.xyzw syntax and other tidbits as seen in OpenCL. An +example is:

+ +
+
+typedef float float4 __attribute__((ext_vector_type(4)));
+typedef float float2 __attribute__((ext_vector_type(2)));
+
+float4 foo(float2 a, float2 b) {
+  float4 c;
+  c.xz = a;
+  c.yw = b;
+  return c;
+}
+
+
+ +

Query for this feature with +__has_extension(attribute_ext_vector_type).

+ +

Giving -faltivec option to clang enables support for AltiVec vector +syntax and functions. For example:

+ +
+
+vector float foo(vector int a) { 
+  vector int b;
+  b = vec_add(a, a) + a; 
+  return (vector float)b;
+}
+
+
+ +

NEON vector types are created using neon_vector_type and +neon_polyvector_type attributes. For example:

+ +
+
+typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
+typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
+
+int8x8_t foo(int8x8_t a) {
+  int8x8_t v;
+  v = a;
+  return v;
+}
+
+
+ + +

Vector Literals

+ + +

Vector literals can be used to create vectors from a set of scalars, or +vectors. Either parentheses or braces form can be used. In the parentheses form +the number of literal values specified must be one, i.e. referring to a scalar +value, or must match the size of the vector type being created. If a single +scalar literal value is specified, the scalar literal value will be replicated +to all the components of the vector type. In the brackets form any number of +literals can be specified. For example:

+ +
+
+typedef int v4si __attribute__((__vector_size__(16)));
+typedef float float4 __attribute__((ext_vector_type(4)));
+typedef float float2 __attribute__((ext_vector_type(2)));
+
+v4si vsi = (v4si){1, 2, 3, 4};
+float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
+vector int vi1 = (vector int)(1);    // vi1 will be (1, 1, 1, 1).
+vector int vi2 = (vector int){1};    // vi2 will be (1, 0, 0, 0).
+vector int vi3 = (vector int)(1, 2); // error
+vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
+vector int vi5 = (vector int)(1, 2, 3, 4);
+float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
+
+
+ + +

Vector Operations

+ + +

The table below shows the support for each operation by vector extension. +A dash indicates that an operation is not accepted according to a corresponding +specification.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorOpenCLAltiVecGCCNEON
[]yesyesyes-
unary operators +, -yesyesyes-
++, --yesyes--
+, -, *, /, %yesyesyes-
bitwise operators &, |, ^, ~yesyesyes-
>>, <<yesyesyes-
!, &&,||no---
==,!=, >, <, >=, <=yesyes--
=yesyesyesyes
:?yes---
sizeofyesyesyesyes
+ +

See also __builtin_shufflevector.

+ + +

Messages on deprecated and unavailable Attributes

+ + +

An optional string message can be added to the deprecated +and unavailable attributes. For example:

+ +
+
void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
+
+ +

If the deprecated or unavailable declaration is used, the message +will be incorporated into the appropriate diagnostic:

+ +
+
harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
+      [-Wdeprecated-declarations]
+  explode();
+  ^
+
+ +

Query for this feature +with __has_extension(attribute_deprecated_with_message) +and __has_extension(attribute_unavailable_with_message).

+ + +

Attributes on Enumerators

+ + +

Clang allows attributes to be written on individual enumerators. +This allows enumerators to be deprecated, made unavailable, etc. The +attribute must appear after the enumerator name and before any +initializer, like so:

+ +
+
enum OperationMode {
+  OM_Invalid,
+  OM_Normal,
+  OM_Terrified __attribute__((deprecated)),
+  OM_AbortOnError __attribute__((deprecated)) = 4
+};
+
+ +

Attributes on the enum declaration do not apply to +individual enumerators.

+ +

Query for this feature with __has_extension(enumerator_attributes).

+ + +

'User-Specified' System Frameworks

+ + +

Clang provides a mechanism by which frameworks can be built in such a way +that they will always be treated as being 'system frameworks', even if they are +not present in a system framework directory. This can be useful to system +framework developers who want to be able to test building other applications +with development builds of their framework, including the manner in which the +compiler changes warning behavior for system headers.

+ +

Framework developers can opt-in to this mechanism by creating a +'.system_framework' file at the top-level of their framework. That is, the +framework should have contents like:

+ +
+ .../TestFramework.framework
+ .../TestFramework.framework/.system_framework
+ .../TestFramework.framework/Headers
+ .../TestFramework.framework/Headers/TestFramework.h
+ ...
+
+ +

Clang will treat the presence of this file as an indicator that the framework +should be treated as a system framework, regardless of how it was found in the +framework search path. For consistency, we recommend that such files never be +included in installed versions of the framework.

+ + +

Availability attribute

+ +

Clang introduces the availability attribute, which can +be placed on declarations to describe the lifecycle of that +declaration relative to operating system versions. Consider the function declaration for a hypothetical function f:

+ +
+void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
+
+ +

The availability attribute states that f was introduced in Mac OS X 10.4, deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information is used by Clang to determine when it is safe to use f: for example, if Clang is instructed to compile code for Mac OS X 10.5, a call to f() succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call succeeds but Clang emits a warning specifying that the function is deprecated. Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call fails because f() is no longer available.

+ +

The availablility attribute is a comma-separated list starting with the platform name and then including clauses specifying important milestones in the declaration's lifetime (in any order) along with additional information. Those clauses can be:

+ +
+
introduced=version
+
The first version in which this declaration was introduced.
+ +
deprecated=version
+
The first version in which this declaration was deprecated, meaning that users should migrate away from this API.
+ +
obsoleted=version
+
The first version in which this declaration was obsoleted, meaning that it was removed completely and can no longer be used.
+ +
unavailable
+
This declaration is never available on this platform.
+ +
message=string-literal
+
Additional message text that Clang will provide when emitting a warning or error about use of a deprecated or obsoleted declaration. Useful to direct users to replacement APIs.
+
+ +

Multiple availability attributes can be placed on a declaration, which may correspond to different platforms. Only the availability attribute with the platform corresponding to the target platform will be used; any others will be ignored. If no availability attribute specifies availability for the current target platform, the availability attributes are ignored. Supported platforms are:

+ +
+
ios
+
Apple's iOS operating system. The minimum deployment target is specified by the -mios-version-min=version or -miphoneos-version-min=version command-line arguments.
+ +
macosx
+
Apple's Mac OS X operating system. The minimum deployment target is specified by the -mmacosx-version-min=version command-line argument.
+
+ +

A declaration can be used even when deploying back to a platform +version prior to when the declaration was introduced. When this +happens, the declaration is weakly +linked, as if the weak_import attribute were added to the declaration. A weakly-linked declaration may or may not be present a run-time, and a program can determine whether the declaration is present by checking whether the address of that declaration is non-NULL.

+ + +

Checks for Standard Language Features

+ + +

The __has_feature macro can be used to query if certain standard +language features are enabled. The __has_extension macro can be used +to query if language features are available as an extension when compiling for +a standard which does not provide them. The features which can be tested are +listed here.

+ +

C++98

+ +

The features listed below are part of the C++98 standard. These features are +enabled by default when compiling C++ code.

+ +

C++ exceptions

+ +

Use __has_feature(cxx_exceptions) to determine if C++ exceptions have been enabled. For +example, compiling code with -fno-exceptions disables C++ exceptions.

+ +

C++ RTTI

+ +

Use __has_feature(cxx_rtti) to determine if C++ RTTI has been enabled. For example, +compiling code with -fno-rtti disables the use of RTTI.

+ +

C++11

+ +

The features listed below are part of the C++11 standard. As a result, all +these features are enabled with the -std=c++11 or -std=gnu++11 +option when compiling C++ code.

+ +

C++11 SFINAE includes access control

+ +

Use __has_feature(cxx_access_control_sfinae) or __has_extension(cxx_access_control_sfinae) to determine whether access-control errors (e.g., calling a private constructor) are considered to be template argument deduction errors (aka SFINAE errors), per C++ DR1170.

+ +

C++11 alias templates

+ +

Use __has_feature(cxx_alias_templates) or +__has_extension(cxx_alias_templates) to determine if support for +C++11's alias declarations and alias templates is enabled.

+ +

C++11 alignment specifiers

+ +

Use __has_feature(cxx_alignas) or +__has_extension(cxx_alignas) to determine if support for alignment +specifiers using alignas is enabled.

+ +

C++11 attributes

+ +

Use __has_feature(cxx_attributes) or +__has_extension(cxx_attributes) to determine if support for attribute +parsing with C++11's square bracket notation is enabled.

+ +

C++11 generalized constant expressions

+ +

Use __has_feature(cxx_constexpr) to determine if support +for generalized constant expressions (e.g., constexpr) is +enabled.

+ +

C++11 decltype()

+ +

Use __has_feature(cxx_decltype) or +__has_extension(cxx_decltype) to determine if support for the +decltype() specifier is enabled. C++11's decltype +does not require type-completeness of a function call expression. +Use __has_feature(cxx_decltype_incomplete_return_types) +or __has_extension(cxx_decltype_incomplete_return_types) +to determine if support for this feature is enabled.

+ +

C++11 default template arguments in function templates

+ +

Use __has_feature(cxx_default_function_template_args) or +__has_extension(cxx_default_function_template_args) to determine +if support for default template arguments in function templates is enabled.

+ +

C++11 defaulted functions

+ +

Use __has_feature(cxx_defaulted_functions) or +__has_extension(cxx_defaulted_functions) to determine if support for +defaulted function definitions (with = default) is enabled.

+ +

C++11 delegating constructors

+ +

Use __has_feature(cxx_delegating_constructors) to determine if +support for delegating constructors is enabled.

+ +

C++11 deleted functions

+ +

Use __has_feature(cxx_deleted_functions) or +__has_extension(cxx_deleted_functions) to determine if support for +deleted function definitions (with = delete) is enabled.

+ +

C++11 explicit conversion functions

+

Use __has_feature(cxx_explicit_conversions) to determine if support for explicit conversion functions is enabled.

+ +

C++11 generalized initializers

+ +

Use __has_feature(cxx_generalized_initializers) to determine if +support for generalized initializers (using braced lists and +std::initializer_list) is enabled.

+ +

C++11 implicit move constructors/assignment operators

+ +

Use __has_feature(cxx_implicit_moves) to determine if Clang will +implicitly generate move constructors and move assignment operators where needed.

+ +

C++11 inheriting constructors

+ +

Use __has_feature(cxx_inheriting_constructors) to determine if support for inheriting constructors is enabled. Clang does not currently implement this feature.

+ +

C++11 inline namespaces

+ +

Use __has_feature(cxx_inline_namespaces) or +__has_extension(cxx_inline_namespaces) to determine if support for +inline namespaces is enabled.

+ +

C++11 lambdas

+ +

Use __has_feature(cxx_lambdas) or +__has_extension(cxx_lambdas) to determine if support for lambdas +is enabled.

+ +

C++11 local and unnamed types as template arguments

+ +

Use __has_feature(cxx_local_type_template_args) or +__has_extension(cxx_local_type_template_args) to determine if +support for local and unnamed types as template arguments is enabled.

+ +

C++11 noexcept

+ +

Use __has_feature(cxx_noexcept) or +__has_extension(cxx_noexcept) to determine if support for noexcept +exception specifications is enabled.

+ +

C++11 in-class non-static data member initialization

+ +

Use __has_feature(cxx_nonstatic_member_init) to determine whether in-class initialization of non-static data members is enabled.

+ +

C++11 nullptr

+ +

Use __has_feature(cxx_nullptr) or +__has_extension(cxx_nullptr) to determine if support for +nullptr is enabled.

+ +

C++11 override control

+ +

Use __has_feature(cxx_override_control) or +__has_extension(cxx_override_control) to determine if support for +the override control keywords is enabled.

+ +

C++11 reference-qualified functions

+

Use __has_feature(cxx_reference_qualified_functions) or +__has_extension(cxx_reference_qualified_functions) to determine +if support for reference-qualified functions (e.g., member functions with +& or && applied to *this) +is enabled.

+ +

C++11 range-based for loop

+ +

Use __has_feature(cxx_range_for) or +__has_extension(cxx_range_for) to determine if support for the +range-based for loop is enabled.

+ +

C++11 raw string literals

+

Use __has_feature(cxx_raw_string_literals) to determine if support +for raw string literals (e.g., R"x(foo\bar)x") is enabled.

+ +

C++11 rvalue references

+ +

Use __has_feature(cxx_rvalue_references) or +__has_extension(cxx_rvalue_references) to determine if support for +rvalue references is enabled.

+ +

C++11 static_assert()

+ +

Use __has_feature(cxx_static_assert) or +__has_extension(cxx_static_assert) to determine if support for +compile-time assertions using static_assert is enabled.

+ +

C++11 type inference

+ +

Use __has_feature(cxx_auto_type) or +__has_extension(cxx_auto_type) to determine C++11 type inference is +supported using the auto specifier. If this is disabled, auto +will instead be a storage class specifier, as in C or C++98.

+ +

C++11 strongly typed enumerations

+ +

Use __has_feature(cxx_strong_enums) or +__has_extension(cxx_strong_enums) to determine if support for +strongly typed, scoped enumerations is enabled.

+ +

C++11 trailing return type

+ +

Use __has_feature(cxx_trailing_return) or +__has_extension(cxx_trailing_return) to determine if support for the +alternate function declaration syntax with trailing return type is enabled.

+ +

C++11 Unicode string literals

+

Use __has_feature(cxx_unicode_literals) to determine if +support for Unicode string literals is enabled.

+ +

C++11 unrestricted unions

+ +

Use __has_feature(cxx_unrestricted_unions) to determine if support for unrestricted unions is enabled.

+ +

C++11 user-defined literals

+ +

Use __has_feature(cxx_user_literals) to determine if support for user-defined literals is enabled.

+ +

C++11 variadic templates

+ +

Use __has_feature(cxx_variadic_templates) or +__has_extension(cxx_variadic_templates) to determine if support +for variadic templates is enabled.

+ +

C11

+ +

The features listed below are part of the C11 standard. As a result, all +these features are enabled with the -std=c11 or -std=gnu11 +option when compiling C code. Additionally, because these features are all +backward-compatible, they are available as extensions in all language modes.

+ +

C11 alignment specifiers

+ +

Use __has_feature(c_alignas) or __has_extension(c_alignas) +to determine if support for alignment specifiers using _Alignas +is enabled.

+ +

C11 atomic operations

+ +

Use __has_feature(c_atomic) or __has_extension(c_atomic) +to determine if support for atomic types using _Atomic is enabled. +Clang also provides a set of builtins which can be +used to implement the <stdatomic.h> operations on _Atomic +types.

+ +

C11 generic selections

+ +

Use __has_feature(c_generic_selections) or +__has_extension(c_generic_selections) to determine if support for +generic selections is enabled.

+ +

As an extension, the C11 generic selection expression is available in all +languages supported by Clang. The syntax is the same as that given in the +C11 standard.

+ +

In C, type compatibility is decided according to the rules given in the +appropriate standard, but in C++, which lacks the type compatibility rules +used in C, types are considered compatible only if they are equivalent.

+ +

C11 _Static_assert()

+ +

Use __has_feature(c_static_assert) or +__has_extension(c_static_assert) to determine if support for +compile-time assertions using _Static_assert is enabled.

+ + +

Checks for Type Traits

+ + +

Clang supports the GNU C++ type traits and a subset of the Microsoft Visual C++ Type traits. For each supported type trait __X, __has_extension(X) indicates the presence of the type trait. For example: +

+
+#if __has_extension(is_convertible_to)
+template<typename From, typename To>
+struct is_convertible_to {
+  static const bool value = __is_convertible_to(From, To);
+};
+#else
+// Emulate type trait
+#endif
+
+
+ +

The following type traits are supported by Clang:

+
    +
  • __has_nothrow_assign (GNU, Microsoft)
  • +
  • __has_nothrow_copy (GNU, Microsoft)
  • +
  • __has_nothrow_constructor (GNU, Microsoft)
  • +
  • __has_trivial_assign (GNU, Microsoft)
  • +
  • __has_trivial_copy (GNU, Microsoft)
  • +
  • __has_trivial_constructor (GNU, Microsoft)
  • +
  • __has_trivial_destructor (GNU, Microsoft)
  • +
  • __has_virtual_destructor (GNU, Microsoft)
  • +
  • __is_abstract (GNU, Microsoft)
  • +
  • __is_base_of (GNU, Microsoft)
  • +
  • __is_class (GNU, Microsoft)
  • +
  • __is_convertible_to (Microsoft)
  • +
  • __is_empty (GNU, Microsoft)
  • +
  • __is_enum (GNU, Microsoft)
  • +
  • __is_pod (GNU, Microsoft)
  • +
  • __is_polymorphic (GNU, Microsoft)
  • +
  • __is_union (GNU, Microsoft)
  • +
  • __is_literal(type): Determines whether the given type is a literal type
  • +
  • __is_final: Determines whether the given type is declared with a final class-virt-specifier.
  • +
  • __underlying_type(type): Retrieves the underlying type for a given enum type. This trait is required to implement the C++11 standard library.
  • +
  • __is_trivially_assignable(totype, fromtype): Determines whether a value of type totype can be assigned to from a value of type fromtype such that no non-trivial functions are called as part of that assignment. This trait is required to implement the C++11 standard library.
  • +
  • __is_trivially_constructible(type, argtypes...): Determines whether a value of type type can be direct-initialized with arguments of types argtypes... such that no non-trivial functions are called as part of that initialization. This trait is required to implement the C++11 standard library.
  • +
+ + +

Blocks

+ + +

The syntax and high level language feature description is in BlockLanguageSpec.txt. Implementation and ABI +details for the clang implementation are in Block-ABI-Apple.txt.

+ + +

Query for this feature with __has_extension(blocks).

+ + +

Objective-C Features

+ + +

Related result types

+ +

According to Cocoa conventions, Objective-C methods with certain names ("init", "alloc", etc.) always return objects that are an instance of the receiving class's type. Such methods are said to have a "related result type", meaning that a message send to one of these methods will have the same static type as an instance of the receiver class. For example, given the following classes:

+ +
+
+@interface NSObject
++ (id)alloc;
+- (id)init;
+@end
+
+@interface NSArray : NSObject
+@end
+
+
+ +

and this common initialization pattern

+ +
+
+NSArray *array = [[NSArray alloc] init];
+
+
+ +

the type of the expression [NSArray alloc] is +NSArray* because alloc implicitly has a +related result type. Similarly, the type of the expression +[[NSArray alloc] init] is NSArray*, since +init has a related result type and its receiver is known +to have the type NSArray *. If neither alloc nor init had a related result type, the expressions would have had type id, as declared in the method signature.

+ +

A method with a related result type can be declared by using the +type instancetype as its result type. instancetype +is a contextual keyword that is only permitted in the result type of +an Objective-C method, e.g.

+ +
+@interface A
++ (instancetype)constructAnA;
+@end
+
+ +

The related result type can also be inferred for some methods. +To determine whether a method has an inferred related result type, the first +word in the camel-case selector (e.g., "init" in "initWithObjects") is +considered, and the method will have a related result type if its return +type is compatible with the type of its class and if

+ +
    + +
  • the first word is "alloc" or "new", and the method is a class + method, or
  • + +
  • the first word is "autorelease", "init", "retain", or "self", + and the method is an instance method.
  • + +
+ +

If a method with a related result type is overridden by a subclass +method, the subclass method must also return a type that is compatible +with the subclass type. For example:

+ +
+
+@interface NSString : NSObject
+- (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
+@end
+
+
+ +

Related result types only affect the type of a message send or +property access via the given method. In all other respects, a method +with a related result type is treated the same way as method that +returns id.

+ +

Use __has_feature(objc_instancetype) to determine whether +the instancetype contextual keyword is available.

+ + +

Automatic reference counting

+ + +

Clang provides support for automated reference counting in Objective-C, which eliminates the need for manual retain/release/autorelease message sends. There are two feature macros associated with automatic reference counting: __has_feature(objc_arc) indicates the availability of automated reference counting in general, while __has_feature(objc_arc_weak) indicates that automated reference counting also includes support for __weak pointers to Objective-C objects.

+ + +

Enumerations with a fixed underlying type

+ + +

Clang provides support for C++11 enumerations with a fixed +underlying type within Objective-C. For example, one can write an +enumeration type as:

+ +
+typedef enum : unsigned char { Red, Green, Blue } Color;
+
+ +

This specifies that the underlying type, which is used to store the +enumeration value, is unsigned char.

+ +

Use __has_feature(objc_fixed_enum) to determine whether +support for fixed underlying types is available in Objective-C.

+ + +

Interoperability with C++11 lambdas

+ + +

Clang provides interoperability between C++11 lambdas and +blocks-based APIs, by permitting a lambda to be implicitly converted +to a block pointer with the corresponding signature. For example, +consider an API such as NSArray's array-sorting +method:

+ +
 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr; 
+ +

NSComparator is simply a typedef for the block pointer +NSComparisonResult (^)(id, id), and parameters of this +type are generally provided with block literals as arguments. However, +one can also use a C++11 lambda so long as it provides the same +signature (in this case, accepting two parameters of type +id and returning an NSComparisonResult):

+ +
+  NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
+                     @"String 02"];
+  const NSStringCompareOptions comparisonOptions
+    = NSCaseInsensitiveSearch | NSNumericSearch |
+      NSWidthInsensitiveSearch | NSForcedOrderingSearch;
+  NSLocale *currentLocale = [NSLocale currentLocale];
+  NSArray *sorted 
+    = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
+               NSRange string1Range = NSMakeRange(0, [s1 length]);
+               return [s1 compare:s2 options:comparisonOptions 
+                          range:string1Range locale:currentLocale];
+       }];
+  NSLog(@"sorted: %@", sorted);
+
+ +

This code relies on an implicit conversion from the type of the +lambda expression (an unnamed, local class type called the closure +type) to the corresponding block pointer type. The conversion +itself is expressed by a conversion operator in that closure type +that produces a block pointer with the same signature as the lambda +itself, e.g.,

+ +
+  operator NSComparisonResult (^)(id, id)() const;
+
+ +

This conversion function returns a new block that simply forwards +the two parameters to the lambda object (which it captures by copy), +then returns the result. The returned block is first copied (with +Block_copy) and then autoreleased. As an optimization, if a +lambda expression is immediately converted to a block pointer (as in +the first example, above), then the block is not copied and +autoreleased: rather, it is given the same lifetime as a block literal +written at that point in the program, which avoids the overhead of +copying a block to the heap in the common case.

+ +

The conversion from a lambda to a block pointer is only available +in Objective-C++, and not in C++ with blocks, due to its use of +Objective-C memory management (autorelease).

+ + +

Object Literals and Subscripting

+ + +

Clang provides support for Object Literals and Subscripting in Objective-C, which simplifies common Objective-C programming patterns, makes programs more concise, and improves the safety of container creation. There are several feature macros associated with object literals and subscripting: __has_feature(objc_array_literals) tests the availability of array literals; __has_feature(objc_dictionary_literals) tests the availability of dictionary literals; __has_feature(objc_subscripting) tests the availability of object subscripting.

+ + +

Function Overloading in C

+ + +

Clang provides support for C++ function overloading in C. Function +overloading in C is introduced using the overloadable attribute. For +example, one might provide several overloaded versions of a tgsin +function that invokes the appropriate standard function computing the sine of a +value with float, double, or long double +precision:

+ +
+
+#include <math.h>
+float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
+double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
+long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
+
+
+ +

Given these declarations, one can call tgsin with a +float value to receive a float result, with a +double to receive a double result, etc. Function +overloading in C follows the rules of C++ function overloading to pick +the best overload given the call arguments, with a few C-specific +semantics:

+
    +
  • Conversion from float or double to long + double is ranked as a floating-point promotion (per C99) rather + than as a floating-point conversion (as in C++).
  • + +
  • A conversion from a pointer of type T* to a pointer of type + U* is considered a pointer conversion (with conversion + rank) if T and U are compatible types.
  • + +
  • A conversion from type T to a value of type U + is permitted if T and U are compatible types. This + conversion is given "conversion" rank.
  • +
+ +

The declaration of overloadable functions is restricted to +function declarations and definitions. Most importantly, if any +function with a given name is given the overloadable +attribute, then all function declarations and definitions with that +name (and in that scope) must have the overloadable +attribute. This rule even applies to redeclarations of functions whose original +declaration had the overloadable attribute, e.g.,

+ +
+
+int f(int) __attribute__((overloadable));
+float f(float); // error: declaration of "f" must have the "overloadable" attribute
+
+int g(int) __attribute__((overloadable));
+int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
+
+
+ +

Functions marked overloadable must have +prototypes. Therefore, the following code is ill-formed:

+ +
+
+int h() __attribute__((overloadable)); // error: h does not have a prototype
+
+
+ +

However, overloadable functions are allowed to use a +ellipsis even if there are no named parameters (as is permitted in C++). This feature is particularly useful when combined with the unavailable attribute:

+ +
+
+void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
+
+
+ +

Functions declared with the overloadable attribute have +their names mangled according to the same rules as C++ function +names. For example, the three tgsin functions in our +motivating example get the mangled names _Z5tgsinf, +_Z5tgsind, and _Z5tgsine, respectively. There are two +caveats to this use of name mangling:

+ +
    + +
  • Future versions of Clang may change the name mangling of + functions overloaded in C, so you should not depend on an specific + mangling. To be completely safe, we strongly urge the use of + static inline with overloadable functions.
  • + +
  • The overloadable attribute has almost no meaning when + used in C++, because names will already be mangled and functions are + already overloadable. However, when an overloadable + function occurs within an extern "C" linkage specification, + it's name will be mangled in the same way as it would in + C.
  • +
+ +

Query for this feature with __has_extension(attribute_overloadable).

+ + +

Initializer lists for complex numbers in C

+ + +

clang supports an extension which allows the following in C:

+ +
+
+#include <math.h>
+#include <complex.h>
+complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
+
+
+ +

This construct is useful because there is no way to separately +initialize the real and imaginary parts of a complex variable in +standard C, given that clang does not support _Imaginary. +(clang also supports the __real__ and __imag__ +extensions from gcc, which help in some cases, but are not usable in +static initializers.) + +

Note that this extension does not allow eliding the braces; the +meaning of the following two lines is different:

+ +
+
+complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
+complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
+
+
+ +

This extension also works in C++ mode, as far as that goes, but does not + apply to the C++ std::complex. (In C++11, list + initialization allows the same syntax to be used with + std::complex with the same meaning.) + + +

Builtin Functions

+ + +

Clang supports a number of builtin library functions with the same syntax as +GCC, including things like __builtin_nan, +__builtin_constant_p, __builtin_choose_expr, +__builtin_types_compatible_p, __sync_fetch_and_add, etc. In +addition to the GCC builtins, Clang supports a number of builtins that GCC does +not, which are listed here.

+ +

Please note that Clang does not and will not support all of the GCC builtins +for vector operations. Instead of using builtins, you should use the functions +defined in target-specific header files like <xmmintrin.h>, which +define portable wrappers for these. Many of the Clang versions of these +functions are implemented directly in terms of extended +vector support instead of builtins, in order to reduce the number of +builtins that we need to implement.

+ + +

__builtin_shufflevector

+ + +

__builtin_shufflevector is used to express generic vector +permutation/shuffle/swizzle operations. This builtin is also very important for +the implementation of various target-specific header files like +<xmmintrin.h>. +

+ +

Syntax:

+ +
+__builtin_shufflevector(vec1, vec2, index1, index2, ...)
+
+ +

Examples:

+ +
+  // Identity operation - return 4-element vector V1.
+  __builtin_shufflevector(V1, V1, 0, 1, 2, 3)
+
+  // "Splat" element 0 of V1 into a 4-element result.
+  __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
+
+  // Reverse 4-element vector V1.
+  __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
+
+  // Concatenate every other element of 4-element vectors V1 and V2.
+  __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
+
+  // Concatenate every other element of 8-element vectors V1 and V2.
+  __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
+
+ +

Description:

+ +

The first two arguments to __builtin_shufflevector are vectors that have the +same element type. The remaining arguments are a list of integers that specify +the elements indices of the first two vectors that should be extracted and +returned in a new vector. These element indices are numbered sequentially +starting with the first vector, continuing into the second vector. Thus, if +vec1 is a 4-element vector, index 5 would refer to the second element of vec2. +

+ +

The result of __builtin_shufflevector is a vector +with the same element type as vec1/vec2 but that has an element count equal to +the number of indices specified. +

+ +

Query for this feature with __has_builtin(__builtin_shufflevector).

+ + +

__builtin_unreachable

+ + +

__builtin_unreachable is used to indicate that a specific point in +the program cannot be reached, even if the compiler might otherwise think it +can. This is useful to improve optimization and eliminates certain warnings. +For example, without the __builtin_unreachable in the example below, +the compiler assumes that the inline asm can fall through and prints a "function +declared 'noreturn' should not return" warning. +

+ +

Syntax:

+ +
+__builtin_unreachable()
+
+ +

Example of Use:

+ +
+void myabort(void) __attribute__((noreturn));
+void myabort(void) {
+    asm("int3");
+    __builtin_unreachable();
+}
+
+ +

Description:

+ +

The __builtin_unreachable() builtin has completely undefined behavior. Since +it has undefined behavior, it is a statement that it is never reached and the +optimizer can take advantage of this to produce better code. This builtin takes +no arguments and produces a void result. +

+ +

Query for this feature with __has_builtin(__builtin_unreachable).

+ + +

__sync_swap

+ + +

__sync_swap is used to atomically swap integers or pointers in +memory. +

+ +

Syntax:

+ +
+type __sync_swap(type *ptr, type value, ...)
+
+ +

Example of Use:

+ +
+int old_value = __sync_swap(&value, new_value);
+
+ +

Description:

+ +

The __sync_swap() builtin extends the existing __sync_*() family of atomic +intrinsics to allow code to atomically swap the current value with the new +value. More importantly, it helps developers write more efficient and correct +code by avoiding expensive loops around __sync_bool_compare_and_swap() or +relying on the platform specific implementation details of +__sync_lock_test_and_set(). The __sync_swap() builtin is a full barrier. +

+ + +

__c11_atomic builtins

+ + +

Clang provides a set of builtins which are intended to be used to implement +C11's <stdatomic.h> header. These builtins provide the semantics +of the _explicit form of the corresponding C11 operation, and are named +with a __c11_ prefix. The supported operations are:

+ +
    +
  • __c11_atomic_init
  • +
  • __c11_atomic_thread_fence
  • +
  • __c11_atomic_signal_fence
  • +
  • __c11_atomic_is_lock_free
  • +
  • __c11_atomic_store
  • +
  • __c11_atomic_load
  • +
  • __c11_atomic_exchange
  • +
  • __c11_atomic_compare_exchange_strong
  • +
  • __c11_atomic_compare_exchange_weak
  • +
  • __c11_atomic_fetch_add
  • +
  • __c11_atomic_fetch_sub
  • +
  • __c11_atomic_fetch_and
  • +
  • __c11_atomic_fetch_or
  • +
  • __c11_atomic_fetch_xor
  • +
+ + + +

Target-Specific Extensions

+ + +

Clang supports some language features conditionally on some targets.

+ + +

X86/X86-64 Language Extensions

+ + +

The X86 backend has these language extensions:

+ + +

Memory references off the GS segment

+ + +

Annotating a pointer with address space #256 causes it to be code generated +relative to the X86 GS segment register, and address space #257 causes it to be +relative to the X86 FS segment. Note that this is a very very low-level +feature that should only be used if you know what you're doing (for example in +an OS kernel).

+ +

Here is an example:

+ +
+#define GS_RELATIVE __attribute__((address_space(256)))
+int foo(int GS_RELATIVE *P) {
+  return *P;
+}
+
+ +

Which compiles to (on X86-32):

+ +
+_foo:
+	movl	4(%esp), %eax
+	movl	%gs:(%eax), %eax
+	ret
+
+ + +

Static Analysis-Specific Extensions

+ + +

Clang supports additional attributes that are useful for documenting program +invariants and rules for static analysis tools. The extensions documented here +are used by the path-sensitive static analyzer +engine that is part of Clang's Analysis library.

+ +

The analyzer_noreturn attribute

+ +

Clang's static analysis engine understands the standard noreturn +attribute. This attribute, which is typically affixed to a function prototype, +indicates that a call to a given function never returns. Function prototypes for +common functions like exit are typically annotated with this attribute, +as well as a variety of common assertion handlers. Users can educate the static +analyzer about their own custom assertion handles (thus cutting down on false +positives due to false paths) by marking their own "panic" functions +with this attribute.

+ +

While useful, noreturn is not applicable in all cases. Sometimes +there are special functions that for all intents and purposes should be +considered panic functions (i.e., they are only called when an internal program +error occurs) but may actually return so that the program can fail gracefully. +The analyzer_noreturn attribute allows one to annotate such functions +as being interpreted as "no return" functions by the analyzer (thus +pruning bogus paths) but will not affect compilation (as in the case of +noreturn).

+ +

Usage: The analyzer_noreturn attribute can be placed in the +same places where the noreturn attribute can be placed. It is commonly +placed at the end of function prototypes:

+ +
+  void foo() __attribute__((analyzer_noreturn));
+
+ +

Query for this feature with +__has_attribute(analyzer_noreturn).

+ +

The objc_method_family attribute

+ +

Many methods in Objective-C have conventional meanings determined +by their selectors. For the purposes of static analysis, it is +sometimes useful to be able to mark a method as having a particular +conventional meaning despite not having the right selector, or as not +having the conventional meaning that its selector would suggest. +For these use cases, we provide an attribute to specifically describe +the method family that a method belongs to.

+ +

Usage: __attribute__((objc_method_family(X))), +where X is one of none, alloc, copy, +init, mutableCopy, or new. This attribute +can only be placed at the end of a method declaration:

+ +
+  - (NSString*) initMyStringValue __attribute__((objc_method_family(none)));
+
+ +

Users who do not wish to change the conventional meaning of a +method, and who merely want to document its non-standard retain and +release semantics, should use the +retaining behavior attributes +described below.

+ +

Query for this feature with +__has_attribute(objc_method_family).

+ +

Objective-C retaining behavior attributes

+ +

In Objective-C, functions and methods are generally assumed to take +and return objects with +0 retain counts, with some exceptions for +special methods like +alloc and init. However, +there are exceptions, and so Clang provides attributes to allow these +exceptions to be documented, which helps the analyzer find leaks (and +ignore non-leaks). Some exceptions may be better described using +the objc_method_family +attribute instead.

+ +

Usage: The ns_returns_retained, ns_returns_not_retained, +ns_returns_autoreleased, cf_returns_retained, +and cf_returns_not_retained attributes can be placed on +methods and functions that return Objective-C or CoreFoundation +objects. They are commonly placed at the end of a function prototype +or method declaration:

+ +
+  id foo() __attribute__((ns_returns_retained));
+
+  - (NSString*) bar: (int) x __attribute__((ns_returns_retained));
+
+ +

The *_returns_retained attributes specify that the +returned object has a +1 retain count. +The *_returns_not_retained attributes specify that the return +object has a +0 retain count, even if the normal convention for its +selector would be +1. ns_returns_autoreleased specifies that the +returned object is +0, but is guaranteed to live at least as long as the +next flush of an autorelease pool.

+ +

Usage: The ns_consumed and cf_consumed +attributes can be placed on an parameter declaration; they specify +that the argument is expected to have a +1 retain count, which will be +balanced in some way by the function or method. +The ns_consumes_self attribute can only be placed on an +Objective-C method; it specifies that the method expects +its self parameter to have a +1 retain count, which it will +balance in some way.

+ +
+  void foo(__attribute__((ns_consumed)) NSString *string);
+
+  - (void) bar __attribute__((ns_consumes_self));
+  - (void) baz: (id) __attribute__((ns_consumed)) x;
+
+ +

Query for these features with __has_attribute(ns_consumed), +__has_attribute(ns_returns_retained), etc.

+ + +

Dynamic Analysis-Specific Extensions

+ +

AddressSanitizer

+

Use __has_feature(address_sanitizer) +to check if the code is being built with AddressSanitizer. +

+

Use __attribute__((no_address_safety_analysis)) on a function +declaration to specify that address safety instrumentation (e.g. +AddressSanitizer) should not be applied to that function. +

+ + +

Thread-Safety Annotation Checking

+ + +

Clang supports additional attributes for checking basic locking policies in +multithreaded programs. +Clang currently parses the following list of attributes, although +the implementation for these annotations is currently in development. +For more details, see the +GCC implementation. +

+ +

no_thread_safety_analysis

+ +

Use __attribute__((no_thread_safety_analysis)) on a function +declaration to specify that the thread safety analysis should not be run on that +function. This attribute provides an escape hatch (e.g. for situations when it +is difficult to annotate the locking policy).

+ +

lockable

+ +

Use __attribute__((lockable)) on a class definition to specify +that it has a lockable type (e.g. a Mutex class). This annotation is primarily +used to check consistency.

+ +

scoped_lockable

+ +

Use __attribute__((scoped_lockable)) on a class definition to +specify that it has a "scoped" lockable type. Objects of this type will acquire +the lock upon construction and release it upon going out of scope. + This annotation is primarily used to check +consistency.

+ +

guarded_var

+ +

Use __attribute__((guarded_var)) on a variable declaration to +specify that the variable must be accessed while holding some lock.

+ +

pt_guarded_var

+ +

Use __attribute__((pt_guarded_var)) on a pointer declaration to +specify that the pointer must be dereferenced while holding some lock.

+ +

guarded_by(l)

+ +

Use __attribute__((guarded_by(l))) on a variable declaration to +specify that the variable must be accessed while holding lock l.

+ +

pt_guarded_by(l)

+ +

Use __attribute__((pt_guarded_by(l))) on a pointer declaration to +specify that the pointer must be dereferenced while holding lock l.

+ +

acquired_before(...)

+ +

Use __attribute__((acquired_before(...))) on a declaration +of a lockable variable to specify that the lock must be acquired before all +attribute arguments. Arguments must be lockable type, and there must be at +least one argument.

+ +

acquired_after(...)

+ +

Use __attribute__((acquired_after(...))) on a declaration +of a lockable variable to specify that the lock must be acquired after all +attribute arguments. Arguments must be lockable type, and there must be at +least one argument.

+ +

exclusive_lock_function(...)

+ +

Use __attribute__((exclusive_lock_function(...))) on a function +declaration to specify that the function acquires all listed locks +exclusively. This attribute takes zero or more arguments: either of lockable +type or integers indexing into function parameters of lockable type. If no +arguments are given, the acquired lock is implicitly this of the +enclosing object.

+ +

shared_lock_function(...)

+ +

Use __attribute__((shared_lock_function(...))) on a function +declaration to specify that the function acquires all listed locks, although + the locks may be shared (e.g. read locks). This attribute takes zero or more +arguments: either of lockable type or integers indexing into function +parameters of lockable type. If no arguments are given, the acquired lock is +implicitly this of the enclosing object.

+ +

exclusive_trylock_function(...)

+ +

Use __attribute__((exclusive_lock_function(...))) on a function +declaration to specify that the function will try (without blocking) to acquire +all listed locks exclusively. This attribute takes one or more arguments. The +first argument is an integer or boolean value specifying the return value of a +successful lock acquisition. The remaining arugments are either of lockable type +or integers indexing into function parameters of lockable type. If only one +argument is given, the acquired lock is implicitly this of the +enclosing object.

+ +

shared_trylock_function(...)

+ +

Use __attribute__((shared_lock_function(...))) on a function +declaration to specify that the function will try (without blocking) to acquire +all listed locks, although the locks may be shared (e.g. read locks). This +attribute takes one or more arguments. The first argument is an integer or +boolean value specifying the return value of a successful lock acquisition. The +remaining arugments are either of lockable type or integers indexing into +function parameters of lockable type. If only one argument is given, the +acquired lock is implicitly this of the enclosing object.

+ +

unlock_function(...)

+ +

Use __attribute__((unlock_function(...))) on a function +declaration to specify that the function release all listed locks. This +attribute takes zero or more arguments: either of lockable type or integers +indexing into function parameters of lockable type. If no arguments are given, +the acquired lock is implicitly this of the enclosing object.

+ +

lock_returned(l)

+ +

Use __attribute__((lock_returned(l))) on a function +declaration to specify that the function returns lock l (l +must be of lockable type). This annotation is used to aid in resolving lock +expressions.

+ +

locks_excluded(...)

+ +

Use __attribute__((locks_excluded(...))) on a function declaration +to specify that the function must not be called with the listed locks. Arguments +must be lockable type, and there must be at least one argument.

+ +

exclusive_locks_required(...)

+ +

Use __attribute__((exclusive_locks_required(...))) on a function +declaration to specify that the function must be called while holding the listed +exclusive locks. Arguments must be lockable type, and there must be at +least one argument.

+ +

shared_locks_required(...)

+ +

Use __attribute__((shared_locks_required(...))) on a function +declaration to specify that the function must be called while holding the listed +shared locks. Arguments must be lockable type, and there must be at +least one argument.

+ +
+ + diff --git a/cpp/llvm/tools/clang/docs/Makefile b/cpp/llvm/tools/clang/docs/Makefile new file mode 100644 index 00000000..2608046f --- /dev/null +++ b/cpp/llvm/tools/clang/docs/Makefile @@ -0,0 +1,97 @@ +##===- docs/Makefile ---------------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +CLANG_LEVEL := .. +DIRS := tools + +ifdef BUILD_FOR_WEBSITE +PROJ_OBJ_DIR = . +DOXYGEN = doxygen + +$(PROJ_OBJ_DIR)/doxygen.cfg: doxygen.cfg.in + cat $< | sed \ + -e 's/@abs_srcdir@/./g' \ + -e 's/@DOT@/dot/g' \ + -e 's/@PACKAGE_VERSION@/mainline/' \ + -e 's/@abs_builddir@/./g' > $@ +endif + +include $(CLANG_LEVEL)/Makefile + +HTML := $(wildcard $(PROJ_SRC_DIR)/*.html) \ + $(wildcard $(PROJ_SRC_DIR)/*.css) +#IMAGES := $(wildcard $(PROJ_SRC_DIR)/img/*.*) +DOXYFILES := doxygen.cfg.in doxygen.css doxygen.footer doxygen.header \ + doxygen.intro +EXTRA_DIST := $(HTML) $(DOXYFILES) llvm.css CommandGuide img + +.PHONY: install-html install-doxygen doxygen generated + +install_targets := +ifndef ONLY_MAN_DOCS +install_targets += install-html +endif +ifeq ($(ENABLE_DOXYGEN),1) +install_targets += install-doxygen +endif +install-local:: $(install_targets) + +# Live documentation is generated for the web site using this target: +# 'make generated BUILD_FOR_WEBSITE=1' +generated:: doxygen + +install-html: $(PROJ_OBJ_DIR)/html.tar.gz + $(Echo) Installing HTML documentation + $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/html + $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/html/img + $(Verb) $(DataInstall) $(HTML) $(DESTDIR)$(PROJ_docsdir)/html +# $(Verb) $(DataInstall) $(IMAGES) $(DESTDIR)$(PROJ_docsdir)/html/img + $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/html.tar.gz $(DESTDIR)$(PROJ_docsdir) + +$(PROJ_OBJ_DIR)/html.tar.gz: $(HTML) + $(Echo) Packaging HTML documentation + $(Verb) $(RM) -rf $@ $(PROJ_OBJ_DIR)/html.tar + $(Verb) cd $(PROJ_SRC_DIR) && \ + $(TAR) cf $(PROJ_OBJ_DIR)/html.tar *.html + $(Verb) $(GZIPBIN) $(PROJ_OBJ_DIR)/html.tar + +install-doxygen: doxygen + $(Echo) Installing doxygen documentation + $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/html/doxygen + $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/doxygen.tar.gz $(DESTDIR)$(PROJ_docsdir) + $(Verb) cd $(PROJ_OBJ_DIR)/doxygen && \ + $(FIND) . -type f -exec \ + $(DataInstall) {} $(DESTDIR)$(PROJ_docsdir)/html/doxygen \; + +doxygen: regendoc $(PROJ_OBJ_DIR)/doxygen.tar.gz + +regendoc: + $(Echo) Building doxygen documentation + $(Verb) if test -e $(PROJ_OBJ_DIR)/doxygen ; then \ + $(RM) -rf $(PROJ_OBJ_DIR)/doxygen ; \ + fi + $(Verb) $(DOXYGEN) $(PROJ_OBJ_DIR)/doxygen.cfg + +$(PROJ_OBJ_DIR)/doxygen.tar.gz: $(DOXYFILES) $(PROJ_OBJ_DIR)/doxygen.cfg + $(Echo) Packaging doxygen documentation + $(Verb) $(RM) -rf $@ $(PROJ_OBJ_DIR)/doxygen.tar + $(Verb) $(TAR) cf $(PROJ_OBJ_DIR)/doxygen.tar doxygen + $(Verb) $(GZIPBIN) $(PROJ_OBJ_DIR)/doxygen.tar + $(Verb) $(CP) $(PROJ_OBJ_DIR)/doxygen.tar.gz $(PROJ_OBJ_DIR)/doxygen/html/ + +userloc: $(LLVM_SRC_ROOT)/docs/userloc.html + +$(LLVM_SRC_ROOT)/docs/userloc.html: + $(Echo) Making User LOC Table + $(Verb) cd $(LLVM_SRC_ROOT) ; ./utils/userloc.pl -details -recurse \ + -html lib include tools runtime utils examples autoconf test > docs/userloc.html + +uninstall-local:: + $(Echo) Uninstalling Documentation + $(Verb) $(RM) -rf $(DESTDIR)$(PROJ_docsdir) diff --git a/cpp/llvm/tools/clang/docs/ObjectiveCLiterals.html b/cpp/llvm/tools/clang/docs/ObjectiveCLiterals.html new file mode 100644 index 00000000..63b523c6 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/ObjectiveCLiterals.html @@ -0,0 +1,314 @@ + + + + + + Clang Language Extensions + + + + + + + + +
+ +

Objective-C Literals

+ +

Introduction

+ +Three new features were introduced into clang at the same time: NSNumber Literals provide a syntax for creating NSNumber from scalar literal expressions; Collection Literals provide a short-hand for creating arrays and dictionaries; Object Subscripting provides a way to use subscripting with Objective-C objects. Users of Apple compiler releases can use these features starting with the Apple LLVM Compiler 4.0. Users of open-source LLVM.org compiler releases can use these features starting with clang v3.1.

+ +These language additions simplify common Objective-C programming patterns, make programs more concise, and improve the safety of container creation.

+ +This document describes how the features are implemented in clang, and how to use them in your own programs.

+ +

NSNumber Literals

+ +The framework class NSNumber is used to wrap scalar values inside objects: signed and unsigned integers (char, short, int, long, long long), floating point numbers (float, double), and boolean values (BOOL, C++ bool). Scalar values wrapped in objects are also known as boxed values.

+ +In Objective-C, any character, numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object initialized with that value. C's type suffixes may be used to control the size of numeric literals. + +

Examples

+ +The following program illustrates the rules for NSNumber literals:

+ +

+void main(int argc, const char *argv[]) {
+  // character literals.
+  NSNumber *theLetterZ = @'Z';          // equivalent to [NSNumber numberWithChar:'Z']
+
+  // integral literals.
+  NSNumber *fortyTwo = @42;             // equivalent to [NSNumber numberWithInt:42]
+  NSNumber *fortyTwoUnsigned = @42U;    // equivalent to [NSNumber numberWithUnsignedInt:42U]
+  NSNumber *fortyTwoLong = @42L;        // equivalent to [NSNumber numberWithLong:42L]
+  NSNumber *fortyTwoLongLong = @42LL;   // equivalent to [NSNumber numberWithLongLong:42LL]
+
+  // floating point literals.
+  NSNumber *piFloat = @3.141592654F;    // equivalent to [NSNumber numberWithFloat:3.141592654F]
+  NSNumber *piDouble = @3.1415926535;   // equivalent to [NSNumber numberWithDouble:3.1415926535]
+
+  // BOOL literals.
+  NSNumber *yesNumber = @YES;           // equivalent to [NSNumber numberWithBool:YES]
+  NSNumber *noNumber = @NO;             // equivalent to [NSNumber numberWithBool:NO]
+
+#ifdef __cplusplus
+  NSNumber *trueNumber = @true;         // equivalent to [NSNumber numberWithBool:(BOOL)true]
+  NSNumber *falseNumber = @false;       // equivalent to [NSNumber numberWithBool:(BOOL)false]
+#endif
+}
+
+ +

Discussion

+ +NSNumber literals only support literal scalar values after the '@'. Consequently, @INT_MAX works, but @INT_MIN does not, because they are defined like this:

+ +

+#define INT_MAX   2147483647  /* max value for an int */
+#define INT_MIN   (-2147483647-1) /* min value for an int */
+
+ +The definition of INT_MIN is not a simple literal, but a parenthesized expression. This is by design, but may be improved in subsequent compiler releases.

+ +Because NSNumber does not currently support wrapping long double values, the use of a long double NSNumber literal (e.g. @123.23L) will be rejected by the compiler.

+ +Previously, the BOOL type was simply a typedef for signed char, and YES and NO were macros that expand to (BOOL)1 and (BOOL)0 respectively. To support @YES and @NO expressions, these macros are now defined using new language keywords in <objc/objc.h>:

+ +

+#if __has_feature(objc_bool)
+#define YES             __objc_yes
+#define NO              __objc_no
+#else
+#define YES             ((BOOL)1)
+#define NO              ((BOOL)0)
+#endif
+
+ +The compiler implicitly converts __objc_yes and __objc_no to (BOOL)1 and (BOOL)0. The keywords are used to disambiguate BOOL and integer literals.

+ +Objective-C++ also supports @true and @false expressions, which are equivalent to @YES and @NO. + + +

Container Literals

+ +Objective-C now supports a new expression syntax for creating immutable array and dictionary container objects. + +

Examples

+ +Immutable array expression:

+ +

+NSArray *array = @[ @"Hello", NSApp, [NSNumber numberWithInt:42] ];
+
+ +This creates an NSArray with 3 elements. The comma-separated sub-expressions of an array literal can be any Objective-C object pointer typed expression.

+ +Immutable dictionary expression:

+ +

+NSDictionary *dictionary = @{
+    @"name" : NSUserName(),
+    @"date" : [NSDate date],
+    @"processInfo" : [NSProcessInfo processInfo]
+};
+
+ +This creates an NSDictionary with 3 key/value pairs. Value sub-expressions of a dictionary literal must be Objective-C object pointer typed, as in array literals. Key sub-expressions must be of an Objective-C object pointer type that implements the <NSCopying> protocol.

+ +

Discussion

+ +Neither keys nor values can have the value nil in containers. If the compiler can prove that a key or value is nil at compile time, then a warning will be emitted. Otherwise, a runtime error will occur.

+ +Using array and dictionary literals is safer than the variadic creation forms commonly in use today. Array literal expressions expand to calls to +[NSArray arrayWithObjects:count:], which validates that all objects are non-nil. The variadic form, +[NSArray arrayWithObjects:] uses nil as an argument list terminator, which can lead to malformed array objects. Dictionary literals are similarly created with +[NSDictionary dictionaryWithObjects:forKeys:count:] which validates all objects and keys, unlike +[NSDictionary dictionaryWithObjectsAndKeys:] which also uses a nil parameter as an argument list terminator.

+ +

Object Subscripting

+ +Objective-C object pointer values can now be used with C's subscripting operator.

+ +

Examples

+ +The following code demonstrates the use of object subscripting syntax with NSMutableArray and NSMutableDictionary objects:

+ +

+NSMutableArray *array = ...;
+NSUInteger idx = ...;
+id newObject = ...;
+id oldObject = array[idx];
+array[idx] = newObject;		    // replace oldObject with newObject
+
+NSMutableDictionary *dictionary = ...;
+NSString *key = ...;
+oldObject = dictionary[key];
+dictionary[key] = newObject;	// replace oldObject with newObject
+
+ +The next section explains how subscripting expressions map to accessor methods.

+ +

Subscripting Methods

+ +Objective-C supports two kinds of subscript expressions: array-style subscript expressions use integer typed subscripts; dictionary-style subscript expressions use Objective-C object pointer typed subscripts. Each type of subscript expression is mapped to a message send using a predefined selector. The advantage of this design is flexibility: class designers are free to introduce subscripting by declaring methods or by adopting protocols. Moreover, because the method names are selected by the type of the subscript, an object can be subscripted using both array and dictionary styles. + +

Array-Style Subscripting

+ +When the subscript operand has an integral type, the expression is rewritten to use one of two different selectors, depending on whether the element is being read or written. When an expression reads an element using an integral index, as in the following example:

+ +

+NSUInteger idx = ...;
+id value = object[idx];
+
+ +it is translated into a call to objectAtIndexedSubscript:

+ +

+id value = [object objectAtIndexedSubscript:idx];
+
+ +When an expression writes an element using an integral index:

+ +

+object[idx] = newValue;
+
+ +it is translated to a call to setObject:atIndexedSubscript:

+ +

+[object setObject:newValue atIndexedSubscript:idx];
+
+ +These message sends are then type-checked and performed just like explicit message sends. The method used for objectAtIndexedSubscript: must be declared with an argument of integral type and a return value of some Objective-C object pointer type. The method used for setObject:atIndexedSubscript: must be declared with its first argument having some Objective-C pointer type and its second argument having integral type.

+ +The meaning of indexes is left up to the declaring class. The compiler will coerce the index to the appropriate argument type of the method it uses for type-checking. For an instance of NSArray, reading an element using an index outside the range [0, array.count) will raise an exception. For an instance of NSMutableArray, assigning to an element using an index within this range will replace that element, but assigning to an element using an index outside this range will raise an exception; no syntax is provided for inserting, appending, or removing elements for mutable arrays.

+ +A class need not declare both methods in order to take advantage of this language feature. For example, the class NSArray declares only objectAtIndexedSubscript:, so that assignments to elements will fail to type-check; moreover, its subclass NSMutableArray declares setObject:atIndexedSubscript:. + +

Dictionary-Style Subscripting

+ +When the subscript operand has an Objective-C object pointer type, the expression is rewritten to use one of two different selectors, depending on whether the element is being read from or written to. When an expression reads an element using an Objective-C object pointer subscript operand, as in the following example:

+ +

+id key = ...;
+id value = object[key];
+
+ +it is translated into a call to the objectForKeyedSubscript: method:

+ +

+id value = [object objectForKeyedSubscript:key];
+
+ +When an expression writes an element using an Objective-C object pointer subscript:

+ +

+object[key] = newValue;
+
+ +it is translated to a call to setObject:forKeyedSubscript: + +
+[object setObject:newValue forKeyedSubscript:key];
+
+ +The behavior of setObject:forKeyedSubscript: is class-specific; but in general it should replace an existing value if one is already associated with a key, otherwise it should add a new value for the key. No syntax is provided for removing elements from mutable dictionaries.

+ +

Discussion

+ +An Objective-C subscript expression occurs when the base operand of the C subscript operator has an Objective-C object pointer type. Since this potentially collides with pointer arithmetic on the value, these expressions are only supported under the modern Objective-C runtime, which categorically forbids such arithmetic.

+ +Currently, only subscripts of integral or Objective-C object pointer type are supported. In C++, a class type can be used if it has a single conversion function to an integral or Objective-C pointer type, in which case that conversion is applied and analysis continues as appropriate. Otherwise, the expression is ill-formed.

+ +An Objective-C object subscript expression is always an l-value. If the expression appears on the left-hand side of a simple assignment operator (=), the element is written as described below. If the expression appears on the left-hand side of a compound assignment operator (e.g. +=), the program is ill-formed, because the result of reading an element is always an Objective-C object pointer and no binary operators are legal on such pointers. If the expression appears in any other position, the element is read as described below. It is an error to take the address of a subscript expression, or (in C++) to bind a reference to it.

+ +Programs can use object subscripting with Objective-C object pointers of type id. Normal dynamic message send rules apply; the compiler must see some declaration of the subscripting methods, and will pick the declaration seen first.

+ +

Grammar Additions

+ +To support the new syntax described above, the Objective-C @-expression grammar has the following new productions:

+ +

+objc-at-expression : '@' (string-literal | encode-literal | selector-literal | protocol-literal | object-literal)
+                   ;
+
+object-literal : ('+' | '-')? numeric-constant
+               | character-constant
+               | boolean-constant
+               | array-literal
+               | dictionary-literal
+               ;
+
+boolean-constant : '__objc_yes' | '__objc_no' | 'true' | 'false'  /* boolean keywords. */
+                 ;
+
+array-literal : '[' assignment-expression-list ']'
+              ;
+
+assignment-expression-list : assignment-expression (',' assignment-expression-list)?
+                           | /* empty */
+                           ;
+
+dictionary-literal : '{' key-value-list '}'
+                   ;
+
+key-value-list : key-value-pair (',' key-value-list)?
+               | /* empty */
+               ;
+
+key-value-pair : assignment-expression ':' assignment-expression
+               ;
+
+ +Note: @true and @false are only supported in Objective-C++.

+ +

Availability Checks

+ +Programs test for the new features by using clang's __has_feature checks. Here are examples of their use:

+ +

+#if __has_feature(objc_array_literals)
+    // new way.
+    NSArray *elements = @[ @"H", @"He", @"O", @"C" ];
+#else
+    // old way (equivalent).
+    id objects[] = { @"H", @"He", @"O", @"C" };
+    NSArray *elements = [NSArray arrayWithObjects:objects count:4];
+#endif
+
+#if __has_feature(objc_dictionary_literals)
+    // new way.
+    NSDictionary *masses = @{ @"H" : @1.0078,  @"He" : @4.0026, @"O" : @15.9990, @"C" : @12.0096 };
+#else
+    // old way (equivalent).
+    id keys[] = { @"H", @"He", @"O", @"C" };
+    id values[] = { [NSNumber numberWithDouble:1.0078], [NSNumber numberWithDouble:4.0026],
+                    [NSNumber numberWithDouble:15.9990], [NSNumber numberWithDouble:12.0096] };
+    NSDictionary *masses = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:4];
+#endif
+
+#if __has_feature(objc_subscripting)
+    NSUInteger i, count = elements.count;
+    for (i = 0; i < count; ++i) {
+        NSString *element = elements[i];
+        NSNumber *mass = masses[element];
+        NSLog(@"the mass of %@ is %@", element, mass);
+    }
+#else
+    NSUInteger i, count = [elements count];
+    for (i = 0; i < count; ++i) {
+        NSString *element = [elements objectAtIndex:i];
+        NSNumber *mass = [masses objectForKey:element];
+        NSLog(@"the mass of %@ is %@", element, mass);
+    }
+#endif
+
+ +Code can use also __has_feature(objc_bool) to check for the availability of numeric literals support. This checks for the new __objc_yes / __objc_no keywords, which enable the use of @YES / @NO literals.

+ +

+ + diff --git a/cpp/llvm/tools/clang/docs/PCHInternals.html b/cpp/llvm/tools/clang/docs/PCHInternals.html new file mode 100644 index 00000000..28ce1ce5 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/PCHInternals.html @@ -0,0 +1,532 @@ + + + + Precompiled Headers (PCH) + + + + + + + + + +
+ +

Precompiled Headers

+ +

This document describes the design and implementation of Clang's + precompiled headers (PCH). If you are interested in the end-user + view, please see the User's Manual.

+ +

Table of Contents

+ + +

Using Precompiled Headers with clang

+ +

The Clang compiler frontend, clang -cc1, supports two command line +options for generating and using PCH files.

+ +

To generate PCH files using clang -cc1, use the option +-emit-pch: + +

 $ clang -cc1 test.h -emit-pch -o test.h.pch 
+ +

This option is transparently used by clang when generating +PCH files. The resulting PCH file contains the serialized form of the +compiler's internal representation after it has completed parsing and +semantic analysis. The PCH file can then be used as a prefix header +with the -include-pch option:

+ +
+  $ clang -cc1 -include-pch test.h.pch test.c -o test.s
+
+ +

Design Philosophy

+ +

Precompiled headers are meant to improve overall compile times for + projects, so the design of precompiled headers is entirely driven by + performance concerns. The use case for precompiled headers is + relatively simple: when there is a common set of headers that is + included in nearly every source file in the project, we + precompile that bundle of headers into a single precompiled + header (PCH file). Then, when compiling the source files in the + project, we load the PCH file first (as a prefix header), which acts + as a stand-in for that bundle of headers.

+ +

A precompiled header implementation improves performance when:

+
    +
  • Loading the PCH file is significantly faster than re-parsing the + bundle of headers stored within the PCH file. Thus, a precompiled + header design attempts to minimize the cost of reading the PCH + file. Ideally, this cost should not vary with the size of the + precompiled header file.
  • + +
  • The cost of generating the PCH file initially is not so large + that it counters the per-source-file performance improvement due to + eliminating the need to parse the bundled headers in the first + place. This is particularly important on multi-core systems, because + PCH file generation serializes the build when all compilations + require the PCH file to be up-to-date.
  • +
+ +

Clang's precompiled headers are designed with a compact on-disk +representation, which minimizes both PCH creation time and the time +required to initially load the PCH file. The PCH file itself contains +a serialized representation of Clang's abstract syntax trees and +supporting data structures, stored using the same compressed bitstream +as LLVM's bitcode +file format.

+ +

Clang's precompiled headers are loaded "lazily" from disk. When a +PCH file is initially loaded, Clang reads only a small amount of data +from the PCH file to establish where certain important data structures +are stored. The amount of data read in this initial load is +independent of the size of the PCH file, such that a larger PCH file +does not lead to longer PCH load times. The actual header data in the +PCH file--macros, functions, variables, types, etc.--is loaded only +when it is referenced from the user's code, at which point only that +entity (and those entities it depends on) are deserialized from the +PCH file. With this approach, the cost of using a precompiled header +for a translation unit is proportional to the amount of code actually +used from the header, rather than being proportional to the size of +the header itself.

+ +

When given the -print-stats option, Clang produces +statistics describing how much of the precompiled header was actually +loaded from disk. For a simple "Hello, World!" program that includes +the Apple Cocoa.h header (which is built as a precompiled +header), this option illustrates how little of the actual precompiled +header is required:

+ +
+*** PCH Statistics:
+  933 stat cache hits
+  4 stat cache misses
+  895/39981 source location entries read (2.238563%)
+  19/15315 types read (0.124061%)
+  20/82685 declarations read (0.024188%)
+  154/58070 identifiers read (0.265197%)
+  0/7260 selectors read (0.000000%)
+  0/30842 statements read (0.000000%)
+  4/8400 macros read (0.047619%)
+  1/4995 lexical declcontexts read (0.020020%)
+  0/4413 visible declcontexts read (0.000000%)
+  0/7230 method pool entries read (0.000000%)
+  0 method pool misses
+
+ +

For this small program, only a tiny fraction of the source +locations, types, declarations, identifiers, and macros were actually +deserialized from the precompiled header. These statistics can be +useful to determine whether the precompiled header implementation can +be improved by making more of the implementation lazy.

+ +

Precompiled headers can be chained. When you create a PCH while +including an existing PCH, Clang can create the new PCH by referencing +the original file and only writing the new data to the new file. For +example, you could create a PCH out of all the headers that are very +commonly used throughout your project, and then create a PCH for every +single source file in the project that includes the code that is +specific to that file, so that recompiling the file itself is very fast, +without duplicating the data from the common headers for every file.

+ +

Precompiled Header Contents

+ +Precompiled header layout + +

Clang's precompiled headers are organized into several different +blocks, each of which contains the serialized representation of a part +of Clang's internal representation. Each of the blocks corresponds to +either a block or a record within LLVM's bitstream +format. The contents of each of these logical blocks are described +below.

+ +

For a given precompiled header, the llvm-bcanalyzer +utility can be used to examine the actual structure of the bitstream +for the precompiled header. This information can be used both to help +understand the structure of the precompiled header and to isolate +areas where precompiled headers can still be optimized, e.g., through +the introduction of abbreviations.

+ +

Metadata Block

+ +

The metadata block contains several records that provide +information about how the precompiled header was built. This metadata +is primarily used to validate the use of a precompiled header. For +example, a precompiled header built for a 32-bit x86 target cannot be used +when compiling for a 64-bit x86 target. The metadata block contains +information about:

+ +
+
Language options
+
Describes the particular language dialect used to compile the +PCH file, including major options (e.g., Objective-C support) and more +minor options (e.g., support for "//" comments). The contents of this +record correspond to the LangOptions class.
+ +
Target architecture
+
The target triple that describes the architecture, platform, and +ABI for which the PCH file was generated, e.g., +i386-apple-darwin9.
+ +
PCH version
+
The major and minor version numbers of the precompiled header +format. Changes in the minor version number should not affect backward +compatibility, while changes in the major version number imply that a +newer compiler cannot read an older precompiled header (and +vice-versa).
+ +
Original file name
+
The full path of the header that was used to generate the +precompiled header.
+ +
Predefines buffer
+
Although not explicitly stored as part of the metadata, the +predefines buffer is used in the validation of the precompiled header. +The predefines buffer itself contains code generated by the compiler +to initialize the preprocessor state according to the current target, +platform, and command-line options. For example, the predefines buffer +will contain "#define __STDC__ 1" when we are compiling C +without Microsoft extensions. The predefines buffer itself is stored +within the source manager block, but its +contents are verified along with the rest of the metadata.
+ +
+ +

A chained PCH file (that is, one that references another PCH) has +a slightly different metadata block, which contains the following +information:

+ +
+
Referenced file
+
The name of the referenced PCH file. It is looked up like a file +specified using -include-pch.
+ +
PCH version
+
This is the same as in normal PCH files.
+ +
Original file name
+
The full path of the header that was used to generate this +precompiled header.
+ +
+ +

The language options, target architecture and predefines buffer data +is taken from the end of the chain, since they have to match anyway.

+ +

Source Manager Block

+ +

The source manager block contains the serialized representation of +Clang's SourceManager class, +which handles the mapping from source locations (as represented in +Clang's abstract syntax tree) into actual column/line positions within +a source file or macro instantiation. The precompiled header's +representation of the source manager also includes information about +all of the headers that were (transitively) included when building the +precompiled header.

+ +

The bulk of the source manager block is dedicated to information +about the various files, buffers, and macro instantiations into which +a source location can refer. Each of these is referenced by a numeric +"file ID", which is a unique number (allocated starting at 1) stored +in the source location. Clang serializes the information for each kind +of file ID, along with an index that maps file IDs to the position +within the PCH file where the information about that file ID is +stored. The data associated with a file ID is loaded only when +required by the front end, e.g., to emit a diagnostic that includes a +macro instantiation history inside the header itself.

+ +

The source manager block also contains information about all of the +headers that were included when building the precompiled header. This +includes information about the controlling macro for the header (e.g., +when the preprocessor identified that the contents of the header +dependent on a macro like LLVM_CLANG_SOURCEMANAGER_H) +along with a cached version of the results of the stat() +system calls performed when building the precompiled header. The +latter is particularly useful in reducing system time when searching +for include files.

+ +

Preprocessor Block

+ +

The preprocessor block contains the serialized representation of +the preprocessor. Specifically, it contains all of the macros that +have been defined by the end of the header used to build the +precompiled header, along with the token sequences that comprise each +macro. The macro definitions are only read from the PCH file when the +name of the macro first occurs in the program. This lazy loading of +macro definitions is triggered by lookups into the identifier table.

+ +

Types Block

+ +

The types block contains the serialized representation of all of +the types referenced in the translation unit. Each Clang type node +(PointerType, FunctionProtoType, etc.) has a +corresponding record type in the PCH file. When types are deserialized +from the precompiled header, the data within the record is used to +reconstruct the appropriate type node using the AST context.

+ +

Each type has a unique type ID, which is an integer that uniquely +identifies that type. Type ID 0 represents the NULL type, type IDs +less than NUM_PREDEF_TYPE_IDS represent predefined types +(void, float, etc.), while other +"user-defined" type IDs are assigned consecutively from +NUM_PREDEF_TYPE_IDS upward as the types are encountered. +The PCH file has an associated mapping from the user-defined types +block to the location within the types block where the serialized +representation of that type resides, enabling lazy deserialization of +types. When a type is referenced from within the PCH file, that +reference is encoded using the type ID shifted left by 3 bits. The +lower three bits are used to represent the const, +volatile, and restrict qualifiers, as in +Clang's QualType +class.

+ +

Declarations Block

+ +

The declarations block contains the serialized representation of +all of the declarations referenced in the translation unit. Each Clang +declaration node (VarDecl, FunctionDecl, +etc.) has a corresponding record type in the PCH file. When +declarations are deserialized from the precompiled header, the data +within the record is used to build and populate a new instance of the +corresponding Decl node. As with types, each declaration +node has a numeric ID that is used to refer to that declaration within +the PCH file. In addition, a lookup table provides a mapping from that +numeric ID to the offset within the precompiled header where that +declaration is described.

+ +

Declarations in Clang's abstract syntax trees are stored +hierarchically. At the top of the hierarchy is the translation unit +(TranslationUnitDecl), which contains all of the +declarations in the translation unit. These declarations (such as +functions or struct types) may also contain other declarations inside +them, and so on. Within Clang, each declaration is stored within a declaration +context, as represented by the DeclContext class. +Declaration contexts provide the mechanism to perform name lookup +within a given declaration (e.g., find the member named x +in a structure) and iterate over the declarations stored within a +context (e.g., iterate over all of the fields of a structure for +structure layout).

+ +

In Clang's precompiled header format, deserializing a declaration +that is a DeclContext is a separate operation from +deserializing all of the declarations stored within that declaration +context. Therefore, Clang will deserialize the translation unit +declaration without deserializing the declarations within that +translation unit. When required, the declarations stored within a +declaration context will be deserialized. There are two representations +of the declarations within a declaration context, which correspond to +the name-lookup and iteration behavior described above:

+ +
    +
  • When the front end performs name lookup to find a name + x within a given declaration context (for example, + during semantic analysis of the expression p->x, + where p's type is defined in the precompiled header), + Clang deserializes a hash table mapping from the names within that + declaration context to the declaration IDs that represent each + visible declaration with that name. The entire hash table is + deserialized at this point (into the llvm::DenseMap + stored within each DeclContext object), but the actual + declarations are not yet deserialized. In a second step, those + declarations with the name x will be deserialized and + will be used as the result of name lookup.
  • + +
  • When the front end performs iteration over all of the + declarations within a declaration context, all of those declarations + are immediately de-serialized. For large declaration contexts (e.g., + the translation unit), this operation is expensive; however, large + declaration contexts are not traversed in normal compilation, since + such a traversal is unnecessary. However, it is common for the code + generator and semantic analysis to traverse declaration contexts for + structs, classes, unions, and enumerations, although those contexts + contain relatively few declarations in the common case.
  • +
+ +

Statements and Expressions

+ +

Statements and expressions are stored in the precompiled header in +both the types and the declarations blocks, because every statement or +expression will be associated with either a type or declaration. The +actual statement and expression records are stored immediately +following the declaration or type that owns the statement or +expression. For example, the statement representing the body of a +function will be stored directly following the declaration of the +function.

+ +

As with types and declarations, each statement and expression kind +in Clang's abstract syntax tree (ForStmt, +CallExpr, etc.) has a corresponding record type in the +precompiled header, which contains the serialized representation of +that statement or expression. Each substatement or subexpression +within an expression is stored as a separate record (which keeps most +records to a fixed size). Within the precompiled header, the +subexpressions of an expression are stored, in reverse order, prior to the expression +that owns those expression, using a form of Reverse +Polish Notation. For example, an expression 3 - 4 + 5 +would be represented as follows:

+ + + + + + + + +
IntegerLiteral(5)
IntegerLiteral(4)
IntegerLiteral(3)
BinaryOperator(-)
BinaryOperator(+)
STOP
+ +

When reading this representation, Clang evaluates each expression +record it encounters, builds the appropriate abstract syntax tree node, +and then pushes that expression on to a stack. When a record contains N +subexpressions--BinaryOperator has two of them--those +expressions are popped from the top of the stack. The special STOP +code indicates that we have reached the end of a serialized expression +or statement; other expression or statement records may follow, but +they are part of a different expression.

+ +

Identifier Table Block

+ +

The identifier table block contains an on-disk hash table that maps +each identifier mentioned within the precompiled header to the +serialized representation of the identifier's information (e.g, the +IdentifierInfo structure). The serialized representation +contains:

+ +
    +
  • The actual identifier string.
  • +
  • Flags that describe whether this identifier is the name of a + built-in, a poisoned identifier, an extension token, or a + macro.
  • +
  • If the identifier names a macro, the offset of the macro + definition within the preprocessor + block.
  • +
  • If the identifier names one or more declarations visible from + translation unit scope, the declaration IDs of these + declarations.
  • +
+ +

When a precompiled header is loaded, the precompiled header +mechanism introduces itself into the identifier table as an external +lookup source. Thus, when the user program refers to an identifier +that has not yet been seen, Clang will perform a lookup into the +identifier table. If an identifier is found, its contents (macro +definitions, flags, top-level declarations, etc.) will be deserialized, at which point the corresponding IdentifierInfo structure will have the same contents it would have after parsing the headers in the precompiled header.

+ +

Within the PCH file, the identifiers used to name declarations are represented with an integral value. A separate table provides a mapping from this integral value (the identifier ID) to the location within the on-disk +hash table where that identifier is stored. This mapping is used when +deserializing the name of a declaration, the identifier of a token, or +any other construct in the PCH file that refers to a name.

+ +

Method Pool Block

+ +

The method pool block is represented as an on-disk hash table that +serves two purposes: it provides a mapping from the names of +Objective-C selectors to the set of Objective-C instance and class +methods that have that particular selector (which is required for +semantic analysis in Objective-C) and also stores all of the selectors +used by entities within the precompiled header. The design of the +method pool is similar to that of the identifier +table: the first time a particular selector is formed during the +compilation of the program, Clang will search in the on-disk hash +table of selectors; if found, Clang will read the Objective-C methods +associated with that selector into the appropriate front-end data +structure (Sema::InstanceMethodPool and +Sema::FactoryMethodPool for instance and class methods, +respectively).

+ +

As with identifiers, selectors are represented by numeric values +within the PCH file. A separate index maps these numeric selector +values to the offset of the selector within the on-disk hash table, +and will be used when de-serializing an Objective-C method declaration +(or other Objective-C construct) that refers to the selector.

+ +

Precompiled Header Integration Points

+ +

The "lazy" deserialization behavior of precompiled headers requires +their integration into several completely different submodules of +Clang. For example, lazily deserializing the declarations during name +lookup requires that the name-lookup routines be able to query the +precompiled header to find entities within the PCH file.

+ +

For each Clang data structure that requires direct interaction with +the precompiled header logic, there is an abstract class that provides +the interface between the two modules. The PCHReader +class, which handles the loading of a precompiled header, inherits +from all of these abstract classes to provide lazy deserialization of +Clang's data structures. PCHReader implements the +following abstract classes:

+ +
+
StatSysCallCache
+
This abstract interface is associated with the + FileManager class, and is used whenever the file + manager is going to perform a stat() system call.
+ +
ExternalSLocEntrySource
+
This abstract interface is associated with the + SourceManager class, and is used whenever the + source manager needs to load the details + of a file, buffer, or macro instantiation.
+ +
IdentifierInfoLookup
+
This abstract interface is associated with the + IdentifierTable class, and is used whenever the + program source refers to an identifier that has not yet been seen. + In this case, the precompiled header implementation searches for + this identifier within its identifier table + to load any top-level declarations or macros associated with that + identifier.
+ +
ExternalASTSource
+
This abstract interface is associated with the + ASTContext class, and is used whenever the abstract + syntax tree nodes need to loaded from the precompiled header. It + provides the ability to de-serialize declarations and types + identified by their numeric values, read the bodies of functions + when required, and read the declarations stored within a + declaration context (either for iteration or for name lookup).
+ +
ExternalSemaSource
+
This abstract interface is associated with the Sema + class, and is used whenever semantic analysis needs to read + information from the global method + pool.
+
+ +
+ + + diff --git a/cpp/llvm/tools/clang/docs/PCHLayout.graffle b/cpp/llvm/tools/clang/docs/PCHLayout.graffle new file mode 100644 index 00000000..5c96bfb7 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/PCHLayout.graffle @@ -0,0 +1,1880 @@ + + + + + ActiveLayerIndex + 0 + ApplicationVersion + + com.omnigroup.OmniGrafflePro + 137.11.0.108132 + + AutoAdjust + + BackgroundGraphic + + Bounds + {{0, 0}, {576, 733}} + Class + SolidGraphic + ID + 2 + Style + + shadow + + Draws + NO + + stroke + + Draws + NO + + + + CanvasOrigin + {0, 0} + ColumnAlign + 1 + ColumnSpacing + 36 + CreationDate + 2009-06-02 11:19:43 -0700 + Creator + Douglas Gregor + DisplayScale + 1 0/72 in = 1.0000 in + GraphDocumentVersion + 6 + GraphicsList + + + Bounds + {{35, 301}, {104, 30}} + Class + ShapedGraphic + ID + 13 + Layer + 0 + Shape + Rectangle + Style + + fill + + Color + + b + 0.175793 + g + 0.402929 + r + 1 + + + stroke + + CornerRadius + 9 + + + Text + + Text + {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\qc\pardirnatural + +\f0\fs24 \cf0 Method Pool} + + + + Bounds + {{32, 58}, {110, 14}} + Class + ShapedGraphic + FitText + YES + Flow + Resize + ID + 12 + Layer + 0 + Shape + Rectangle + Style + + fill + + Draws + NO + + shadow + + Draws + NO + + stroke + + Draws + NO + + + Text + + Pad + 0 + Text + {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\qc\pardirnatural + +\f0\fs24 \cf0 Precompiled Header} + VerticalPad + 0 + + Wrap + NO + + + Bounds + {{35, 190}, {104, 30}} + Class + ShapedGraphic + ID + 11 + Layer + 0 + Shape + Rectangle + Style + + fill + + Color + + b + 1 + g + 0.796208 + r + 0.324589 + + + stroke + + CornerRadius + 9 + + + Text + + Text + {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\qc\pardirnatural + +\f0\fs24 \cf0 Types} + + + + Bounds + {{35, 227}, {104, 30}} + Class + ShapedGraphic + ID + 10 + Layer + 0 + Shape + Rectangle + Style + + fill + + Color + + b + 1 + g + 0.382716 + r + 0.524072 + + + stroke + + CornerRadius + 9 + + + Text + + Text + {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\qc\pardirnatural + +\f0\fs24 \cf0 Declarations} + + + + Bounds + {{35, 264}, {104, 30}} + Class + ShapedGraphic + ID + 8 + Layer + 0 + Shape + Rectangle + Style + + fill + + Color + + b + 0.99938 + g + 0.457913 + r + 1 + + + stroke + + CornerRadius + 9 + + + Text + + Text + {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\qc\pardirnatural + +\f0\fs24 \cf0 Identifier Table} + + + + Bounds + {{35, 153}, {104, 30}} + Class + ShapedGraphic + ID + 7 + Layer + 0 + Shape + Rectangle + Style + + fill + + Color + + b + 0.669993 + g + 1 + r + 0.254644 + + + stroke + + CornerRadius + 9 + + + Text + + Text + {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\qc\pardirnatural + +\f0\fs24 \cf0 Preprocessor} + + + + Bounds + {{35, 116}, {104, 30}} + Class + ShapedGraphic + ID + 6 + Layer + 0 + Shape + Rectangle + Style + + fill + + Color + + b + 0.258332 + g + 1 + r + 0.593784 + + + stroke + + CornerRadius + 9 + + + Text + + Text + {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\qc\pardirnatural + +\f0\fs24 \cf0 Source Manager} + + + + Bounds + {{35, 79}, {104, 30}} + Class + ShapedGraphic + ID + 5 + Layer + 0 + Shape + Rectangle + Style + + fill + + Color + + b + 0.270873 + g + 1 + r + 0.979351 + + + stroke + + CornerRadius + 9 + + + Text + + Text + {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\qc\pardirnatural + +\f0\fs24 \cf0 Metadata} + + + + Bounds + {{21, 47}, {132, 293}} + Class + ShapedGraphic + ID + 4 + Layer + 1 + Shape + Rectangle + Style + + fill + + FillType + 2 + GradientAngle + 90 + + stroke + + CornerRadius + 9 + + + + + GridInfo + + GuidesLocked + NO + GuidesVisible + YES + HPages + 1 + ImageCounter + 1 + KeepToScale + + Layers + + + Lock + NO + Name + Sub-blocks + Print + YES + View + YES + + + Lock + NO + Name + PCH Block + Print + YES + View + YES + + + LayoutInfo + + Animate + NO + circoMinDist + 18 + circoSeparation + 0.0 + layoutEngine + dot + neatoSeparation + 0.0 + twopiSeparation + 0.0 + + LinksVisible + NO + MagnetsVisible + NO + MasterSheets + + ModificationDate + 2009-06-03 08:22:05 -0700 + Modifier + Douglas Gregor + NotesVisible + NO + Orientation + 2 + OriginVisible + NO + PageBreaks + YES + PrintInfo + + NSBottomMargin + + float + 41 + + NSLeftMargin + + float + 18 + + NSPaperSize + + size + {612, 792} + + NSRightMargin + + float + 18 + + NSTopMargin + + float + 18 + + + PrintOnePage + + QuickLookPreview + + JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmls + dGVyIC9GbGF0ZURlY29kZSA+PgpzdHJlYW0KeAGNWNtuGzcQfedX8LF5iMz77r7WadEU + CJDUBvqsyptagWQ5klOgP9tv6TnDy64syXYMhGeo5XAuZ4bc/a6/6O/a4C92SXfe6/2o + /9QP2iySkX96ra+uD1avDtrK32Gl35tFLL9OqChQUPBVX30e96vx8enHcqP3a2xhY5Bt + vI3aGu27Xq+2+urj1uoPOxhBM7zRqU96q20IRGoD1C+GziT5wUaP0eYJEbpOr6Da62Cc + xtNAfugWxg1hWuoHr6gRI57GJgQb7aI8l+ednRYCU91KF3A0KEybxcB/OmF76GliNa1o + prFJu6E+DWGl75uXimHG4oidHf63CD7tLgk4jaDE773VfaejH7CCAby5t/pwr3IAz+TR + 6t+RtW+n+by+EX1G31wzPVW5IQkUNCNOoSu5AJilAhIDHa3Ez2WBvkn4va2J8FEyhdiX + HPpgJLUccyIA5omAyESUhRmDeRU4qzzUyyMyXSMf0zwPzbCWB1jc0gCcs6CAtvoGzDsN + tUsSj+i0AxPNULjqMlcRrqMHYucYMZDZX3jA52R93IbzDwRskzVEJeXwfIuQ4LBskS5o + GGpBdecf8H1XjOzzA1d/jJvl0/qf8Xq32e3X2/Fpv16xWGu5I7rd4COqFexYuM70HUiB + 8g9BJZQz6pQVCwRy+FDqFKL1qI0A3rNwswD/MwLJ+TQecL3wR01LEQTRyGBgEzxC1aA6 + 6zmLCGRdqImhDkzKwEdF+Wg6RGrA79WcSRsMpVIM5EOBW/Suc9WAn7uheAwwcxgS3el9 + rQYKyIXMWkOC83drcoAmdy1oRXc5irsEM3cpwvK6MGMpHE6ii0WVB5EkCthXvG3GNG9h + ZXah+CrOCPevD2h1ByWJNWj2M+/RaBJMB+9+vgXlS4tw+j0Ly6akg74FJ39FIwBFbr/q + nz6NT8u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DBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBg + wIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYM + GDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIAB + AwYMGDBgwIABAwYMGDBgwIABAwYMGDBg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yBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB + hWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0 + UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYA + oog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBBhWYAoog0UyBB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EQZmlGSQAAABAAAAEgZGFESwAAABwA + AAEwemhDTgAAAAwAAAFMZnJGUgAAABYAAAFYamFKUAAAAA4AAAFuZW5VUwAAABIAAAF8 + cGxQTAAAABIAAAGOcHRCUgAAABgAAAGgZXNFUwAAABIAAAG4emhUVwAAAA4AAAHKcnVS + VQAAACQAAAHYa29LUgAAAAwAAAH8ZGVERQAAABAAAAIIbmxOTAAAABYAAAIYaXRJVAAA + ABQAAAIuAEYAYQByAGcAZQAtAEwAQwBEAEwAQwBEACAAYQAgAEMAbwByAGUAcwBGAOQA + cgBnAC0ATABDAEQAVgDkAHIAaQAtAEwAQwBEAEwAQwBEAC0AZgBhAHIAdgBlAHMAawDm + AHIAbV9pgnIAIABMAEMARABMAEMARAAgAGMAbwB1AGwAZQB1AHIwqzDpMPwAIABMAEMA + RABDAG8AbABvAHIAIABMAEMARABLAG8AbABvAHIAIABMAEMARABMAEMARAAgAEMAbwBs + AG8AcgBpAGQAbwBMAEMARAAgAGMAbwBsAG8Acl9pgnJtsmZ2mG95OlZoBCYEMgQ1BEIE + PQQ+BDkAIAQWBBoALQQ0BDgEQQQ/BDsENQQ5zuy37AAgAEwAQwBEAEYAYQByAGIALQBM + AEMARABLAGwAZQB1AHIAZQBuAC0ATABDAEQATABDAEQAIABjAG8AbABvAHIAaQAAbW1v + ZAAAAAAAAAYQAACcgAAAAADDJekAAAAAAAAAAAAAAAAAAAAAAHRleHQAAAAAQ29weXJp + Z2h0IEFwcGxlLCBJbmMuLCAyMDA5AA== + + ReadOnly + NO + RowAlign + 1 + RowSpacing + 36 + SheetTitle + Canvas 1 + SmartAlignmentGuidesActive + YES + SmartDistanceGuidesActive + YES + UniqueID + 1 + UseEntirePage + + VPages + 1 + WindowInfo + + CurrentSheet + 0 + ExpandedCanvases + + + name + Canvas 1 + + + Frame + {{388, 0}, {710, 878}} + ListView + + OutlineWidth + 142 + RightSidebar + + ShowRuler + + Sidebar + + SidebarWidth + 120 + VisibleRegion + {{0, 0}, {561, 709}} + Zoom + 1 + ZoomValues + + + Canvas 1 + 1 + 1 + + + + saveQuickLookFiles + YES + + diff --git a/cpp/llvm/tools/clang/docs/PCHLayout.png b/cpp/llvm/tools/clang/docs/PCHLayout.png new file mode 100644 index 00000000..c304e04a Binary files /dev/null and b/cpp/llvm/tools/clang/docs/PCHLayout.png differ diff --git a/cpp/llvm/tools/clang/docs/PTHInternals.html b/cpp/llvm/tools/clang/docs/PTHInternals.html new file mode 100644 index 00000000..b15f6816 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/PTHInternals.html @@ -0,0 +1,179 @@ + + + + Pretokenized Headers (PTH) + + + + + + + + +
+ +

Pretokenized Headers (PTH)

+ +

This document first describes the low-level +interface for using PTH and then briefly elaborates on its design and +implementation. If you are interested in the end-user view, please see the +User's Manual.

+ + +

Using Pretokenized Headers with clang (Low-level Interface)

+ +

The Clang compiler frontend, clang -cc1, supports three command line +options for generating and using PTH files.

+ +

To generate PTH files using clang -cc1, use the option +-emit-pth: + +

 $ clang -cc1 test.h -emit-pth -o test.h.pth 
+ +

This option is transparently used by clang when generating PTH +files. Similarly, PTH files can be used as prefix headers using the +-include-pth option:

+ +
+  $ clang -cc1 -include-pth test.h.pth test.c -o test.s
+
+ +

Alternatively, Clang's PTH files can be used as a raw "token-cache" +(or "content" cache) of the source included by the original header +file. This means that the contents of the PTH file are searched as substitutes +for any source files that are used by clang -cc1 to process a +source file. This is done by specifying the -token-cache +option:

+ +
+  $ cat test.h
+  #include <stdio.h>
+  $ clang -cc1 -emit-pth test.h -o test.h.pth
+  $ cat test.c
+  #include "test.h"
+  $ clang -cc1 test.c -o test -token-cache test.h.pth
+
+ +

In this example the contents of stdio.h (and the files it includes) +will be retrieved from test.h.pth, as the PTH file is being used in +this case as a raw cache of the contents of test.h. This is a low-level +interface used to both implement the high-level PTH interface as well as to +provide alternative means to use PTH-style caching.

+ +

PTH Design and Implementation

+ +

Unlike GCC's precompiled headers, which cache the full ASTs and preprocessor +state of a header file, Clang's pretokenized header files mainly cache the raw +lexer tokens that are needed to segment the stream of characters in a +source file into keywords, identifiers, and operators. Consequently, PTH serves +to mainly directly speed up the lexing and preprocessing of a source file, while +parsing and type-checking must be completely redone every time a PTH file is +used.

+ +

Basic Design Tradeoffs

+ +

In the long term there are plans to provide an alternate PCH implementation +for Clang that also caches the work for parsing and type checking the contents +of header files. The current implementation of PCH in Clang as pretokenized +header files was motivated by the following factors:

+ +

    + +
  • Language independence: PTH files work with any language that +Clang's lexer can handle, including C, Objective-C, and (in the early stages) +C++. This means development on language features at the parsing level or above +(which is basically almost all interesting pieces) does not require PTH to be +modified.

  • + +
  • Simple design: Relatively speaking, PTH has a simple design and +implementation, making it easy to test. Further, because the machinery for PTH +resides at the lower-levels of the Clang library stack it is fairly +straightforward to profile and optimize.
  • +
+ +

Further, compared to GCC's PCH implementation (which is the dominate +precompiled header file implementation that Clang can be directly compared +against) the PTH design in Clang yields several attractive features:

+ +
    + +
  • Architecture independence: In contrast to GCC's PCH files (and +those of several other compilers), Clang's PTH files are architecture +independent, requiring only a single PTH file when building an program for +multiple architectures.

    + +

    For example, on Mac OS X one may wish to +compile a "universal binary" that runs on PowerPC, 32-bit Intel +(i386), and 64-bit Intel architectures. In contrast, GCC requires a PCH file for +each architecture, as the definitions of types in the AST are +architecture-specific. Since a Clang PTH file essentially represents a lexical +cache of header files, a single PTH file can be safely used when compiling for +multiple architectures. This can also reduce compile times because only a single +PTH file needs to be generated during a build instead of several.

  • + +
  • Reduced memory pressure: Similar to GCC, +Clang reads PTH files via the use of memory mapping (i.e., mmap). +Clang, however, memory maps PTH files as read-only, meaning that multiple +invocations of clang -cc1 can share the same pages in memory from a +memory-mapped PTH file. In comparison, GCC also memory maps its PCH files but +also modifies those pages in memory, incurring the copy-on-write costs. The +read-only nature of PTH can greatly reduce memory pressure for builds involving +multiple cores, thus improving overall scalability.

  • + +
  • Fast generation: PTH files can be generated in a small fraction +of the time needed to generate GCC's PCH files. Since PTH/PCH generation is a +serial operation that typically blocks progress during a build, faster +generation time leads to improved processor utilization with parallel builds on +multicore machines.

  • + +
+ +

Despite these strengths, PTH's simple design suffers some algorithmic +handicaps compared to other PCH strategies such as those used by GCC. While PTH +can greatly speed up the processing time of a header file, the amount of work +required to process a header file is still roughly linear in the size of the +header file. In contrast, the amount of work done by GCC to process a +precompiled header is (theoretically) constant (the ASTs for the header are +literally memory mapped into the compiler). This means that only the pieces of +the header file that are referenced by the source file including the header are +the only ones the compiler needs to process during actual compilation. While +GCC's particular implementation of PCH mitigates some of these algorithmic +strengths via the use of copy-on-write pages, the approach itself can +fundamentally dominate at an algorithmic level, especially when one considers +header files of arbitrary size.

+ +

There are plans to potentially implement an complementary PCH implementation +for Clang based on the lazy deserialization of ASTs. This approach would +theoretically have the same constant-time algorithmic advantages just mentioned +but would also retain some of the strengths of PTH such as reduced memory +pressure (ideal for multi-core builds).

+ +

Internal PTH Optimizations

+ +

While the main optimization employed by PTH is to reduce lexing time of +header files by caching pre-lexed tokens, PTH also employs several other +optimizations to speed up the processing of header files:

+ +
    + +
  • stat caching: PTH files cache information obtained via +calls to stat that clang -cc1 uses to resolve which files are +included by #include directives. This greatly reduces the overhead +involved in context-switching to the kernel to resolve included files.

  • + +
  • Fasting skipping of #ifdef...#endif chains: +PTH files record the basic structure of nested preprocessor blocks. When the +condition of the preprocessor block is false, all of its tokens are immediately +skipped instead of requiring them to be handled by Clang's +preprocessor.

  • + +
+ +
+ + diff --git a/cpp/llvm/tools/clang/docs/ReleaseNotes.html b/cpp/llvm/tools/clang/docs/ReleaseNotes.html new file mode 100644 index 00000000..8367b8a7 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/ReleaseNotes.html @@ -0,0 +1,177 @@ + + + +Clang 3.1 Release Notes + + + + + + + + +
+ +

Clang 3.1 Release Notes

+ +LLVM Dragon Logo + + + +
+

Written by the LLVM Team

+
+ + +

Introduction

+ + +

This document contains the release notes for the Clang C/C++/Objective-C +frontend, part of the LLVM Compiler Infrastructure, release 3.1. Here we +describe the status of Clang in some detail, including major improvements from +the previous release and new feature work. For the general LLVM release notes, +see the LLVM + documentation. All LLVM releases may be downloaded from the +LLVM releases web site.

+ +

For more information about Clang or LLVM, including information about the +latest release, please check out the main please see the +Clang Web Site or the +LLVM Web Site. + +

Note that if you are reading this file from a Subversion checkout or the main +Clang web page, this document applies to the next release, not the +current one. To see the release notes for a specific release, please see the +releases page.

+ + +

What's New in Clang 3.1?

+ + +

Some of the major new features and improvements to Clang are listed here. +Generic improvements to Clang as a whole or two its underlying infrastructure +are described first, followed by language-specific sections with improvements to +Clang's support for those languages.

+ + +

C Language Changes in Clang

+ + +

C11 Feature Support

+ +

Clang 3.1 adds support for anonymous structs and anonymous unions, added in +the latest ISO C standard. Use -std=c11 or -std=gnu11 +to enable support for the new language standard. The new C11 features are +backwards-compatible and are available as an extension in all language +modes.

+ +

All warning and language selection flags which previously accepted +c1x have been updated to accept c11. The old +c1x forms have been removed. + + +

C++ Language Changes in Clang

+ + +

C++11 Feature Support

+

Clang 3.1 supports +most of the language +features added in the latest ISO C++ standard, +C++ 2011. +Use -std=c++11 or -std=gnu++11 to enable support for +these features. In addition to the features supported by Clang 3.0, the +following are now considered to be of production quality: +

    +
  • Generalized constant expressions
  • +
  • Lambda expressions
  • +
  • Generalized initializers
  • +
  • Unrestricted unions
  • +
  • User-defined literals
  • +
  • Forward-declared enumerations
  • +
  • Atomics (both libc++'s and libstdc++4.7's <atomic> are + supported)
  • +
+ + +

Objective-C Language Changes in Clang

+ +Clang 3.1 introduces several new Objective-C language features and improvements. + +

Objective-C literals and subscripting

+ +

Objective-C now provides additional literal expressions, including numeric, array, and dictionary literals. Additionally, array and dictionary elements can be accesses via the subscripting operator. For more information about the new literals, see the documentation for Objective-C literals and subscripting. + +

Format string checking for NSString literals

+ +-Wformat now checks @"NSString literals". + + +

Python Binding Changes

+ + +The following methods have been added: +
    +
  • SourceLocation.from_position (static)
  • +
  • SourceLocation.__eq__ and SourceLocation.__ne__
  • +
  • SourceRange.__eq__ and SourceRange.__ne__
  • +
  • Diagnostic.category_number (property)
  • +
  • Diagnostic.category_name (property)
  • +
  • Diagnostic.option (property)
  • +
  • Diagnostic.disable_option (property)
  • +
  • CursorKind.is_translation_unit
  • +
  • CursorKind.is_preprocessing
  • +
  • CursorKind.is_unexposed
  • +
  • Cursor.from_location (static)
  • +
  • Cursor.underlying_typedef_type (property)
  • +
  • Cursor.enum_type (property)
  • +
  • Cursor.objc_type_encoding (property)
  • +
  • Cursor.hash
  • +
  • TypeKind.spelling
  • +
  • Type.argument_types
  • +
  • Type.element_type (property)
  • +
  • Type.element_count (property)
  • +
  • Type.is_function_variadic
  • +
  • Type.is_pod
  • +
  • Type.get_array_element_type
  • +
  • Type.get_array_size
  • +
  • Type.__eq__ and Type.__ne__
  • +
  • File.from_name (static)
  • +
  • File.__str__ and File.__repr__
  • +
+ + +

Additional Information

+ + +

A wide variety of additional information is available on the +Clang web page. The web page contains +versions of the API documentation which are up-to-date with the Subversion +version of the source code. You can access versions of these documents specific +to this release by going into the "clang/doc/" directory in the Clang +tree.

+ +

If you have any questions or comments about Clang, please feel free to +contact us via the +mailing list.

+ + +
+ + diff --git a/cpp/llvm/tools/clang/docs/UsersManual.html b/cpp/llvm/tools/clang/docs/UsersManual.html new file mode 100644 index 00000000..b33ed612 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/UsersManual.html @@ -0,0 +1,1147 @@ + + + +Clang Compiler User's Manual + + + + + + + + +
+ +

Clang Compiler User's Manual

+ + + + + +

Introduction

+ + +

The Clang Compiler is an open-source compiler for the C family of programming +languages, aiming to be the best in class implementation of these languages. +Clang builds on the LLVM optimizer and code generator, allowing it to provide +high-quality optimization and code generation support for many targets. For +more general information, please see the Clang +Web Site or the LLVM Web Site.

+ +

This document describes important notes about using Clang as a compiler for +an end-user, documenting the supported features, command line options, etc. If +you are interested in using Clang to build a tool that processes code, please +see the Clang Internals Manual. If you are +interested in the Clang +Static Analyzer, please see its web page.

+ +

Clang is designed to support the C family of programming languages, which +includes C, Objective-C, C++, and Objective-C++ as well as many +dialects of those. For language-specific information, please see the +corresponding language specific section:

+ + + +

In addition to these base languages and their dialects, Clang supports a +broad variety of language extensions, which are documented in the corresponding +language section. These extensions are provided to be compatible with the GCC, +Microsoft, and other popular compilers as well as to improve functionality +through Clang-specific features. The Clang driver and language features are +intentionally designed to be as compatible with the GNU GCC compiler as +reasonably possible, easing migration from GCC to Clang. In most cases, code +"just works".

+ +

In addition to language specific features, Clang has a variety of features +that depend on what CPU architecture or operating system is being compiled for. +Please see the Target-Specific Features and +Limitations section for more details.

+ +

The rest of the introduction introduces some basic compiler terminology that is used throughout this manual +and contains a basic introduction to using Clang +as a command line compiler.

+ + +

Terminology

+ + +

Front end, parser, backend, preprocessor, undefined behavior, diagnostic, + optimizer

+ + +

Basic Usage

+ + +

Intro to how to use a C compiler for newbies.

+

+compile + link + +compile then link + +debug info + +enabling optimizations + +picking a language to use, defaults to C99 by default. Autosenses based on +extension. + +using a makefile +

+ + + +

Command Line Options

+ + +

+This section is generally an index into other sections. It does not go into +depth on the ones that are covered by other sections. However, the first part +introduces the language selection and other high level options like -c, -g, etc. +

+ + + +

Options to Control Error and Warning Messages

+ + +

-Werror: Turn warnings into errors.

+

-Werror=foo: Turn warning "foo" into an error.

+

-Wno-error=foo: Turn warning "foo" into an warning even if -Werror is + specified.

+

-Wfoo: Enable warning foo

+

-Wno-foo: Disable warning foo

+

-w: Disable all warnings.

+

-pedantic: Warn on language extensions.

+

-pedantic-errors: Error on language extensions.

+

-Wsystem-headers: Enable warnings from system headers.

+ +

-ferror-limit=123: Stop emitting diagnostics after 123 errors have + been produced. The default is 20, and the error limit can be disabled with + -ferror-limit=0.

+ +

-ftemplate-backtrace-limit=123: Only emit up to 123 template instantiation notes within the template instantiation backtrace for a single warning or error. The default is 10, and the limit can be disabled with -ftemplate-backtrace-limit=0.

+ + +

Formatting of Diagnostics

+ + +

Clang aims to produce beautiful diagnostics by default, particularly for new +users that first come to Clang. However, different people have different +preferences, and sometimes Clang is driven by another program that wants to +parse simple and consistent output, not a person. For these cases, Clang +provides a wide range of options to control the exact output format of the +diagnostics that it generates.

+ +
+ + +
-f[no-]show-column: Print column number in +diagnostic.
+
This option, which defaults to on, controls whether or not Clang prints the +column number of a diagnostic. For example, when this is enabled, Clang will +print something like: + +
+  test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
+  #endif bad
+         ^
+         //
+
+ +

When this is disabled, Clang will print "test.c:28: warning..." with no +column number.

+
+ + +
-f[no-]show-source-location: Print +source file/line/column information in diagnostic.
+
This option, which defaults to on, controls whether or not Clang prints the +filename, line number and column number of a diagnostic. For example, +when this is enabled, Clang will print something like: + +
+  test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
+  #endif bad
+         ^
+         //
+
+ +

When this is disabled, Clang will not print the "test.c:28:8: " part.

+
+ + +
-f[no-]caret-diagnostics: Print source +line and ranges from source code in diagnostic.
+
This option, which defaults to on, controls whether or not Clang prints the +source line, source ranges, and caret when emitting a diagnostic. For example, +when this is enabled, Clang will print something like: + +
+  test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
+  #endif bad
+         ^
+         //
+
+
+ +
-f[no-]color-diagnostics:
+
This option, which defaults to on when a color-capable terminal is + detected, controls whether or not Clang prints diagnostics in color. + When this option is enabled, Clang will use colors to highlight + specific parts of the diagnostic, e.g., +
+  test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
+  #endif bad
+         ^
+         //
+
+ +

When this is disabled, Clang will just print:

+ +
+  test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
+  #endif bad
+         ^
+         //
+
+
+ +
-fdiagnostics-format=clang/msvc/vi: +Changes diagnostic output format to better match IDEs and command line tools.
+
This option controls the output format of the filename, line number, and column printed in diagnostic messages. The options, and their affect on formatting a simple conversion diagnostic, follow: + +
+
clang (default)
+
+
t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
+
+ +
msvc
+
+
t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
+
+ +
vi
+
+
t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
+
+
+
+ + +
-f[no-]diagnostics-show-name: +Enable the display of the diagnostic name.
+
This option, which defaults to off, controls whether or not +Clang prints the associated name.

+ +
-f[no-]diagnostics-show-option: +Enable [-Woption] information in diagnostic line.
+
This option, which defaults to on, +controls whether or not Clang prints the associated warning group option name when outputting +a warning diagnostic. For example, in this output: + +
+  test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
+  #endif bad
+         ^
+         //
+
+ +

Passing -fno-diagnostics-show-option will prevent Clang from printing +the [-Wextra-tokens] information in the +diagnostic. This information tells you the flag needed to enable or disable the +diagnostic, either from the command line or through #pragma GCC diagnostic.

+ + +
-fdiagnostics-show-category=none/id/name: +Enable printing category information in diagnostic line.
+
This option, which defaults to "none", +controls whether or not Clang prints the category associated with a diagnostic +when emitting it. Each diagnostic may or many not have an associated category, +if it has one, it is listed in the diagnostic categorization field of the +diagnostic line (in the []'s). + +

For example, a format string warning will produce these three renditions +based on the setting of this option:

+ +
+  t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
+  t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
+  t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
+
+ +

This category can be used by clients that want to group diagnostics by +category, so it should be a high level category. We want dozens of these, not +hundreds or thousands of them.

+
+ + + + +
-f[no-]diagnostics-fixit-info: +Enable "FixIt" information in the diagnostics output.
+
This option, which defaults to on, controls whether or not Clang prints the +information on how to fix a specific diagnostic underneath it when it knows. +For example, in this output: + +
+  test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
+  #endif bad
+         ^
+         //
+
+ +

Passing -fno-diagnostics-fixit-info will prevent Clang from printing +the "//" line at the end of the message. This information is useful for users +who may not understand what is wrong, but can be confusing for machine +parsing.

+
+ + +
+-f[no-]diagnostics-print-source-range-info: +Print machine parsable information about source ranges.
+
This option, which defaults to off, controls whether or not Clang prints +information about source ranges in a machine parsable format after the +file/line/column number information. The information is a simple sequence of +brace enclosed ranges, where each range lists the start and end line/column +locations. For example, in this output: + +
+exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
+   P = (P-42) + Gamma*4;
+       ~~~~~~ ^ ~~~~~~~
+
+ +

The {}'s are generated by -fdiagnostics-print-source-range-info.

+
+ + +
+-fdiagnostics-parseable-fixits: +Print Fix-Its in a machine parseable form.
+

This option makes Clang print available Fix-Its in a machine parseable format at the end of diagnostics. The following example illustrates the format:

+ +
+ fix-it:"t.cpp":{7:25-7:29}:"Gamma"
+
+ +

The range printed is a half-open range, so in this example the characters at +column 25 up to but not including column 29 on line 7 in t.cpp should be +replaced with the string "Gamma". Either the range or the replacement +string may be empty (representing strict insertions and strict erasures, +respectively). Both the file name and the insertion string escape backslash (as +"\\"), tabs (as "\t"), newlines (as "\n"), double +quotes(as "\"") and non-printable characters (as octal +"\xxx").

+
+ +
+ + + + +

Individual Warning Groups

+ + +

TODO: Generate this from tblgen. Define one anchor per warning group.

+ + +
+ + + +
-Wextra-tokens: Warn about excess tokens at + the end of a preprocessor directive.
+
This option, which defaults to on, enables warnings about extra tokens at +the end of preprocessor directives. For example: + +
+  test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
+  #endif bad
+         ^
+
+ +

These extra tokens are not strictly conforming, and are usually best handled +by commenting them out.

+ +

This option is also enabled by -Wfoo, -Wbar, + and -Wbaz.

+
+ + +
-Wambiguous-member-template: +Warn about unqualified uses of a member template whose name resolves +to another template at the location of the use.
+
This option, which defaults to on, enables a warning in the +following code: + +
+template<typename T> struct set{};
+template<typename T> struct trait { typedef const T& type; };
+struct Value {
+  template<typename T> void set(typename trait<T>::type value) {}
+};
+void foo() {
+  Value v;
+  v.set<double>(3.2);
+}
+
+ +

C++ [basic.lookup.classref] requires this to be an error, but, +because it's hard to work around, Clang downgrades it to a warning as +an extension.

+
+ + +
-Wbind-to-temporary-copy: Warn about +an unusable copy constructor when binding a reference to a temporary.
+
This option, which defaults to on, enables warnings about binding a +reference to a temporary when the temporary doesn't have a usable copy +constructor. For example: + +
+  struct NonCopyable {
+    NonCopyable();
+  private:
+    NonCopyable(const NonCopyable&);
+  };
+  void foo(const NonCopyable&);
+  void bar() {
+    foo(NonCopyable());  // Disallowed in C++98; allowed in C++11.
+  }
+
+
+  struct NonCopyable2 {
+    NonCopyable2();
+    NonCopyable2(NonCopyable2&);
+  };
+  void foo(const NonCopyable2&);
+  void bar() {
+    foo(NonCopyable2());  // Disallowed in C++98; allowed in C++11.
+  }
+
+ +

Note that if NonCopyable2::NonCopyable2() has a default +argument whose instantiation produces a compile error, that error will +still be a hard error in C++98 mode even if this warning is turned +off.

+ +
+ +
+ + +

Options to Control Clang Crash Diagnostics

+ + +

As unbelievable as it may sound, Clang does crash from time to time. +Generally, this only occurs to those living on the +bleeding edge. Clang +goes to great lengths to assist you in filing a bug report. Specifically, Clang +generates preprocessed source file(s) and associated run script(s) upon a +crash. These files should be attached to a bug report to ease reproducibility +of the failure. Below are the command line options to control the crash +diagnostics. +

+ +

-fno-crash-diagnostics: Disable auto-generation of preprocessed +source files during a clang crash.

+ +

The -fno-crash-diagnostics flag can be helpful for speeding the process of +generating a delta reduced test case.

+ + + +

Language and Target-Independent Features

+ + + + +

Controlling Errors and Warnings

+ + +

Clang provides a number of ways to control which code constructs cause it to +emit errors and warning messages, and how they are displayed to the console.

+ +

Controlling How Clang Displays Diagnostics

+ +

When Clang emits a diagnostic, it includes rich information in the output, +and gives you fine-grain control over which information is printed. Clang has +the ability to print this information, and these are the options that control +it:

+ +
    +
  1. A file/line/column indicator that shows exactly where the diagnostic occurs + in your code [-fshow-column, -fshow-source-location].
  2. +
  3. A categorization of the diagnostic as a note, warning, error, or fatal + error.
  4. +
  5. A text string that describes what the problem is.
  6. +
  7. An option that indicates how to control the diagnostic (for diagnostics that + support it) [-fdiagnostics-show-option].
  8. +
  9. A high-level category for the + diagnostic for clients that want to group diagnostics by class (for + diagnostics that support it) [-fdiagnostics-show-category].
  10. +
  11. The line of source code that the issue occurs on, along with a caret and + ranges that indicate the important locations [-fcaret-diagnostics].
  12. +
  13. "FixIt" information, which is a concise explanation of how to fix the + problem (when Clang is certain it knows) [-fdiagnostics-fixit-info].
  14. +
  15. A machine-parsable representation of the ranges involved (off by + default) [-fdiagnostics-print-source-range-info].
  16. +
+ +

For more information please see Formatting of +Diagnostics.

+ + +

Diagnostic Mappings

+ +

All diagnostics are mapped into one of these 5 classes:

+ +
    +
  • Ignored
  • +
  • Note
  • +
  • Warning
  • +
  • Error
  • +
  • Fatal
  • +
+ +

Diagnostic Categories

+ +

Though not shown by default, diagnostics may each be associated with a + high-level category. This category is intended to make it possible to triage + builds that produce a large number of errors or warnings in a grouped way. +

+ +

Categories are not shown by default, but they can be turned on with the +-fdiagnostics-show-category option. +When set to "name", the category is printed textually in the diagnostic +output. When it is set to "id", a category number is printed. The +mapping of category names to category id's can be obtained by running 'clang + --print-diagnostic-categories'. +

+ +

Controlling Diagnostics via Command Line + Flags

+ +

-W flags, -pedantic, etc

+ +

Controlling Diagnostics via Pragmas

+ +

Clang can also control what diagnostics are enabled through the use of +pragmas in the source code. This is useful for turning off specific warnings +in a section of source code. Clang supports GCC's pragma for compatibility +with existing source code, as well as several extensions.

+ +

The pragma may control any warning that can be used from the command line. +Warnings may be set to ignored, warning, error, or fatal. The following +example code will tell Clang or GCC to ignore the -Wall warnings:

+ +
+#pragma GCC diagnostic ignored "-Wall"
+
+ +

In addition to all of the functionality provided by GCC's pragma, Clang +also allows you to push and pop the current warning state. This is particularly +useful when writing a header file that will be compiled by other people, because +you don't know what warning flags they build with.

+ +

In the below example +-Wmultichar is ignored for only a single line of code, after which the +diagnostics return to whatever state had previously existed.

+ +
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wmultichar"
+
+char b = 'df'; // no warning.
+
+#pragma clang diagnostic pop
+
+ +

The push and pop pragmas will save and restore the full diagnostic state of +the compiler, regardless of how it was set. That means that it is possible to +use push and pop around GCC compatible diagnostics and Clang will push and pop +them appropriately, while GCC will ignore the pushes and pops as unknown +pragmas. It should be noted that while Clang supports the GCC pragma, Clang and +GCC do not support the exact same set of warnings, so even when using GCC +compatible #pragmas there is no guarantee that they will have identical behaviour +on both compilers.

+ +

Enabling All Warnings

+ +

In addition to the traditional -W flags, one can enable all + warnings by passing -Weverything. + This works as expected with -Werror, + and also includes the warnings from -pedantic.

+ +

Note that when combined with -w (which disables all warnings), that + flag wins.

+ +

Controlling Static Analyzer Diagnostics

+ +

While not strictly part of the compiler, the diagnostics from Clang's static analyzer can also be influenced +by the user via changes to the source code. This can be done in two ways: + +

    + +
  • Annotations: The static analyzer recognizes various GCC-style +attributes (e.g., __attribute__((nonnull)))) that can either suppress +static analyzer warnings or teach the analyzer about code invariants which +enable it to find more bugs. While many of these attributes are standard GCC +attributes, additional ones have been added to Clang to specifically support the +static analyzer. Detailed information on these annotations can be found in the +analyzer's +documentation.
  • + +
  • __clang_analyzer__: When the static analyzer is using Clang +to parse source files, it implicitly defines the preprocessor macro +__clang_analyzer__. While discouraged, code can use this macro to +selectively exclude code the analyzer examines. Here is an example: + +
    +#ifndef __clang_analyzer__
    +// Code not to be analyzed
    +#endif
    +
    + +In general, this usage is discouraged. Instead, we prefer that users file bugs +against the analyzer when it flags false positives. There is also active +discussion of allowing users in the future to selectively silence specific +analyzer warnings (some of which can already be done using annotations).
  • + +
+ + +

Precompiled Headers

+ + +

Precompiled +headers are a general approach employed by many compilers to reduce +compilation time. The underlying motivation of the approach is that it is +common for the same (and often large) header files to be included by +multiple source files. Consequently, compile times can often be greatly improved +by caching some of the (redundant) work done by a compiler to process headers. +Precompiled header files, which represent one of many ways to implement +this optimization, are literally files that represent an on-disk cache that +contains the vital information necessary to reduce some of the work +needed to process a corresponding header file. While details of precompiled +headers vary between compilers, precompiled headers have been shown to be +highly effective at speeding up program compilation on systems with very large +system headers (e.g., Mac OS/X).

+ +

Generating a PCH File

+ +

To generate a PCH file using Clang, one invokes Clang with +the -x <language>-header option. This mirrors the +interface in GCC for generating PCH files:

+ +
+  $ gcc -x c-header test.h -o test.h.gch
+  $ clang -x c-header test.h -o test.h.pch
+
+ +

Using a PCH File

+ +

A PCH file can then be used as a prefix header when a +-include option is passed to clang:

+ +
+  $ clang -include test.h test.c -o test
+
+ +

The clang driver will first check if a PCH file for test.h +is available; if so, the contents of test.h (and the files it includes) +will be processed from the PCH file. Otherwise, Clang falls back to +directly processing the content of test.h. This mirrors the behavior of +GCC.

+ +

NOTE: Clang does not automatically use PCH files +for headers that are directly included within a source file. For example:

+ +
+  $ clang -x c-header test.h -o test.h.pch
+  $ cat test.c
+  #include "test.h"
+  $ clang test.c -o test
+
+ +

In this example, clang will not automatically use the PCH file for +test.h since test.h was included directly in the source file +and not specified on the command line using -include.

+ +

Relocatable PCH Files

+

It is sometimes necessary to build a precompiled header from headers that +are not yet in their final, installed locations. For example, one might build a +precompiled header within the build tree that is then meant to be installed +alongside the headers. Clang permits the creation of "relocatable" precompiled +headers, which are built with a given path (into the build directory) and can +later be used from an installed location.

+ +

To build a relocatable precompiled header, place your headers into a +subdirectory whose structure mimics the installed location. For example, if you +want to build a precompiled header for the header mylib.h that +will be installed into /usr/include, create a subdirectory +build/usr/include and place the header mylib.h into +that subdirectory. If mylib.h depends on other headers, then +they can be stored within build/usr/include in a way that mimics +the installed location.

+ +

Building a relocatable precompiled header requires two additional arguments. +First, pass the --relocatable-pch flag to indicate that the +resulting PCH file should be relocatable. Second, pass +-isysroot /path/to/build, which makes all includes for your +library relative to the build directory. For example:

+ +
+  # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
+
+ +

When loading the relocatable PCH file, the various headers used in the PCH +file are found from the system header root. For example, mylib.h +can be found in /usr/include/mylib.h. If the headers are installed +in some other system root, the -isysroot option can be used provide +a different system root from which the headers will be based. For example, +-isysroot /Developer/SDKs/MacOSX10.4u.sdk will look for +mylib.h in +/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h.

+ +

Relocatable precompiled headers are intended to be used in a limited number +of cases where the compilation environment is tightly controlled and the +precompiled header cannot be generated after headers have been installed. +Relocatable precompiled headers also have some performance impact, because +the difference in location between the header locations at PCH build time vs. +at the time of PCH use requires one of the PCH optimizations, +stat() caching, to be disabled. However, this change is only +likely to affect PCH files that reference a large number of headers.

+ + +

Controlling Code Generation

+ + +

Clang provides a number of ways to control code generation. The options are listed below.

+ + +
+
-fcatch-undefined-behavior: Turn +on runtime code generation to check for undefined behavior.
+ +
This option, which defaults to off, controls whether or not Clang +adds runtime checks for undefined runtime behavior. If a check fails, +__builtin_trap() is used to indicate failure. +The checks are: +
    +
  • Subscripting where the static type of one operand is a variable + which is decayed from an array type and the other operand is + greater than the size of the array or less than zero.
  • +
  • Shift operators where the amount shifted is greater or equal to the + promoted bit-width of the left-hand-side or less than zero.
  • +
  • If control flow reaches __builtin_unreachable. +
  • When llvm implements more __builtin_object_size support, reads and + writes for objects that __builtin_object_size indicates we aren't + accessing valid memory. Bit-fields and vectors are not yet checked. +
+
+ +
-f[no-]address-sanitizer: +Turn on AddressSanitizer, +a memory error detector. + +
-f[no-]thread-sanitizer: +Turn on ThreadSanitizer, an experimental data race detector. +Not ready for widespread use. + +
-fno-assume-sane-operator-new: +Don't assume that the C++'s new operator is sane.
+
This option tells the compiler to do not assume that C++'s global new +operator will always return a pointer that does not +alias any other pointer when the function returns.
+ +
-ftrap-function=[name]: Instruct code +generator to emit a function call to the specified function name for +__builtin_trap().
+ +
LLVM code generator translates __builtin_trap() to a trap +instruction if it is supported by the target ISA. Otherwise, the builtin is +translated into a call to abort. If this option is set, then the code +generator will always lower the builtin to a call to the specified function +regardless of whether the target ISA has a trap instruction. This option is +useful for environments (e.g. deeply embedded) where a trap cannot be properly +handled, or when some custom behavior is desired.
+
+ + +

C Language Features

+ + +

The support for standard C in clang is feature-complete except for the C99 +floating-point pragmas.

+ + +

Extensions supported by clang

+ + +

See clang language extensions.

+ + +

Differences between various standard modes

+ + +

clang supports the -std option, which changes what language mode clang uses. +The supported modes for C are c89, gnu89, c94, c99, gnu99 and various aliases +for those modes. If no -std option is specified, clang defaults to gnu99 mode. +

+ +

Differences between all c* and gnu* modes:

+
    +
  • c* modes define "__STRICT_ANSI__".
  • +
  • Target-specific defines not prefixed by underscores, like "linux", are +defined in gnu* modes.
  • +
  • Trigraphs default to being off in gnu* modes; they can be enabled by the +-trigraphs option.
  • +
  • The parser recognizes "asm" and "typeof" as keywords in gnu* modes; the +variants "__asm__" and "__typeof__" are recognized in all modes.
  • +
  • The Apple "blocks" extension is recognized by default in gnu* modes +on some platforms; it can be enabled in any mode with the "-fblocks" +option.
  • +
  • Arrays that are VLA's according to the standard, but which can be constant + folded by the frontend are treated as fixed size arrays. This occurs for + things like "int X[(1, 2)];", which is technically a VLA. c* modes are + strictly compliant and treat these as VLAs.
  • +
+ +

Differences between *89 and *99 modes:

+
    +
  • The *99 modes default to implementing "inline" as specified in C99, while +the *89 modes implement the GNU version. This can be overridden for individual +functions with the __gnu_inline__ attribute.
  • +
  • Digraphs are not recognized in c89 mode.
  • +
  • The scope of names defined inside a "for", "if", "switch", "while", or "do" +statement is different. (example: "if ((struct x {int x;}*)0) {}".)
  • +
  • __STDC_VERSION__ is not defined in *89 modes.
  • +
  • "inline" is not recognized as a keyword in c89 mode.
  • +
  • "restrict" is not recognized as a keyword in *89 modes.
  • +
  • Commas are allowed in integer constant expressions in *99 modes.
  • +
  • Arrays which are not lvalues are not implicitly promoted to pointers in +*89 modes.
  • +
  • Some warnings are different.
  • +
+ +

c94 mode is identical to c89 mode except that digraphs are enabled in +c94 mode (FIXME: And __STDC_VERSION__ should be defined!).

+ + +

GCC extensions not implemented yet

+ + +

clang tries to be compatible with gcc as much as possible, but some gcc +extensions are not implemented yet:

+ +
    + +
  • clang does not support #pragma weak +(bug 3679). Due to +the uses described in the bug, this is likely to be implemented at some +point, at least partially.
  • + +
  • clang does not support decimal floating point types (_Decimal32 and +friends) or fixed-point types (_Fract and friends); nobody has expressed +interest in these features yet, so it's hard to say when they will be +implemented.
  • + +
  • clang does not support nested functions; this is a complex feature which +is infrequently used, so it is unlikely to be implemented anytime soon.
  • + +
  • clang does not support global register variables, this is unlikely +to be implemented soon because it requires additional LLVM backend support. +
  • + +
  • clang does not support static initialization of flexible array +members. This appears to be a rarely used extension, but could be +implemented pending user demand.
  • + +
  • clang does not support __builtin_va_arg_pack/__builtin_va_arg_pack_len. +This is used rarely, but in some potentially interesting places, like the +glibc headers, so it may be implemented pending user demand. Note that +because clang pretends to be like GCC 4.2, and this extension was introduced +in 4.3, the glibc headers will not try to use this extension with clang at +the moment.
  • + +
  • clang does not support the gcc extension for forward-declaring function +parameters; this has not showed up in any real-world code yet, though, so it +might never be implemented.
  • + +
+ +

This is not a complete list; if you find an unsupported extension +missing from this list, please send an e-mail to cfe-dev. This list +currently excludes C++; see C++ Language Features. +Also, this list does not include bugs in mostly-implemented features; please +see the +bug tracker for known existing bugs (FIXME: Is there a section for +bug-reporting guidelines somewhere?).

+ + +

Intentionally unsupported GCC extensions

+ + +
    + +
  • clang does not support the gcc extension that allows variable-length arrays +in structures. This is for a few reasons: one, it is tricky +to implement, two, the extension is completely undocumented, and three, the +extension appears to be rarely used. Note that clang does support +flexible array members (arrays with a zero or unspecified size at the end of +a structure).
  • + +
  • clang does not have an equivalent to gcc's "fold"; this means that +clang doesn't accept some constructs gcc might accept in contexts where a +constant expression is required, like "x-x" where x is a variable.
  • + +
  • clang does not support __builtin_apply and friends; this extension is +extremely obscure and difficult to implement reliably.
  • + +
+ + +

Microsoft extensions

+ + +

clang has some experimental support for extensions from +Microsoft Visual C++; to enable it, use the -fms-extensions command-line +option. This is the default for Windows targets. Note that the +support is incomplete; enabling Microsoft extensions will silently drop +certain constructs (including __declspec and Microsoft-style asm statements). +

+ +
    +
  • clang allows setting _MSC_VER with -fmsc-version=. It defaults to 1300 which +is the same as Visual C/C++ 2003. Any number is supported and can greatly affect +what Windows SDK and c++stdlib headers clang can compile. This option will be +removed when clang supports the full set of MS extensions required for these +headers.
  • + +
  • clang does not support the Microsoft extension where anonymous +record members can be declared using user defined typedefs.
  • + +
  • clang supports the Microsoft "#pragma pack" feature for +controlling record layout. GCC also contains support for this feature, +however where MSVC and GCC are incompatible clang follows the MSVC +definition.
  • +
+ + +

C++ Language Features

+ + +

clang fully implements all of standard C++98 except for exported templates +(which were removed in C++11), and +many C++11 features are also +implemented.

+ + +

Controlling implementation limits

+ + +

-fconstexpr-depth=N: Sets the limit for recursive constexpr function +invocations to N. The default is 512.

+ +

-ftemplate-depth=N: Sets the limit for recursively nested template +instantiations to N. The default is 1024.

+ + +

Target-Specific Features and Limitations

+ + + + +

CPU Architectures Features and Limitations

+ + + +

X86

+ + +

The support for X86 (both 32-bit and 64-bit) is considered stable on Darwin +(Mac OS/X), Linux, FreeBSD, and Dragonfly BSD: it has been tested to correctly +compile many large C, C++, Objective-C, and Objective-C++ codebases.

+ +

On x86_64-mingw32, passing i128(by value) is incompatible to Microsoft x64 +calling conversion. You might need to tweak WinX86_64ABIInfo::classify() +in lib/CodeGen/TargetInfo.cpp.

+ + +

ARM

+ + +

The support for ARM (specifically ARMv6 and ARMv7) is considered stable on +Darwin (iOS): it has been tested to correctly compile many large C, C++, +Objective-C, and Objective-C++ codebases. Clang only supports a limited number +of ARM architectures. It does not yet fully support ARMv5, for example.

+ + +

Other platforms

+ +clang currently contains some support for PPC and Sparc; however, significant +pieces of code generation are still missing, and they haven't undergone +significant testing. + +

clang contains limited support for the MSP430 embedded processor, but both +the clang support and the LLVM backend support are highly experimental. + +

Other platforms are completely unsupported at the moment. Adding the +minimal support needed for parsing and semantic analysis on a new platform +is quite easy; see lib/Basic/Targets.cpp in the clang source tree. This level +of support is also sufficient for conversion to LLVM IR for simple programs. +Proper support for conversion to LLVM IR requires adding code to +lib/CodeGen/CGCall.cpp at the moment; this is likely to change soon, though. +Generating assembly requires a suitable LLVM backend. + + +

Operating System Features and Limitations

+ + + +

Darwin (Mac OS/X)

+ + +

No __thread support, 64-bit ObjC support requires SL tools.

+ + +

Windows

+ + +

Experimental supports are on Cygming.

+ +
Cygwin
+ +

Clang works on Cygwin-1.7.

+ +
MinGW32
+ +

Clang works on some mingw32 distributions. +Clang assumes directories as below;

+ +
    +
  • C:/mingw/include
  • +
  • C:/mingw/lib
  • +
  • C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++
  • +
+ +

On MSYS, a few tests might fail.

+ +
MinGW-w64
+ +

For 32-bit (i686-w64-mingw32), and 64-bit (x86_64-w64-mingw32), Clang assumes as below;

+ +

    +
  • GCC versions 4.5.0 to 4.5.3, 4.6.0 to 4.6.2, or 4.7.0 (for the C++ header search path)
  • +
  • some_directory/bin/gcc.exe
  • +
  • some_directory/bin/clang.exe
  • +
  • some_directory/bin/clang++.exe
  • +
  • some_directory/bin/../include/c++/GCC_version
  • +
  • some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32
  • +
  • some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32
  • +
  • some_directory/bin/../include/c++/GCC_version/backward
  • +
  • some_directory/bin/../x86_64-w64-mingw32/include
  • +
  • some_directory/bin/../i686-w64-mingw32/include
  • +
  • some_directory/bin/../include
  • +
+ +

This directory layout is standard for any toolchain you will find on the official MinGW-w64 website. + +

Clang expects the GCC executable "gcc.exe" compiled for i686-w64-mingw32 (or x86_64-w64-mingw32) to be present on PATH.

+ +

Some tests might fail +on x86_64-w64-mingw32.

+ +
+ + diff --git a/cpp/llvm/tools/clang/docs/doxygen.cfg.in b/cpp/llvm/tools/clang/docs/doxygen.cfg.in new file mode 100644 index 00000000..ed9ffcb8 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/doxygen.cfg.in @@ -0,0 +1,1230 @@ +# Doxyfile 1.4.4 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = clang + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = @PACKAGE_VERSION@ + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = @abs_builddir@/doxygen + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, +# Dutch, Finnish, French, German, Greek, Hungarian, Italian, Japanese, +# Japanese-en (Japanese with English messages), Korean, Korean-en, Norwegian, +# Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, +# Swedish, and Ukrainian. + +OUTPUT_LANGUAGE = English + +# This tag can be used to specify the encoding used in the generated output. +# The encoding is not always determined by the language that is chosen, +# but also whether or not the output is meant for Windows or non-Windows users. +# In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES +# forces the Windows encoding (this is the default for the Windows binary), +# whereas setting the tag to NO uses a Unix-style encoding (the default for +# all platforms other than Windows). + +USE_WINDOWS_ENCODING = NO + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = NO + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = ../.. + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like the Qt-style comments (thus requiring an +# explicit @brief command for a brief description. + +JAVADOC_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the DETAILS_AT_TOP tag is set to YES then Doxygen +# will output the detailed description near the top, like JavaDoc. +# If set to NO, the detailed description appears after the member +# documentation. + +DETAILS_AT_TOP = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +#SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 2 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources +# only. Doxygen will then generate output that is more tailored for Java. +# For instance, namespaces will be presented as packages, qualified scopes +# will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is YES. + +SHOW_DIRECTORIES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from the +# version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the progam writes to standard output +# is used as the file version. See the manual for examples. + +#FILE_VERSION_FILTER = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = NO + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = NO + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +#WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = @abs_srcdir@/../include \ + @abs_srcdir@/../lib \ + @abs_srcdir@/doxygen.intro + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = @abs_srcdir@/../examples + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = YES + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = @abs_srcdir@/img + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = NO + +# If the REFERENCED_BY_RELATION tag is set to YES (the default) +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES (the default) +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +#USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = YES + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 4 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = clang:: + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = @abs_srcdir@/doxygen.header + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = @abs_srcdir@/doxygen.footer + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = @abs_srcdir@/doxygen.css + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be +# generated containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, +# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are +# probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = letter + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_PREDEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = ../include + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = YES + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = NO + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = YES + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +#GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a call dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +#DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = @DOT@ + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_WIDTH = 1024 + +# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_HEIGHT = 1024 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that a graph may be further truncated if the graph's +# image dimensions are not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH +# and MAX_DOT_GRAPH_HEIGHT). If 0 is used for the depth value (the default), +# the graph is not depth-constrained. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, which results in a white background. +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). + +#DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +#DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- + +# The SEARCHENGINE tag specifies whether or not a search engine should be +# used. If set to NO the values of all tags below this one will be ignored. + +SEARCHENGINE = NO diff --git a/cpp/llvm/tools/clang/docs/doxygen.css b/cpp/llvm/tools/clang/docs/doxygen.css new file mode 100644 index 00000000..9780b98d --- /dev/null +++ b/cpp/llvm/tools/clang/docs/doxygen.css @@ -0,0 +1,408 @@ +BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { + font-family: Verdana,Geneva,Arial,Helvetica,sans-serif; +} +BODY,TD { + font-size: 90%; +} +H1 { + text-align: center; + font-size: 140%; + font-weight: bold; +} +H2 { + font-size: 120%; + font-style: italic; +} +H3 { + font-size: 100%; +} +CAPTION { font-weight: bold } +DIV.qindex { + width: 100%; + background-color: #eeeeff; + border: 1px solid #b0b0b0; + text-align: center; + margin: 2px; + padding: 2px; + line-height: 140%; +} +DIV.nav { + width: 100%; + background-color: #eeeeff; + border: 1px solid #b0b0b0; + text-align: center; + margin: 2px; + padding: 2px; + line-height: 140%; +} +DIV.navtab { + background-color: #eeeeff; + border: 1px solid #b0b0b0; + text-align: center; + margin: 2px; + margin-right: 15px; + padding: 2px; +} +TD.navtab { + font-size: 70%; +} +A.qindex { + text-decoration: none; + font-weight: bold; + color: #1A419D; +} +A.qindex:visited { + text-decoration: none; + font-weight: bold; + color: #1A419D +} +A.qindex:hover { + text-decoration: none; + background-color: #ddddff; +} +A.qindexHL { + text-decoration: none; + font-weight: bold; + background-color: #6666cc; + color: #ffffff; + border: 1px double #9295C2; +} +A.qindexHL:hover { + text-decoration: none; + background-color: #6666cc; + color: #ffffff; +} +A.qindexHL:visited { + text-decoration: none; background-color: #6666cc; color: #ffffff } +A.el { text-decoration: none; font-weight: bold } +A.elRef { font-weight: bold } +A.code:link { text-decoration: none; font-weight: normal; color: #0000FF} +A.code:visited { text-decoration: none; font-weight: normal; color: #0000FF} +A.codeRef:link { font-weight: normal; color: #0000FF} +A.codeRef:visited { font-weight: normal; color: #0000FF} +A:hover { text-decoration: none; background-color: #f2f2ff } +DL.el { margin-left: -1cm } +.fragment { + font-family: Fixed, monospace; + font-size: 95%; +} +PRE.fragment { + border: 1px solid #CCCCCC; + background-color: #f5f5f5; + margin-top: 4px; + margin-bottom: 4px; + margin-left: 2px; + margin-right: 8px; + padding-left: 6px; + padding-right: 6px; + padding-top: 4px; + padding-bottom: 4px; +} +DIV.ah { background-color: black; font-weight: bold; color: #ffffff; margin-bottom: 3px; margin-top: 3px } +TD.md { background-color: #F4F4FB; font-weight: bold; } +TD.mdPrefix { + background-color: #F4F4FB; + color: #606060; + font-size: 80%; +} +TD.mdname1 { background-color: #F4F4FB; font-weight: bold; color: #602020; } +TD.mdname { background-color: #F4F4FB; font-weight: bold; color: #602020; width: 600px; } +DIV.groupHeader { + margin-left: 16px; + margin-top: 12px; + margin-bottom: 6px; + font-weight: bold; +} +DIV.groupText { margin-left: 16px; font-style: italic; font-size: 90% } +BODY { + background: white; + color: black; + margin-right: 20px; + margin-left: 20px; +} +TD.indexkey { + background-color: #eeeeff; + font-weight: bold; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; +} +TD.indexvalue { + background-color: #eeeeff; + font-style: italic; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; +} +TR.memlist { + background-color: #f0f0f0; +} +P.formulaDsp { text-align: center; } +IMG.formulaDsp { } +IMG.formulaInl { vertical-align: middle; } +SPAN.keyword { color: #008000 } +SPAN.keywordtype { color: #604020 } +SPAN.keywordflow { color: #e08000 } +SPAN.comment { color: #800000 } +SPAN.preprocessor { color: #806020 } +SPAN.stringliteral { color: #002080 } +SPAN.charliteral { color: #008080 } +.mdTable { + border: 1px solid #868686; + background-color: #F4F4FB; +} +.mdRow { + padding: 8px 10px; +} +.mdescLeft { + padding: 0px 8px 4px 8px; + font-size: 80%; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; +} +.mdescRight { + padding: 0px 8px 4px 8px; + font-size: 80%; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; +} +.memItemLeft { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memItemRight { + padding: 1px 8px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memTemplItemLeft { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: none; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memTemplItemRight { + padding: 1px 8px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: none; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memTemplParams { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + color: #606060; + background-color: #FAFAFA; + font-size: 80%; +} +.search { color: #003399; + font-weight: bold; +} +FORM.search { + margin-bottom: 0px; + margin-top: 0px; +} +INPUT.search { font-size: 75%; + color: #000080; + font-weight: normal; + background-color: #eeeeff; +} +TD.tiny { font-size: 75%; +} +a { + color: #252E78; +} +a:visited { + color: #3D2185; +} +.dirtab { padding: 4px; + border-collapse: collapse; + border: 1px solid #b0b0b0; +} +TH.dirtab { background: #eeeeff; + font-weight: bold; +} +HR { height: 1px; + border: none; + border-top: 1px solid black; +} + +/* + * LLVM Modifications. + * Note: Everything above here is generated with "doxygen -w htlm" command. See + * "doxygen --help" for details. What follows are CSS overrides for LLVM + * specific formatting. We want to keep the above so it can be replaced with + * subsequent doxygen upgrades. + */ + +.footer { + font-size: 80%; + font-weight: bold; + text-align: center; + vertical-align: middle; +} +.title { + font-size: 25pt; + color: black; background: url("http://llvm.org/img/lines.gif"); + font-weight: bold; + border-width: 1px; + border-style: solid none solid none; + text-align: center; + vertical-align: middle; + padding-left: 8pt; + padding-top: 1px; + padding-bottom: 2px +} +A:link { + cursor: pointer; + text-decoration: none; + font-weight: bolder; +} +A:visited { + cursor: pointer; + text-decoration: underline; + font-weight: bolder; +} +A:hover { + cursor: pointer; + text-decoration: underline; + font-weight: bolder; +} +A:active { + cursor: pointer; + text-decoration: underline; + font-weight: bolder; + font-style: italic; +} +H1 { + text-align: center; + font-size: 140%; + font-weight: bold; +} +H2 { + font-size: 120%; + font-style: italic; +} +H3 { + font-size: 100%; +} + +H2, H3 { + border-bottom: 2px solid; + margin-top: 2em; +} + +A.qindex {} +A.qindexRef {} +A.el { text-decoration: none; font-weight: bold } +A.elRef { font-weight: bold } +A.code { text-decoration: none; font-weight: normal; color: #4444ee } +A.codeRef { font-weight: normal; color: #4444ee } + +div.memitem { + border: 1px solid #999999; + margin-top: 1.0em; + margin-bottom: 1.0em; + -webkit-border-radius: 0.5em; + -webkit-box-shadow: 3px 3px 6px #777777; + -moz-border-radius: 0.5em; + -moz-box-shadow: black 3px 3px 3px; +} + +div.memproto { + background-color: #E3E4E5; + padding: 0.25em 0.5em; + -webkit-border-top-left-radius: 0.5em; + -webkit-border-top-right-radius: 0.5em; + -moz-border-radius-topleft: 0.5em; + -moz-border-radius-topright: 0.5em; +} + +div.memdoc { + padding-left: 1em; + padding-right: 1em; +} diff --git a/cpp/llvm/tools/clang/docs/doxygen.footer b/cpp/llvm/tools/clang/docs/doxygen.footer new file mode 100644 index 00000000..524e9a2b --- /dev/null +++ b/cpp/llvm/tools/clang/docs/doxygen.footer @@ -0,0 +1,10 @@ +
+ + + + + diff --git a/cpp/llvm/tools/clang/docs/doxygen.header b/cpp/llvm/tools/clang/docs/doxygen.header new file mode 100644 index 00000000..bea51371 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/doxygen.header @@ -0,0 +1,9 @@ + + + + + +clang: $title + + +

clang API Documentation

diff --git a/cpp/llvm/tools/clang/docs/doxygen.intro b/cpp/llvm/tools/clang/docs/doxygen.intro new file mode 100644 index 00000000..accab72b --- /dev/null +++ b/cpp/llvm/tools/clang/docs/doxygen.intro @@ -0,0 +1,15 @@ +/// @mainpage clang +/// +/// @section main_intro Introduction +/// Welcome to the clang project. +/// +/// This documentation describes the @b internal software that makes +/// up clang, not the @b external use of clang. There are no instructions +/// here on how to use clang, only the APIs that make up the software. For +/// usage instructions, please see the programmer's guide or reference +/// manual. +/// +/// @section main_caveat Caveat +/// This documentation is generated directly from the source code with doxygen. +/// Since clang is constantly under active development, what you're about to +/// read is out of date! diff --git a/cpp/llvm/tools/clang/docs/tools/Makefile b/cpp/llvm/tools/clang/docs/tools/Makefile new file mode 100644 index 00000000..5521d6b7 --- /dev/null +++ b/cpp/llvm/tools/clang/docs/tools/Makefile @@ -0,0 +1,116 @@ +##===- docs/tools/Makefile ---------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +ifdef BUILD_FOR_WEBSITE + +# FIXME: This was copied from the CommandGuide makefile. Figure out +# how to get this stuff on the website. + +# This special case is for keeping the CommandGuide on the LLVM web site +# up to date automatically as the documents are checked in. It must build +# the POD files to HTML only and keep them in the src directories. It must also +# build in an unconfigured tree, hence the ifdef. To use this, run +# make -s BUILD_FOR_WEBSITE=1 inside the cvs commit script. +SRC_DOC_DIR= +DST_HTML_DIR=html/ +DST_MAN_DIR=man/man1/ +DST_PS_DIR=ps/ +CLANG_VERSION := trunk + +# If we are in BUILD_FOR_WEBSITE mode, default to the all target. +all:: html man ps + +clean: + rm -f pod2htm*.*~~ $(HTML) $(MAN) $(PS) + +# To create other directories, as needed, and timestamp their creation +%/.dir: + -mkdir $* > /dev/null + date > $@ + +else + +# Otherwise, if not in BUILD_FOR_WEBSITE mode, use the project info. +CLANG_LEVEL := ../.. +include $(CLANG_LEVEL)/Makefile + +CLANG_VERSION := $(word 3,$(shell grep "CLANG_VERSION " \ + $(PROJ_OBJ_DIR)/$(CLANG_LEVEL)/include/clang/Basic/Version.inc)) + +SRC_DOC_DIR=$(PROJ_SRC_DIR)/ +DST_HTML_DIR=$(PROJ_OBJ_DIR)/ +DST_MAN_DIR=$(PROJ_OBJ_DIR)/ +DST_PS_DIR=$(PROJ_OBJ_DIR)/ + +endif + + +POD := $(wildcard $(SRC_DOC_DIR)*.pod) +HTML := $(patsubst $(SRC_DOC_DIR)%.pod, $(DST_HTML_DIR)%.html, $(POD)) +MAN := $(patsubst $(SRC_DOC_DIR)%.pod, $(DST_MAN_DIR)%.1, $(POD)) +PS := $(patsubst $(SRC_DOC_DIR)%.pod, $(DST_PS_DIR)%.ps, $(POD)) + +ifdef ONLY_MAN_DOCS +INSTALL_TARGETS := install-man +else +INSTALL_TARGETS := install-html install-man install-ps +endif + +.SUFFIXES: +.SUFFIXES: .html .pod .1 .ps + +$(DST_HTML_DIR)%.html: %.pod $(DST_HTML_DIR)/.dir + pod2html --css=manpage.css --htmlroot=. \ + --podpath=. --infile=$< --outfile=$@ --title=$* + +$(DST_MAN_DIR)%.1: %.pod $(DST_MAN_DIR)/.dir + pod2man --release "clang $(CLANG_VERSION)" --center="Clang Tools Documentation" $< $@ + +$(DST_PS_DIR)%.ps: $(DST_MAN_DIR)%.1 $(DST_PS_DIR)/.dir + groff -Tps -man $< > $@ + + +html: $(HTML) +man: $(MAN) +ps: $(PS) + +EXTRA_DIST := $(POD) + +clean-local:: + $(Verb) $(RM) -f pod2htm*.*~~ $(HTML) $(MAN) $(PS) + +HTML_DIR := $(DESTDIR)$(PROJ_docsdir)/html/clang +MAN_DIR := $(DESTDIR)$(PROJ_mandir)/man1 +PS_DIR := $(DESTDIR)$(PROJ_docsdir)/ps + +install-html:: $(HTML) + $(Echo) Installing HTML Clang Tools Documentation + $(Verb) $(MKDIR) $(HTML_DIR) + $(Verb) $(DataInstall) $(HTML) $(HTML_DIR) + $(Verb) $(DataInstall) $(PROJ_SRC_DIR)/manpage.css $(HTML_DIR) + +install-man:: $(MAN) + $(Echo) Installing MAN Clang Tools Documentation + $(Verb) $(MKDIR) $(MAN_DIR) + $(Verb) $(DataInstall) $(MAN) $(MAN_DIR) + +install-ps:: $(PS) + $(Echo) Installing PS Clang Tools Documentation + $(Verb) $(MKDIR) $(PS_DIR) + $(Verb) $(DataInstall) $(PS) $(PS_DIR) + +install-local:: $(INSTALL_TARGETS) + +uninstall-local:: + $(Echo) Uninstalling Clang Tools Documentation + $(Verb) $(RM) -rf $(HTML_DIR) $(MAN_DIR) $(PS_DIR) + +printvars:: + $(Echo) "POD : " '$(POD)' + $(Echo) "HTML : " '$(HTML)' diff --git a/cpp/llvm/tools/clang/docs/tools/clang.pod b/cpp/llvm/tools/clang/docs/tools/clang.pod new file mode 100644 index 00000000..8f61568e --- /dev/null +++ b/cpp/llvm/tools/clang/docs/tools/clang.pod @@ -0,0 +1,560 @@ +=pod + +=head1 NAME + +clang - the Clang C, C++, and Objective-C compiler + +=head1 SYNOPSIS + +B [B<-c>|B<-S>|B<-E>] B<-std=>I B<-g> + [B<-O0>|B<-O1>|B<-O2>|B<-Os>|B<-Oz>|B<-O3>|B<-O4>] + B<-W>I B<-pedantic> + B<-I>I B<-L>I + B<-D>I + B<-f>I + B<-m>I + B<-o> I + B<-stdlib=>I + I + +=head1 DESCRIPTION + +B is a C, C++, and Objective-C compiler which encompasses preprocessing, +parsing, optimization, code generation, assembly, and linking. Depending on +which high-level mode setting is passed, Clang will stop before doing a full +link. While Clang is highly integrated, it is important to understand the +stages of compilation, to understand how to invoke it. These stages are: + +=over + +=item B + +The B executable is actually a small driver which controls the overall +execution of other tools such as the compiler, assembler and linker. Typically +you do not need to interact with the driver, but you transparently use it to run +the other tools. + +=item B + +This stage handles tokenization of the input source file, macro expansion, +#include expansion and handling of other preprocessor directives. The output of +this stage is typically called a ".i" (for C), ".ii" (for C++), ".mi" (for +Objective-C) , or ".mii" (for Objective-C++) file. + +=item B + +This stage parses the input file, translating preprocessor tokens into a parse +tree. Once in the form of a parser tree, it applies semantic analysis to compute +types for expressions as well and determine whether the code is well formed. This +stage is responsible for generating most of the compiler warnings as well as +parse errors. The output of this stage is an "Abstract Syntax Tree" (AST). + +=item B + +This stage translates an AST into low-level intermediate code (known as "LLVM +IR") and ultimately to machine code. This phase is responsible for optimizing +the generated code and handling target-specific code generation. The output of +this stage is typically called a ".s" file or "assembly" file. + +Clang also supports the use of an integrated assembler, in which the code +generator produces object files directly. This avoids the overhead of generating +the ".s" file and of calling the target assembler. + +=item B + +This stage runs the target assembler to translate the output of the compiler +into a target object file. The output of this stage is typically called a ".o" +file or "object" file. + +=item B + +This stage runs the target linker to merge multiple object files into an +executable or dynamic library. The output of this stage is typically called an +"a.out", ".dylib" or ".so" file. + +=back + +The Clang compiler supports a large number of options to control each of these +stages. In addition to compilation of code, Clang also supports other tools: + +B + +The Clang Static Analyzer is a tool that scans source code to try to find bugs +through code analysis. This tool uses many parts of Clang and is built into the +same driver. + + +=head1 OPTIONS + +=head2 Stage Selection Options + +=over + +=item B<-E> + +Run the preprocessor stage. + +=item B<-fsyntax-only> + +Run the preprocessor, parser and type checking stages. + +=item B<-S> + +Run the previous stages as well as LLVM generation and optimization stages and +target-specific code generation, producing an assembly file. + +=item B<-c> + +Run all of the above, plus the assembler, generating a target ".o" object file. + +=item B + +If no stage selection option is specified, all stages above are run, and the +linker is run to combine the results into an executable or shared library. + +=item B<--analyze> + +Run the Clang Static Analyzer. + +=back + + + +=head2 Language Selection and Mode Options + +=over + +=item B<-x> I + +Treat subsequent input files as having type I. + +=item B<-std>=I + +Specify the language standard to compile for. + +=item B<-stdlib>=I + +Specify the C++ standard library to use; supported options are libstdc++ and +libc++. + +=item B<-ansi> + +Same as B<-std=c89>. + +=item B<-ObjC++> + +Treat source input files as Objective-C++ inputs. + +=item B<-ObjC> + +Treat source input files as Objective-C inputs. + +=item B<-trigraphs> + +Enable trigraphs. + +=item B<-ffreestanding> + +Indicate that the file should be compiled for a freestanding, not a hosted, +environment. + +=item B<-fno-builtin> + +Disable special handling and optimizations of builtin functions like strlen and +malloc. + +=item B<-fmath-errno> + +Indicate that math functions should be treated as updating errno. + +=item B<-fpascal-strings> + +Enable support for Pascal-style strings with "\pfoo". + +=item B<-fms-extensions> + +Enable support for Microsoft extensions. + +=item B<-fmsc-version=> + +Set _MSC_VER. Defaults to 1300 on Windows. Not set otherwise. + +=item B<-fborland-extensions> + +Enable support for Borland extensions. + +=item B<-fwritable-strings> + +Make all string literals default to writable. This disables uniquing of +strings and other optimizations. + +=item B<-flax-vector-conversions> + +Allow loose type checking rules for implicit vector conversions. + +=item B<-fblocks> + +Enable the "Blocks" language feature. + +=item B<-fobjc-gc-only> + +Indicate that Objective-C code should be compiled in GC-only mode, which only +works when Objective-C Garbage Collection is enabled. + +=item B<-fobjc-gc> + +Indicate that Objective-C code should be compiled in hybrid-GC mode, which works +with both GC and non-GC mode. + +=item B<-fobjc-abi-version>=I + +Select the Objective-C ABI version to use. Available versions are 1 (legacy +"fragile" ABI), 2 (non-fragile ABI 1), and 3 (non-fragile ABI 2). + +=item B<-fobjc-nonfragile-abi-version>=I + +Select the Objective-C non-fragile ABI version to use by default. This will only +be used as the Objective-C ABI when the non-fragile ABI is enabled (either via +-fobjc-nonfragile-abi, or because it is the platform default). + +=item B<-fobjc-nonfragile-abi> + +Enable use of the Objective-C non-fragile ABI. On platforms for which this is +the default ABI, it can be disabled with B<-fno-objc-nonfragile-abi>. + +=back + + + +=head2 Target Selection Options + +Clang fully supports cross compilation as an inherent part of its design. +Depending on how your version of Clang is configured, it may have support for +a number of cross compilers, or may only support a native target. + +=over + +=item B<-arch> I + +Specify the architecture to build for. + +=item B<-mmacosx-version-min>=I + +When building for Mac OS/X, specify the minimum version supported by your +application. + +=item B<-miphoneos-version-min> + +When building for iPhone OS, specify the minimum version supported by your +application. + + +=item B<-march>=I + +Specify that Clang should generate code for a specific processor family member +and later. For example, if you specify -march=i486, the compiler is allowed to +generate instructions that are valid on i486 and later processors, but which +may not exist on earlier ones. + +=back + + +=head2 Code Generation Options + +=over + +=item B<-O0> B<-O1> B<-O2> B<-Os> B<-Oz> B<-O3> B<-O4> + +Specify which optimization level to use. B<-O0> means "no optimization": this +level compiles the fastest and generates the most debuggable code. B<-O2> is a +moderate level of optimization which enables most optimizations. B<-Os> is like +B<-O2> with extra optimizations to reduce code size. B<-Oz> is like B<-Os> +(and thus B<-O2>), but reduces code size further. B<-O3> is like B<-O2>, +except that it enables optimizations that take longer to perform or that may +generate larger code (in an attempt to make the program run faster). On +supported platforms, B<-O4> enables link-time optimization; object files are +stored in the LLVM bitcode file format and whole program optimization is done at +link time. B<-O1> is somewhere between B<-O0> and B<-O2>. + +=item B<-g> + +Generate debug information. Note that Clang debug information works best at +B<-O0>. At higher optimization levels, only line number information is +currently available. + +=item B<-fexceptions> + +Enable generation of unwind information, this allows exceptions to be thrown +through Clang compiled stack frames. This is on by default in x86-64. + +=item B<-ftrapv> + +Generate code to catch integer overflow errors. Signed integer overflow is +undefined in C, with this flag, extra code is generated to detect this and abort +when it happens. + + +=item B<-fvisibility> + +This flag sets the default visibility level. + +=item B<-fcommon> + +This flag specifies that variables without initializers get common linkage. It +can be disabled with B<-fno-common>. + +=item B<-flto> B<-emit-llvm> + +Generate output files in LLVM formats, suitable for link time optimization. When +used with B<-S> this generates LLVM intermediate language assembly files, +otherwise this generates LLVM bitcode format object files (which may be passed +to the linker depending on the stage selection options). + +=cut + +##=item B<-fnext-runtime> B<-fobjc-nonfragile-abi> B<-fgnu-runtime> +##These options specify which Objective-C runtime the code generator should +##target. FIXME: we don't want people poking these generally. + +=pod + +=back + + +=head2 Driver Options + +=over + +=item B<-###> + +Print the commands to run for this compilation. + +=item B<--help> + +Display available options. + +=item B<-Qunused-arguments> + +Don't emit warning for unused driver arguments. + +=item B<-Wa,>I + +Pass the comma separated arguments in I to the assembler. + +=item B<-Wl,>I + +Pass the comma separated arguments in I to the linker. + +=item B<-Wp,>I + +Pass the comma separated arguments in I to the preprocessor. + +=item B<-Xanalyzer> I + +Pass I to the static analyzer. + +=item B<-Xassembler> I + +Pass I to the assembler. + +=item B<-Xlinker> I + +Pass I to the linker. + +=item B<-Xpreprocessor> I + +Pass I to the preprocessor. + +=item B<-o> I + +Write output to I. + +=item B<-print-file-name>=I + +Print the full library path of I. + +=item B<-print-libgcc-file-name> + +Print the library path for "libgcc.a". + +=item B<-print-prog-name>=I + +Print the full program path of I. + +=item B<-print-search-dirs> + +Print the paths used for finding libraries and programs. + +=item B<-save-temps> + +Save intermediate compilation results. + +=item B<-integrated-as> B<-no-integrated-as> + +Used to enable and disable, respectively, the use of the integrated +assembler. Whether the integrated assembler is on by default is target +dependent. + +=item B<-time> + +Time individual commands. + +=item B<-ftime-report> + +Print timing summary of each stage of compilation. + +=item B<-v> + +Show commands to run and use verbose output. + +=back + + +=head2 Diagnostics Options + +=over + +=item B<-fshow-column> +B<-fshow-source-location> +B<-fcaret-diagnostics> +B<-fdiagnostics-fixit-info> +B<-fdiagnostics-parseable-fixits> +B<-fdiagnostics-print-source-range-info> +B<-fprint-source-range-info> +B<-fdiagnostics-show-option> +B<-fmessage-length> + +These options control how Clang prints out information about diagnostics (errors +and warnings). Please see the Clang User's Manual for more information. + +=back + + +=head2 Preprocessor Options + +=over + +=item B<-D>I + +Adds an implicit #define into the predefines buffer which is read before the +source file is preprocessed. + +=item B<-U>I + +Adds an implicit #undef into the predefines buffer which is read before the +source file is preprocessed. + +=item B<-include> I + +Adds an implicit #include into the predefines buffer which is read before the +source file is preprocessed. + +=item B<-I>I + +Add the specified directory to the search path for include files. + +=item B<-F>I + +Add the specified directory to the search path for framework include files. + +=item B<-nostdinc> + +Do not search the standard system directories or compiler builtin directories +for include files. + +=item B<-nostdlibinc> + +Do not search the standard system directories for include files, but do search +compiler builtin include directories. + +=item B<-nobuiltininc> + +Do not search clang's builtin directory for include files. + +=cut + +## TODO, but do we really want people using this stuff? +#=item B<-idirafter>I +#=item B<-iquote>I +#=item B<-isystem>I +#=item B<-iprefix>I +#=item B<-iwithprefix>I +#=item B<-iwithprefixbefore>I +#=item B<-isysroot> + +=pod + + +=back + + + +=cut + +### TODO someday. +#=head2 Warning Control Options +#=over +#=back +#=head2 Code Generation and Optimization Options +#=over +#=back +#=head2 Assembler Options +#=over +#=back +#=head2 Linker Options +#=over +#=back +#=head2 Static Analyzer Options +#=over +#=back + +=pod + + +=head1 ENVIRONMENT + +=over + +=item B, B, B + +These environment variables are checked, in order, for the location to +write temporary files used during the compilation process. + +=item B + +If this environment variable is present, it is treated as a delimited +list of paths to be added to the default system include path list. The +delimiter is the platform dependent delimitor, as used in the I +environment variable. + +Empty components in the environment variable are ignored. + +=item B, B, B, +B + +These environment variables specify additional paths, as for CPATH, +which are only used when processing the appropriate language. + +=item B + +If -mmacosx-version-min is unspecified, the default deployment target +is read from this environment variable. This option only affects darwin +targets. + +=back + +=head1 BUGS + +To report bugs, please visit L. Most bug reports should +include preprocessed source files (use the B<-E> option) and the full output of +the compiler, along with information to reproduce. + +=head1 SEE ALSO + + as(1), ld(1) + +=head1 AUTHOR + +Maintained by the Clang / LLVM Team (L). + +=cut diff --git a/cpp/llvm/tools/clang/docs/tools/manpage.css b/cpp/llvm/tools/clang/docs/tools/manpage.css new file mode 100644 index 00000000..c922564d --- /dev/null +++ b/cpp/llvm/tools/clang/docs/tools/manpage.css @@ -0,0 +1,256 @@ +/* Based on http://www.perldoc.com/css/perldoc.css */ + +@import url("../llvm.css"); + +body { font-family: Arial,Helvetica; } + +blockquote { margin: 10pt; } + +h1, a { color: #336699; } + + +/*** Top menu style ****/ +.mmenuon { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #ff6600; font-size: 10pt; +} +.mmenuoff { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #ffffff; font-size: 10pt; +} +.cpyright { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #ffffff; font-size: xx-small; +} +.cpyrightText { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #ffffff; font-size: xx-small; +} +.sections { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: 11pt; +} +.dsections { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: 12pt; +} +.slink { + font-family: Arial,Helvetica; font-weight: normal; text-decoration: none; + color: #000000; font-size: 9pt; +} + +.slink2 { font-family: Arial,Helvetica; text-decoration: none; color: #336699; } + +.maintitle { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: 18pt; +} +.dblArrow { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: small; +} +.menuSec { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: small; +} + +.newstext { + font-family: Arial,Helvetica; font-size: small; +} + +.linkmenu { + font-family: Arial,Helvetica; color: #000000; font-weight: bold; + text-decoration: none; +} + +P { + font-family: Arial,Helvetica; +} + +PRE { + font-size: 10pt; +} +.quote { + font-family: Times; text-decoration: none; + color: #000000; font-size: 9pt; font-style: italic; +} +.smstd { font-family: Arial,Helvetica; color: #000000; font-size: x-small; } +.std { font-family: Arial,Helvetica; color: #000000; } +.meerkatTitle { + font-family: sans-serif; font-size: x-small; color: black; } + +.meerkatDescription { font-family: sans-serif; font-size: 10pt; color: black } +.meerkatCategory { + font-family: sans-serif; font-size: 9pt; font-weight: bold; font-style: italic; + color: brown; } +.meerkatChannel { + font-family: sans-serif; font-size: 9pt; font-style: italic; color: brown; } +.meerkatDate { font-family: sans-serif; font-size: xx-small; color: #336699; } + +.tocTitle { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #333333; font-size: 10pt; +} + +.toc-item { + font-family: Arial,Helvetica; font-weight: bold; + color: #336699; font-size: 10pt; text-decoration: underline; +} + +.perlVersion { + font-family: Arial,Helvetica; font-weight: bold; + color: #336699; font-size: 10pt; text-decoration: none; +} + +.podTitle { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #000000; +} + +.docTitle { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #000000; font-size: 10pt; +} +.dotDot { + font-family: Arial,Helvetica; font-weight: bold; + color: #000000; font-size: 9pt; +} + +.docSec { + font-family: Arial,Helvetica; font-weight: normal; + color: #333333; font-size: 9pt; +} +.docVersion { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: 10pt; +} + +.docSecs-on { + font-family: Arial,Helvetica; font-weight: normal; text-decoration: none; + color: #ff0000; font-size: 10pt; +} +.docSecs-off { + font-family: Arial,Helvetica; font-weight: normal; text-decoration: none; + color: #333333; font-size: 10pt; +} + +h2 { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: medium; +} +h1 { + font-family: Verdana,Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: large; +} + +DL { + font-family: Arial,Helvetica; font-weight: normal; text-decoration: none; + color: #333333; font-size: 10pt; +} + +UL > LI > A { + font-family: Arial,Helvetica; font-weight: bold; + color: #336699; font-size: 10pt; +} + +.moduleInfo { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #333333; font-size: 11pt; +} + +.moduleInfoSec { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: 10pt; +} + +.moduleInfoVal { + font-family: Arial,Helvetica; font-weight: normal; text-decoration: underline; + color: #000000; font-size: 10pt; +} + +.cpanNavTitle { + font-family: Arial,Helvetica; font-weight: bold; + color: #ffffff; font-size: 10pt; +} +.cpanNavLetter { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #333333; font-size: 9pt; +} +.cpanCat { + font-family: Arial,Helvetica; font-weight: bold; text-decoration: none; + color: #336699; font-size: 9pt; +} + +.bttndrkblue-bkgd-top { + background-color: #225688; + background-image: url(/global/mvc_objects/images/bttndrkblue_bgtop.gif); +} +.bttndrkblue-bkgd-left { + background-color: #225688; + background-image: url(/global/mvc_objects/images/bttndrkblue_bgleft.gif); +} +.bttndrkblue-bkgd { + padding-top: 0px; + padding-bottom: 0px; + margin-bottom: 0px; + margin-top: 0px; + background-repeat: no-repeat; + background-color: #225688; + background-image: url(/global/mvc_objects/images/bttndrkblue_bgmiddle.gif); + vertical-align: top; +} +.bttndrkblue-bkgd-right { + background-color: #225688; + background-image: url(/global/mvc_objects/images/bttndrkblue_bgright.gif); +} +.bttndrkblue-bkgd-bottom { + background-color: #225688; + background-image: url(/global/mvc_objects/images/bttndrkblue_bgbottom.gif); +} +.bttndrkblue-text a { + color: #ffffff; + text-decoration: none; +} +a.bttndrkblue-text:hover { + color: #ffDD3C; + text-decoration: none; +} +.bg-ltblue { + background-color: #f0f5fa; +} + +.border-left-b { + background: #f0f5fa url(/i/corner-leftline.gif) repeat-y; +} + +.border-right-b { + background: #f0f5fa url(/i/corner-rightline.gif) repeat-y; +} + +.border-top-b { + background: #f0f5fa url(/i/corner-topline.gif) repeat-x; +} + +.border-bottom-b { + background: #f0f5fa url(/i/corner-botline.gif) repeat-x; +} + +.border-right-w { + background: #ffffff url(/i/corner-rightline.gif) repeat-y; +} + +.border-top-w { + background: #ffffff url(/i/corner-topline.gif) repeat-x; +} + +.border-bottom-w { + background: #ffffff url(/i/corner-botline.gif) repeat-x; +} + +.bg-white { + background-color: #ffffff; +} + +.border-left-w { + background: #ffffff url(/i/corner-leftline.gif) repeat-y; +} diff --git a/cpp/llvm/tools/clang/examples/CMakeLists.txt b/cpp/llvm/tools/clang/examples/CMakeLists.txt new file mode 100644 index 00000000..19d88693 --- /dev/null +++ b/cpp/llvm/tools/clang/examples/CMakeLists.txt @@ -0,0 +1,7 @@ +if(NOT CLANG_BUILD_EXAMPLES) + set(EXCLUDE_FROM_ALL ON) +endif() + +add_subdirectory(analyzer-plugin) +add_subdirectory(clang-interpreter) +add_subdirectory(PrintFunctionNames) diff --git a/cpp/llvm/tools/clang/examples/Makefile b/cpp/llvm/tools/clang/examples/Makefile new file mode 100644 index 00000000..d8d90287 --- /dev/null +++ b/cpp/llvm/tools/clang/examples/Makefile @@ -0,0 +1,14 @@ +##===- examples/Makefile -----------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +CLANG_LEVEL := .. + +PARALLEL_DIRS := analyzer-plugin clang-interpreter PrintFunctionNames + +include $(CLANG_LEVEL)/Makefile diff --git a/cpp/llvm/tools/clang/examples/PrintFunctionNames/CMakeLists.txt b/cpp/llvm/tools/clang/examples/PrintFunctionNames/CMakeLists.txt new file mode 100644 index 00000000..86793ce7 --- /dev/null +++ b/cpp/llvm/tools/clang/examples/PrintFunctionNames/CMakeLists.txt @@ -0,0 +1,15 @@ +set(MODULE TRUE) + +set( LLVM_USED_LIBS + clangFrontend + clangAST + ) + +set( LLVM_LINK_COMPONENTS support mc) + +add_clang_library(PrintFunctionNames PrintFunctionNames.cpp) + +set_target_properties(PrintFunctionNames + PROPERTIES + LINKER_LANGUAGE CXX + PREFIX "") diff --git a/cpp/llvm/tools/clang/examples/PrintFunctionNames/Makefile b/cpp/llvm/tools/clang/examples/PrintFunctionNames/Makefile new file mode 100644 index 00000000..23a53054 --- /dev/null +++ b/cpp/llvm/tools/clang/examples/PrintFunctionNames/Makefile @@ -0,0 +1,28 @@ +##===- examples/PrintFunctionNames/Makefile ----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +CLANG_LEVEL := ../.. +LIBRARYNAME = PrintFunctionNames + +# If we don't need RTTI or EH, there's no reason to export anything +# from the plugin. +ifneq ($(REQUIRES_RTTI), 1) +ifneq ($(REQUIRES_EH), 1) +EXPORTED_SYMBOL_FILE = $(PROJ_SRC_DIR)/PrintFunctionNames.exports +endif +endif + +LINK_LIBS_IN_SHARED = 0 +SHARED_LIBRARY = 1 + +include $(CLANG_LEVEL)/Makefile + +ifeq ($(OS),Darwin) + LDFLAGS=-Wl,-undefined,dynamic_lookup +endif diff --git a/cpp/llvm/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp b/cpp/llvm/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp new file mode 100644 index 00000000..ce8f208e --- /dev/null +++ b/cpp/llvm/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp @@ -0,0 +1,71 @@ +//===- PrintFunctionNames.cpp ---------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// Example clang plugin which simply prints the names of all the top-level decls +// in the input file. +// +//===----------------------------------------------------------------------===// + +#include "clang/Frontend/FrontendPluginRegistry.h" +#include "clang/AST/ASTConsumer.h" +#include "clang/AST/AST.h" +#include "clang/Frontend/CompilerInstance.h" +#include "llvm/Support/raw_ostream.h" +using namespace clang; + +namespace { + +class PrintFunctionsConsumer : public ASTConsumer { +public: + virtual bool HandleTopLevelDecl(DeclGroupRef DG) { + for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) { + const Decl *D = *i; + if (const NamedDecl *ND = dyn_cast(D)) + llvm::errs() << "top-level-decl: \"" << ND->getNameAsString() << "\"\n"; + } + + return true; + } +}; + +class PrintFunctionNamesAction : public PluginASTAction { +protected: + ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) { + return new PrintFunctionsConsumer(); + } + + bool ParseArgs(const CompilerInstance &CI, + const std::vector& args) { + for (unsigned i = 0, e = args.size(); i != e; ++i) { + llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n"; + + // Example error handling. + if (args[i] == "-an-error") { + DiagnosticsEngine &D = CI.getDiagnostics(); + unsigned DiagID = D.getCustomDiagID( + DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'"); + D.Report(DiagID); + return false; + } + } + if (args.size() && args[0] == "help") + PrintHelp(llvm::errs()); + + return true; + } + void PrintHelp(llvm::raw_ostream& ros) { + ros << "Help for PrintFunctionNames plugin goes here\n"; + } + +}; + +} + +static FrontendPluginRegistry::Add +X("print-fns", "print function names"); diff --git a/cpp/llvm/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.exports b/cpp/llvm/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.exports new file mode 100644 index 00000000..0ff590d3 --- /dev/null +++ b/cpp/llvm/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.exports @@ -0,0 +1 @@ +_ZN4llvm8Registry* diff --git a/cpp/llvm/tools/clang/examples/PrintFunctionNames/README.txt b/cpp/llvm/tools/clang/examples/PrintFunctionNames/README.txt new file mode 100644 index 00000000..23ab5f0b --- /dev/null +++ b/cpp/llvm/tools/clang/examples/PrintFunctionNames/README.txt @@ -0,0 +1,16 @@ +This is a simple example demonstrating how to use clang's facility for +providing AST consumers using a plugin. + +Build the plugin by running `make` in this directory. + +Once the plugin is built, you can run it using: +-- +Linux: +$ clang -cc1 -load ../../Debug+Asserts/lib/libPrintFunctionNames.so -plugin print-fns some-input-file.c +$ clang -cc1 -load ../../Debug+Asserts/lib/libPrintFunctionNames.so -plugin print-fns -plugin-arg-print-fns help -plugin-arg-print-fns --example-argument some-input-file.c +$ clang -cc1 -load ../../Debug+Asserts/lib/libPrintFunctionNames.so -plugin print-fns -plugin-arg-print-fns -an-error some-input-file.c + +Mac: +$ clang -cc1 -load ../../Debug+Asserts/lib/libPrintFunctionNames.dylib -plugin print-fns some-input-file.c +$ clang -cc1 -load ../../Debug+Asserts/lib/libPrintFunctionNames.dylib -plugin print-fns -plugin-arg-print-fns help -plugin-arg-print-fns --example-argument some-input-file.c +$ clang -cc1 -load ../../Debug+Asserts/lib/libPrintFunctionNames.dylib -plugin print-fns -plugin-arg-print-fns -an-error some-input-file.c diff --git a/cpp/llvm/tools/clang/examples/analyzer-plugin/CMakeLists.txt b/cpp/llvm/tools/clang/examples/analyzer-plugin/CMakeLists.txt new file mode 100644 index 00000000..2b9d8258 --- /dev/null +++ b/cpp/llvm/tools/clang/examples/analyzer-plugin/CMakeLists.txt @@ -0,0 +1,14 @@ +set(MODULE TRUE) + +set( LLVM_USED_LIBS + clangStaticAnalyzerCore + ) + +set( LLVM_LINK_COMPONENTS support mc) + +add_clang_library(SampleAnalyzerPlugin MainCallChecker.cpp) + +set_target_properties(SampleAnalyzerPlugin + PROPERTIES + LINKER_LANGUAGE CXX + PREFIX "") diff --git a/cpp/llvm/tools/clang/examples/analyzer-plugin/MainCallChecker.cpp b/cpp/llvm/tools/clang/examples/analyzer-plugin/MainCallChecker.cpp new file mode 100644 index 00000000..48a97954 --- /dev/null +++ b/cpp/llvm/tools/clang/examples/analyzer-plugin/MainCallChecker.cpp @@ -0,0 +1,53 @@ +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Core/CheckerRegistry.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" + +using namespace clang; +using namespace ento; + +namespace { +class MainCallChecker : public Checker < check::PreStmt > { + mutable OwningPtr BT; + +public: + void checkPreStmt(const CallExpr *CE, CheckerContext &C) const; +}; +} // end anonymous namespace + +void MainCallChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const { + const ProgramStateRef state = C.getState(); + const LocationContext *LC = C.getLocationContext(); + const Expr *Callee = CE->getCallee(); + const FunctionDecl *FD = state->getSVal(Callee, LC).getAsFunctionDecl(); + + if (!FD) + return; + + // Get the name of the callee. + IdentifierInfo *II = FD->getIdentifier(); + if (!II) // if no identifier, not a simple C function + return; + + if (II->isStr("main")) { + ExplodedNode *N = C.generateSink(); + if (!N) + return; + + if (!BT) + BT.reset(new BugType("call to main", "example analyzer plugin")); + + BugReport *report = new BugReport(*BT, BT->getName(), N); + report->addRange(Callee->getSourceRange()); + C.EmitReport(report); + } +} + +// Register plugin! +extern "C" +void clang_registerCheckers (CheckerRegistry ®istry) { + registry.addChecker("example.MainCallChecker", "Disallows calls to functions called main"); +} + +extern "C" +const char clang_analyzerAPIVersionString[] = CLANG_ANALYZER_API_VERSION_STRING; diff --git a/cpp/llvm/tools/clang/examples/analyzer-plugin/Makefile b/cpp/llvm/tools/clang/examples/analyzer-plugin/Makefile new file mode 100644 index 00000000..8b83bef9 --- /dev/null +++ b/cpp/llvm/tools/clang/examples/analyzer-plugin/Makefile @@ -0,0 +1,20 @@ +##===- examples/analyzer-plugin/Makefile -------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +CLANG_LEVEL := ../.. +LIBRARYNAME = SampleAnalyzerPlugin + +LINK_LIBS_IN_SHARED = 0 +LOADABLE_MODULE = 1 + +include $(CLANG_LEVEL)/Makefile + +ifeq ($(OS),Darwin) + LDFLAGS=-Wl,-undefined,dynamic_lookup +endif diff --git a/cpp/llvm/tools/clang/examples/clang-interpreter/CMakeLists.txt b/cpp/llvm/tools/clang/examples/clang-interpreter/CMakeLists.txt new file mode 100644 index 00000000..809e324d --- /dev/null +++ b/cpp/llvm/tools/clang/examples/clang-interpreter/CMakeLists.txt @@ -0,0 +1,34 @@ +set(LLVM_USED_LIBS + clangFrontend + clangSerialization + clangDriver + clangCodeGen + clangSema + clangStaticAnalyzerFrontend + clangStaticAnalyzerCheckers + clangStaticAnalyzerCore + clangAnalysis + clangRewrite + clangAST + clangParse + clangLex + clangBasic + ) + +set(LLVM_LINK_COMPONENTS + jit + interpreter + nativecodegen + asmparser + bitreader + bitwriter + codegen + ipo + linker + selectiondag + ) + +add_clang_executable(clang-interpreter + main.cpp + ) +add_dependencies(clang-interpreter clang-headers) diff --git a/cpp/llvm/tools/clang/examples/clang-interpreter/Makefile b/cpp/llvm/tools/clang/examples/clang-interpreter/Makefile new file mode 100644 index 00000000..420a066c --- /dev/null +++ b/cpp/llvm/tools/clang/examples/clang-interpreter/Makefile @@ -0,0 +1,26 @@ +##===- examples/clang-interpreter/Makefile -----------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +CLANG_LEVEL := ../.. + +TOOLNAME = clang-interpreter +NO_INSTALL = 1 + +# No plugins, optimize startup time. +TOOL_NO_EXPORTS = 1 + +LINK_COMPONENTS := jit interpreter nativecodegen bitreader bitwriter ipo \ + linker selectiondag asmparser instrumentation +USEDLIBS = clangFrontend.a clangSerialization.a clangDriver.a clangCodeGen.a \ + clangParse.a clangSema.a clangStaticAnalyzerFrontend.a \ + clangStaticAnalyzerCheckers.a clangStaticAnalyzerCore.a \ + clangAnalysis.a clangRewrite.a \ + clangEdit.a clangAST.a clangLex.a clangBasic.a + +include $(CLANG_LEVEL)/Makefile diff --git a/cpp/llvm/tools/clang/examples/clang-interpreter/README.txt b/cpp/llvm/tools/clang/examples/clang-interpreter/README.txt new file mode 100644 index 00000000..7dd45fad --- /dev/null +++ b/cpp/llvm/tools/clang/examples/clang-interpreter/README.txt @@ -0,0 +1,17 @@ +This is an example of Clang based interpreter, for executing standalone C +programs. + +It demonstrates the following features: + 1. Parsing standard compiler command line arguments using the Driver library. + + 2. Constructing a Clang compiler instance, using the appropriate arguments + derived in step #1. + + 3. Invoking the Clang compiler to lex, parse, syntax check, and then generate + LLVM code. + + 4. Use the LLVM JIT functionality to execute the final module. + +The implementation has many limitations and is not designed to be a full fledged +C interpreter. It is designed to demonstrate a simple but functional use of the +Clang compiler libraries. diff --git a/cpp/llvm/tools/clang/examples/clang-interpreter/main.cpp b/cpp/llvm/tools/clang/examples/clang-interpreter/main.cpp new file mode 100644 index 00000000..c39468a3 --- /dev/null +++ b/cpp/llvm/tools/clang/examples/clang-interpreter/main.cpp @@ -0,0 +1,156 @@ +//===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/CodeGen/CodeGenAction.h" +#include "clang/Driver/Compilation.h" +#include "clang/Driver/Driver.h" +#include "clang/Driver/Tool.h" +#include "clang/Frontend/CompilerInvocation.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Frontend/DiagnosticOptions.h" +#include "clang/Frontend/FrontendDiagnostic.h" +#include "clang/Frontend/TextDiagnosticPrinter.h" + +#include "llvm/Module.h" +#include "llvm/ADT/OwningPtr.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/ExecutionEngine/JIT.h" +#include "llvm/ExecutionEngine/ExecutionEngine.h" +#include "llvm/Support/ManagedStatic.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Support/Host.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/TargetSelect.h" +using namespace clang; +using namespace clang::driver; + +// This function isn't referenced outside its translation unit, but it +// can't use the "static" keyword because its address is used for +// GetMainExecutable (since some platforms don't support taking the +// address of main, and some platforms can't implement GetMainExecutable +// without being given the address of a function in the main executable). +llvm::sys::Path GetExecutablePath(const char *Argv0) { + // This just needs to be some symbol in the binary; C++ doesn't + // allow taking the address of ::main however. + void *MainAddr = (void*) (intptr_t) GetExecutablePath; + return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr); +} + +static int Execute(llvm::Module *Mod, char * const *envp) { + llvm::InitializeNativeTarget(); + + std::string Error; + OwningPtr EE( + llvm::ExecutionEngine::createJIT(Mod, &Error)); + if (!EE) { + llvm::errs() << "unable to make execution engine: " << Error << "\n"; + return 255; + } + + llvm::Function *EntryFn = Mod->getFunction("main"); + if (!EntryFn) { + llvm::errs() << "'main' function not found in module.\n"; + return 255; + } + + // FIXME: Support passing arguments. + std::vector Args; + Args.push_back(Mod->getModuleIdentifier()); + + return EE->runFunctionAsMain(EntryFn, Args, envp); +} + +int main(int argc, const char **argv, char * const *envp) { + void *MainAddr = (void*) (intptr_t) GetExecutablePath; + llvm::sys::Path Path = GetExecutablePath(argv[0]); + TextDiagnosticPrinter *DiagClient = + new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions()); + + IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + DiagnosticsEngine Diags(DiagID, DiagClient); + Driver TheDriver(Path.str(), llvm::sys::getDefaultTargetTriple(), + "a.out", /*IsProduction=*/false, Diags); + TheDriver.setTitle("clang interpreter"); + + // FIXME: This is a hack to try to force the driver to do something we can + // recognize. We need to extend the driver library to support this use model + // (basically, exactly one input, and the operation mode is hard wired). + llvm::SmallVector Args(argv, argv + argc); + Args.push_back("-fsyntax-only"); + OwningPtr C(TheDriver.BuildCompilation(Args)); + if (!C) + return 0; + + // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate. + + // We expect to get back exactly one command job, if we didn't something + // failed. Extract that job from the compilation. + const driver::JobList &Jobs = C->getJobs(); + if (Jobs.size() != 1 || !isa(*Jobs.begin())) { + SmallString<256> Msg; + llvm::raw_svector_ostream OS(Msg); + C->PrintJob(OS, C->getJobs(), "; ", true); + Diags.Report(diag::err_fe_expected_compiler_job) << OS.str(); + return 1; + } + + const driver::Command *Cmd = cast(*Jobs.begin()); + if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") { + Diags.Report(diag::err_fe_expected_clang_command); + return 1; + } + + // Initialize a compiler invocation object from the clang (-cc1) arguments. + const driver::ArgStringList &CCArgs = Cmd->getArguments(); + OwningPtr CI(new CompilerInvocation); + CompilerInvocation::CreateFromArgs(*CI, + const_cast(CCArgs.data()), + const_cast(CCArgs.data()) + + CCArgs.size(), + Diags); + + // Show the invocation, with -v. + if (CI->getHeaderSearchOpts().Verbose) { + llvm::errs() << "clang invocation:\n"; + C->PrintJob(llvm::errs(), C->getJobs(), "\n", true); + llvm::errs() << "\n"; + } + + // FIXME: This is copied from cc1_main.cpp; simplify and eliminate. + + // Create a compiler instance to handle the actual work. + CompilerInstance Clang; + Clang.setInvocation(CI.take()); + + // Create the compilers actual diagnostics engine. + Clang.createDiagnostics(int(CCArgs.size()),const_cast(CCArgs.data())); + if (!Clang.hasDiagnostics()) + return 1; + + // Infer the builtin include path if unspecified. + if (Clang.getHeaderSearchOpts().UseBuiltinIncludes && + Clang.getHeaderSearchOpts().ResourceDir.empty()) + Clang.getHeaderSearchOpts().ResourceDir = + CompilerInvocation::GetResourcesPath(argv[0], MainAddr); + + // Create and execute the frontend to generate an LLVM bitcode module. + OwningPtr Act(new EmitLLVMOnlyAction()); + if (!Clang.ExecuteAction(*Act)) + return 1; + + int Res = 255; + if (llvm::Module *Module = Act->takeModule()) + Res = Execute(Module, envp); + + // Shutdown. + + llvm::llvm_shutdown(); + + return Res; +} diff --git a/cpp/llvm/tools/clang/include/CMakeLists.txt b/cpp/llvm/tools/clang/include/CMakeLists.txt new file mode 100644 index 00000000..253a09b1 --- /dev/null +++ b/cpp/llvm/tools/clang/include/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(clang) diff --git a/cpp/llvm/tools/clang/include/Makefile b/cpp/llvm/tools/clang/include/Makefile new file mode 100644 index 00000000..79b9adfb --- /dev/null +++ b/cpp/llvm/tools/clang/include/Makefile @@ -0,0 +1,4 @@ +CLANG_LEVEL := .. +DIRS := clang clang-c + +include $(CLANG_LEVEL)/Makefile diff --git a/cpp/llvm/tools/clang/include/clang-c/Index.h b/cpp/llvm/tools/clang/include/clang-c/Index.h new file mode 100644 index 00000000..13ba6ba2 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang-c/Index.h @@ -0,0 +1,4748 @@ +/*===-- clang-c/Index.h - Indexing Public C Interface -------------*- C -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This header provides a public inferface to a Clang library for extracting *| +|* high-level symbol information from source files without exposing the full *| +|* Clang C++ API. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifndef CLANG_C_INDEX_H +#define CLANG_C_INDEX_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* MSVC DLL import/export. */ +#ifdef _MSC_VER + #ifdef _CINDEX_LIB_ + #define CINDEX_LINKAGE __declspec(dllexport) + #else + #define CINDEX_LINKAGE __declspec(dllimport) + #endif +#else + #define CINDEX_LINKAGE +#endif + +#ifdef __GNUC__ + #define CINDEX_DEPRECATED __attribute__((deprecated)) +#else + #ifdef _MSC_VER + #define CINDEX_DEPRECATED __declspec(deprecated) + #else + #define CINDEX_DEPRECATED + #endif +#endif + +/** \defgroup CINDEX libclang: C Interface to Clang + * + * The C Interface to Clang provides a relatively small API that exposes + * facilities for parsing source code into an abstract syntax tree (AST), + * loading already-parsed ASTs, traversing the AST, associating + * physical source locations with elements within the AST, and other + * facilities that support Clang-based development tools. + * + * This C interface to Clang will never provide all of the information + * representation stored in Clang's C++ AST, nor should it: the intent is to + * maintain an API that is relatively stable from one release to the next, + * providing only the basic functionality needed to support development tools. + * + * To avoid namespace pollution, data types are prefixed with "CX" and + * functions are prefixed with "clang_". + * + * @{ + */ + +/** + * \brief An "index" that consists of a set of translation units that would + * typically be linked together into an executable or library. + */ +typedef void *CXIndex; + +/** + * \brief A single translation unit, which resides in an index. + */ +typedef struct CXTranslationUnitImpl *CXTranslationUnit; + +/** + * \brief Opaque pointer representing client data that will be passed through + * to various callbacks and visitors. + */ +typedef void *CXClientData; + +/** + * \brief Provides the contents of a file that has not yet been saved to disk. + * + * Each CXUnsavedFile instance provides the name of a file on the + * system along with the current contents of that file that have not + * yet been saved to disk. + */ +struct CXUnsavedFile { + /** + * \brief The file whose contents have not yet been saved. + * + * This file must already exist in the file system. + */ + const char *Filename; + + /** + * \brief A buffer containing the unsaved contents of this file. + */ + const char *Contents; + + /** + * \brief The length of the unsaved contents of this buffer. + */ + unsigned long Length; +}; + +/** + * \brief Describes the availability of a particular entity, which indicates + * whether the use of this entity will result in a warning or error due to + * it being deprecated or unavailable. + */ +enum CXAvailabilityKind { + /** + * \brief The entity is available. + */ + CXAvailability_Available, + /** + * \brief The entity is available, but has been deprecated (and its use is + * not recommended). + */ + CXAvailability_Deprecated, + /** + * \brief The entity is not available; any use of it will be an error. + */ + CXAvailability_NotAvailable, + /** + * \brief The entity is available, but not accessible; any use of it will be + * an error. + */ + CXAvailability_NotAccessible +}; + +/** + * \defgroup CINDEX_STRING String manipulation routines + * + * @{ + */ + +/** + * \brief A character string. + * + * The \c CXString type is used to return strings from the interface when + * the ownership of that string might different from one call to the next. + * Use \c clang_getCString() to retrieve the string data and, once finished + * with the string data, call \c clang_disposeString() to free the string. + */ +typedef struct { + void *data; + unsigned private_flags; +} CXString; + +/** + * \brief Retrieve the character data associated with the given string. + */ +CINDEX_LINKAGE const char *clang_getCString(CXString string); + +/** + * \brief Free the given string, + */ +CINDEX_LINKAGE void clang_disposeString(CXString string); + +/** + * @} + */ + +/** + * \brief clang_createIndex() provides a shared context for creating + * translation units. It provides two options: + * + * - excludeDeclarationsFromPCH: When non-zero, allows enumeration of "local" + * declarations (when loading any new translation units). A "local" declaration + * is one that belongs in the translation unit itself and not in a precompiled + * header that was used by the translation unit. If zero, all declarations + * will be enumerated. + * + * Here is an example: + * + * // excludeDeclsFromPCH = 1, displayDiagnostics=1 + * Idx = clang_createIndex(1, 1); + * + * // IndexTest.pch was produced with the following command: + * // "clang -x c IndexTest.h -emit-ast -o IndexTest.pch" + * TU = clang_createTranslationUnit(Idx, "IndexTest.pch"); + * + * // This will load all the symbols from 'IndexTest.pch' + * clang_visitChildren(clang_getTranslationUnitCursor(TU), + * TranslationUnitVisitor, 0); + * clang_disposeTranslationUnit(TU); + * + * // This will load all the symbols from 'IndexTest.c', excluding symbols + * // from 'IndexTest.pch'. + * char *args[] = { "-Xclang", "-include-pch=IndexTest.pch" }; + * TU = clang_createTranslationUnitFromSourceFile(Idx, "IndexTest.c", 2, args, + * 0, 0); + * clang_visitChildren(clang_getTranslationUnitCursor(TU), + * TranslationUnitVisitor, 0); + * clang_disposeTranslationUnit(TU); + * + * This process of creating the 'pch', loading it separately, and using it (via + * -include-pch) allows 'excludeDeclsFromPCH' to remove redundant callbacks + * (which gives the indexer the same performance benefit as the compiler). + */ +CINDEX_LINKAGE CXIndex clang_createIndex(int excludeDeclarationsFromPCH, + int displayDiagnostics); + +/** + * \brief Destroy the given index. + * + * The index must not be destroyed until all of the translation units created + * within that index have been destroyed. + */ +CINDEX_LINKAGE void clang_disposeIndex(CXIndex index); + +typedef enum { + /** + * \brief Used to indicate that no special CXIndex options are needed. + */ + CXGlobalOpt_None = 0x0, + + /** + * \brief Used to indicate that threads that libclang creates for indexing + * purposes should use background priority. + * Affects \see clang_indexSourceFile, \see clang_indexTranslationUnit, + * \see clang_parseTranslationUnit, \see clang_saveTranslationUnit. + */ + CXGlobalOpt_ThreadBackgroundPriorityForIndexing = 0x1, + + /** + * \brief Used to indicate that threads that libclang creates for editing + * purposes should use background priority. + * Affects \see clang_reparseTranslationUnit, \see clang_codeCompleteAt, + * \see clang_annotateTokens + */ + CXGlobalOpt_ThreadBackgroundPriorityForEditing = 0x2, + + /** + * \brief Used to indicate that all threads that libclang creates should use + * background priority. + */ + CXGlobalOpt_ThreadBackgroundPriorityForAll = + CXGlobalOpt_ThreadBackgroundPriorityForIndexing | + CXGlobalOpt_ThreadBackgroundPriorityForEditing + +} CXGlobalOptFlags; + +/** + * \brief Sets general options associated with a CXIndex. + * + * For example: + * \code + * CXIndex idx = ...; + * clang_CXIndex_setGlobalOptions(idx, + * clang_CXIndex_getGlobalOptions(idx) | + * CXGlobalOpt_ThreadBackgroundPriorityForIndexing); + * \endcode + * + * \param options A bitmask of options, a bitwise OR of CXGlobalOpt_XXX flags. + */ +CINDEX_LINKAGE void clang_CXIndex_setGlobalOptions(CXIndex, unsigned options); + +/** + * \brief Gets the general options associated with a CXIndex. + * + * \returns A bitmask of options, a bitwise OR of CXGlobalOpt_XXX flags that + * are associated with the given CXIndex object. + */ +CINDEX_LINKAGE unsigned clang_CXIndex_getGlobalOptions(CXIndex); + +/** + * \defgroup CINDEX_FILES File manipulation routines + * + * @{ + */ + +/** + * \brief A particular source file that is part of a translation unit. + */ +typedef void *CXFile; + + +/** + * \brief Retrieve the complete file and path name of the given file. + */ +CINDEX_LINKAGE CXString clang_getFileName(CXFile SFile); + +/** + * \brief Retrieve the last modification time of the given file. + */ +CINDEX_LINKAGE time_t clang_getFileTime(CXFile SFile); + +/** + * \brief Determine whether the given header is guarded against + * multiple inclusions, either with the conventional + * #ifndef/#define/#endif macro guards or with #pragma once. + */ +CINDEX_LINKAGE unsigned +clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file); + +/** + * \brief Retrieve a file handle within the given translation unit. + * + * \param tu the translation unit + * + * \param file_name the name of the file. + * + * \returns the file handle for the named file in the translation unit \p tu, + * or a NULL file handle if the file was not a part of this translation unit. + */ +CINDEX_LINKAGE CXFile clang_getFile(CXTranslationUnit tu, + const char *file_name); + +/** + * @} + */ + +/** + * \defgroup CINDEX_LOCATIONS Physical source locations + * + * Clang represents physical source locations in its abstract syntax tree in + * great detail, with file, line, and column information for the majority of + * the tokens parsed in the source code. These data types and functions are + * used to represent source location information, either for a particular + * point in the program or for a range of points in the program, and extract + * specific location information from those data types. + * + * @{ + */ + +/** + * \brief Identifies a specific source location within a translation + * unit. + * + * Use clang_getExpansionLocation() or clang_getSpellingLocation() + * to map a source location to a particular file, line, and column. + */ +typedef struct { + void *ptr_data[2]; + unsigned int_data; +} CXSourceLocation; + +/** + * \brief Identifies a half-open character range in the source code. + * + * Use clang_getRangeStart() and clang_getRangeEnd() to retrieve the + * starting and end locations from a source range, respectively. + */ +typedef struct { + void *ptr_data[2]; + unsigned begin_int_data; + unsigned end_int_data; +} CXSourceRange; + +/** + * \brief Retrieve a NULL (invalid) source location. + */ +CINDEX_LINKAGE CXSourceLocation clang_getNullLocation(); + +/** + * \determine Determine whether two source locations, which must refer into + * the same translation unit, refer to exactly the same point in the source + * code. + * + * \returns non-zero if the source locations refer to the same location, zero + * if they refer to different locations. + */ +CINDEX_LINKAGE unsigned clang_equalLocations(CXSourceLocation loc1, + CXSourceLocation loc2); + +/** + * \brief Retrieves the source location associated with a given file/line/column + * in a particular translation unit. + */ +CINDEX_LINKAGE CXSourceLocation clang_getLocation(CXTranslationUnit tu, + CXFile file, + unsigned line, + unsigned column); +/** + * \brief Retrieves the source location associated with a given character offset + * in a particular translation unit. + */ +CINDEX_LINKAGE CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu, + CXFile file, + unsigned offset); + +/** + * \brief Retrieve a NULL (invalid) source range. + */ +CINDEX_LINKAGE CXSourceRange clang_getNullRange(); + +/** + * \brief Retrieve a source range given the beginning and ending source + * locations. + */ +CINDEX_LINKAGE CXSourceRange clang_getRange(CXSourceLocation begin, + CXSourceLocation end); + +/** + * \brief Determine whether two ranges are equivalent. + * + * \returns non-zero if the ranges are the same, zero if they differ. + */ +CINDEX_LINKAGE unsigned clang_equalRanges(CXSourceRange range1, + CXSourceRange range2); + +/** + * \brief Returns non-zero if \arg range is null. + */ +CINDEX_LINKAGE int clang_Range_isNull(CXSourceRange range); + +/** + * \brief Retrieve the file, line, column, and offset represented by + * the given source location. + * + * If the location refers into a macro expansion, retrieves the + * location of the macro expansion. + * + * \param location the location within a source file that will be decomposed + * into its parts. + * + * \param file [out] if non-NULL, will be set to the file to which the given + * source location points. + * + * \param line [out] if non-NULL, will be set to the line to which the given + * source location points. + * + * \param column [out] if non-NULL, will be set to the column to which the given + * source location points. + * + * \param offset [out] if non-NULL, will be set to the offset into the + * buffer to which the given source location points. + */ +CINDEX_LINKAGE void clang_getExpansionLocation(CXSourceLocation location, + CXFile *file, + unsigned *line, + unsigned *column, + unsigned *offset); + +/** + * \brief Retrieve the file, line, column, and offset represented by + * the given source location, as specified in a # line directive. + * + * Example: given the following source code in a file somefile.c + * + * #123 "dummy.c" 1 + * + * static int func(void) + * { + * return 0; + * } + * + * the location information returned by this function would be + * + * File: dummy.c Line: 124 Column: 12 + * + * whereas clang_getExpansionLocation would have returned + * + * File: somefile.c Line: 3 Column: 12 + * + * \param location the location within a source file that will be decomposed + * into its parts. + * + * \param filename [out] if non-NULL, will be set to the filename of the + * source location. Note that filenames returned will be for "virtual" files, + * which don't necessarily exist on the machine running clang - e.g. when + * parsing preprocessed output obtained from a different environment. If + * a non-NULL value is passed in, remember to dispose of the returned value + * using \c clang_disposeString() once you've finished with it. For an invalid + * source location, an empty string is returned. + * + * \param line [out] if non-NULL, will be set to the line number of the + * source location. For an invalid source location, zero is returned. + * + * \param column [out] if non-NULL, will be set to the column number of the + * source location. For an invalid source location, zero is returned. + */ +CINDEX_LINKAGE void clang_getPresumedLocation(CXSourceLocation location, + CXString *filename, + unsigned *line, + unsigned *column); + +/** + * \brief Legacy API to retrieve the file, line, column, and offset represented + * by the given source location. + * + * This interface has been replaced by the newer interface + * \see clang_getExpansionLocation(). See that interface's documentation for + * details. + */ +CINDEX_LINKAGE void clang_getInstantiationLocation(CXSourceLocation location, + CXFile *file, + unsigned *line, + unsigned *column, + unsigned *offset); + +/** + * \brief Retrieve the file, line, column, and offset represented by + * the given source location. + * + * If the location refers into a macro instantiation, return where the + * location was originally spelled in the source file. + * + * \param location the location within a source file that will be decomposed + * into its parts. + * + * \param file [out] if non-NULL, will be set to the file to which the given + * source location points. + * + * \param line [out] if non-NULL, will be set to the line to which the given + * source location points. + * + * \param column [out] if non-NULL, will be set to the column to which the given + * source location points. + * + * \param offset [out] if non-NULL, will be set to the offset into the + * buffer to which the given source location points. + */ +CINDEX_LINKAGE void clang_getSpellingLocation(CXSourceLocation location, + CXFile *file, + unsigned *line, + unsigned *column, + unsigned *offset); + +/** + * \brief Retrieve a source location representing the first character within a + * source range. + */ +CINDEX_LINKAGE CXSourceLocation clang_getRangeStart(CXSourceRange range); + +/** + * \brief Retrieve a source location representing the last character within a + * source range. + */ +CINDEX_LINKAGE CXSourceLocation clang_getRangeEnd(CXSourceRange range); + +/** + * @} + */ + +/** + * \defgroup CINDEX_DIAG Diagnostic reporting + * + * @{ + */ + +/** + * \brief Describes the severity of a particular diagnostic. + */ +enum CXDiagnosticSeverity { + /** + * \brief A diagnostic that has been suppressed, e.g., by a command-line + * option. + */ + CXDiagnostic_Ignored = 0, + + /** + * \brief This diagnostic is a note that should be attached to the + * previous (non-note) diagnostic. + */ + CXDiagnostic_Note = 1, + + /** + * \brief This diagnostic indicates suspicious code that may not be + * wrong. + */ + CXDiagnostic_Warning = 2, + + /** + * \brief This diagnostic indicates that the code is ill-formed. + */ + CXDiagnostic_Error = 3, + + /** + * \brief This diagnostic indicates that the code is ill-formed such + * that future parser recovery is unlikely to produce useful + * results. + */ + CXDiagnostic_Fatal = 4 +}; + +/** + * \brief A single diagnostic, containing the diagnostic's severity, + * location, text, source ranges, and fix-it hints. + */ +typedef void *CXDiagnostic; + +/** + * \brief A group of CXDiagnostics. + */ +typedef void *CXDiagnosticSet; + +/** + * \brief Determine the number of diagnostics in a CXDiagnosticSet. + */ +CINDEX_LINKAGE unsigned clang_getNumDiagnosticsInSet(CXDiagnosticSet Diags); + +/** + * \brief Retrieve a diagnostic associated with the given CXDiagnosticSet. + * + * \param Unit the CXDiagnosticSet to query. + * \param Index the zero-based diagnostic number to retrieve. + * + * \returns the requested diagnostic. This diagnostic must be freed + * via a call to \c clang_disposeDiagnostic(). + */ +CINDEX_LINKAGE CXDiagnostic clang_getDiagnosticInSet(CXDiagnosticSet Diags, + unsigned Index); + + +/** + * \brief Describes the kind of error that occurred (if any) in a call to + * \c clang_loadDiagnostics. + */ +enum CXLoadDiag_Error { + /** + * \brief Indicates that no error occurred. + */ + CXLoadDiag_None = 0, + + /** + * \brief Indicates that an unknown error occurred while attempting to + * deserialize diagnostics. + */ + CXLoadDiag_Unknown = 1, + + /** + * \brief Indicates that the file containing the serialized diagnostics + * could not be opened. + */ + CXLoadDiag_CannotLoad = 2, + + /** + * \brief Indicates that the serialized diagnostics file is invalid or + * corrupt. + */ + CXLoadDiag_InvalidFile = 3 +}; + +/** + * \brief Deserialize a set of diagnostics from a Clang diagnostics bitcode + * file. + * + * \param The name of the file to deserialize. + * \param A pointer to a enum value recording if there was a problem + * deserializing the diagnostics. + * \param A pointer to a CXString for recording the error string + * if the file was not successfully loaded. + * + * \returns A loaded CXDiagnosticSet if successful, and NULL otherwise. These + * diagnostics should be released using clang_disposeDiagnosticSet(). + */ +CINDEX_LINKAGE CXDiagnosticSet clang_loadDiagnostics(const char *file, + enum CXLoadDiag_Error *error, + CXString *errorString); + +/** + * \brief Release a CXDiagnosticSet and all of its contained diagnostics. + */ +CINDEX_LINKAGE void clang_disposeDiagnosticSet(CXDiagnosticSet Diags); + +/** + * \brief Retrieve the child diagnostics of a CXDiagnostic. This + * CXDiagnosticSet does not need to be released by clang_diposeDiagnosticSet. + */ +CINDEX_LINKAGE CXDiagnosticSet clang_getChildDiagnostics(CXDiagnostic D); + +/** + * \brief Determine the number of diagnostics produced for the given + * translation unit. + */ +CINDEX_LINKAGE unsigned clang_getNumDiagnostics(CXTranslationUnit Unit); + +/** + * \brief Retrieve a diagnostic associated with the given translation unit. + * + * \param Unit the translation unit to query. + * \param Index the zero-based diagnostic number to retrieve. + * + * \returns the requested diagnostic. This diagnostic must be freed + * via a call to \c clang_disposeDiagnostic(). + */ +CINDEX_LINKAGE CXDiagnostic clang_getDiagnostic(CXTranslationUnit Unit, + unsigned Index); + +/** + * \brief Retrieve the complete set of diagnostics associated with a + * translation unit. + * + * \param Unit the translation unit to query. + */ +CINDEX_LINKAGE CXDiagnosticSet + clang_getDiagnosticSetFromTU(CXTranslationUnit Unit); + +/** + * \brief Destroy a diagnostic. + */ +CINDEX_LINKAGE void clang_disposeDiagnostic(CXDiagnostic Diagnostic); + +/** + * \brief Options to control the display of diagnostics. + * + * The values in this enum are meant to be combined to customize the + * behavior of \c clang_displayDiagnostic(). + */ +enum CXDiagnosticDisplayOptions { + /** + * \brief Display the source-location information where the + * diagnostic was located. + * + * When set, diagnostics will be prefixed by the file, line, and + * (optionally) column to which the diagnostic refers. For example, + * + * \code + * test.c:28: warning: extra tokens at end of #endif directive + * \endcode + * + * This option corresponds to the clang flag \c -fshow-source-location. + */ + CXDiagnostic_DisplaySourceLocation = 0x01, + + /** + * \brief If displaying the source-location information of the + * diagnostic, also include the column number. + * + * This option corresponds to the clang flag \c -fshow-column. + */ + CXDiagnostic_DisplayColumn = 0x02, + + /** + * \brief If displaying the source-location information of the + * diagnostic, also include information about source ranges in a + * machine-parsable format. + * + * This option corresponds to the clang flag + * \c -fdiagnostics-print-source-range-info. + */ + CXDiagnostic_DisplaySourceRanges = 0x04, + + /** + * \brief Display the option name associated with this diagnostic, if any. + * + * The option name displayed (e.g., -Wconversion) will be placed in brackets + * after the diagnostic text. This option corresponds to the clang flag + * \c -fdiagnostics-show-option. + */ + CXDiagnostic_DisplayOption = 0x08, + + /** + * \brief Display the category number associated with this diagnostic, if any. + * + * The category number is displayed within brackets after the diagnostic text. + * This option corresponds to the clang flag + * \c -fdiagnostics-show-category=id. + */ + CXDiagnostic_DisplayCategoryId = 0x10, + + /** + * \brief Display the category name associated with this diagnostic, if any. + * + * The category name is displayed within brackets after the diagnostic text. + * This option corresponds to the clang flag + * \c -fdiagnostics-show-category=name. + */ + CXDiagnostic_DisplayCategoryName = 0x20 +}; + +/** + * \brief Format the given diagnostic in a manner that is suitable for display. + * + * This routine will format the given diagnostic to a string, rendering + * the diagnostic according to the various options given. The + * \c clang_defaultDiagnosticDisplayOptions() function returns the set of + * options that most closely mimics the behavior of the clang compiler. + * + * \param Diagnostic The diagnostic to print. + * + * \param Options A set of options that control the diagnostic display, + * created by combining \c CXDiagnosticDisplayOptions values. + * + * \returns A new string containing for formatted diagnostic. + */ +CINDEX_LINKAGE CXString clang_formatDiagnostic(CXDiagnostic Diagnostic, + unsigned Options); + +/** + * \brief Retrieve the set of display options most similar to the + * default behavior of the clang compiler. + * + * \returns A set of display options suitable for use with \c + * clang_displayDiagnostic(). + */ +CINDEX_LINKAGE unsigned clang_defaultDiagnosticDisplayOptions(void); + +/** + * \brief Determine the severity of the given diagnostic. + */ +CINDEX_LINKAGE enum CXDiagnosticSeverity +clang_getDiagnosticSeverity(CXDiagnostic); + +/** + * \brief Retrieve the source location of the given diagnostic. + * + * This location is where Clang would print the caret ('^') when + * displaying the diagnostic on the command line. + */ +CINDEX_LINKAGE CXSourceLocation clang_getDiagnosticLocation(CXDiagnostic); + +/** + * \brief Retrieve the text of the given diagnostic. + */ +CINDEX_LINKAGE CXString clang_getDiagnosticSpelling(CXDiagnostic); + +/** + * \brief Retrieve the name of the command-line option that enabled this + * diagnostic. + * + * \param Diag The diagnostic to be queried. + * + * \param Disable If non-NULL, will be set to the option that disables this + * diagnostic (if any). + * + * \returns A string that contains the command-line option used to enable this + * warning, such as "-Wconversion" or "-pedantic". + */ +CINDEX_LINKAGE CXString clang_getDiagnosticOption(CXDiagnostic Diag, + CXString *Disable); + +/** + * \brief Retrieve the category number for this diagnostic. + * + * Diagnostics can be categorized into groups along with other, related + * diagnostics (e.g., diagnostics under the same warning flag). This routine + * retrieves the category number for the given diagnostic. + * + * \returns The number of the category that contains this diagnostic, or zero + * if this diagnostic is uncategorized. + */ +CINDEX_LINKAGE unsigned clang_getDiagnosticCategory(CXDiagnostic); + +/** + * \brief Retrieve the name of a particular diagnostic category. This + * is now deprecated. Use clang_getDiagnosticCategoryText() + * instead. + * + * \param Category A diagnostic category number, as returned by + * \c clang_getDiagnosticCategory(). + * + * \returns The name of the given diagnostic category. + */ +CINDEX_DEPRECATED CINDEX_LINKAGE +CXString clang_getDiagnosticCategoryName(unsigned Category); + +/** + * \brief Retrieve the diagnostic category text for a given diagnostic. + * + * + * \returns The text of the given diagnostic category. + */ +CINDEX_LINKAGE CXString clang_getDiagnosticCategoryText(CXDiagnostic); + +/** + * \brief Determine the number of source ranges associated with the given + * diagnostic. + */ +CINDEX_LINKAGE unsigned clang_getDiagnosticNumRanges(CXDiagnostic); + +/** + * \brief Retrieve a source range associated with the diagnostic. + * + * A diagnostic's source ranges highlight important elements in the source + * code. On the command line, Clang displays source ranges by + * underlining them with '~' characters. + * + * \param Diagnostic the diagnostic whose range is being extracted. + * + * \param Range the zero-based index specifying which range to + * + * \returns the requested source range. + */ +CINDEX_LINKAGE CXSourceRange clang_getDiagnosticRange(CXDiagnostic Diagnostic, + unsigned Range); + +/** + * \brief Determine the number of fix-it hints associated with the + * given diagnostic. + */ +CINDEX_LINKAGE unsigned clang_getDiagnosticNumFixIts(CXDiagnostic Diagnostic); + +/** + * \brief Retrieve the replacement information for a given fix-it. + * + * Fix-its are described in terms of a source range whose contents + * should be replaced by a string. This approach generalizes over + * three kinds of operations: removal of source code (the range covers + * the code to be removed and the replacement string is empty), + * replacement of source code (the range covers the code to be + * replaced and the replacement string provides the new code), and + * insertion (both the start and end of the range point at the + * insertion location, and the replacement string provides the text to + * insert). + * + * \param Diagnostic The diagnostic whose fix-its are being queried. + * + * \param FixIt The zero-based index of the fix-it. + * + * \param ReplacementRange The source range whose contents will be + * replaced with the returned replacement string. Note that source + * ranges are half-open ranges [a, b), so the source code should be + * replaced from a and up to (but not including) b. + * + * \returns A string containing text that should be replace the source + * code indicated by the \c ReplacementRange. + */ +CINDEX_LINKAGE CXString clang_getDiagnosticFixIt(CXDiagnostic Diagnostic, + unsigned FixIt, + CXSourceRange *ReplacementRange); + +/** + * @} + */ + +/** + * \defgroup CINDEX_TRANSLATION_UNIT Translation unit manipulation + * + * The routines in this group provide the ability to create and destroy + * translation units from files, either by parsing the contents of the files or + * by reading in a serialized representation of a translation unit. + * + * @{ + */ + +/** + * \brief Get the original translation unit source file name. + */ +CINDEX_LINKAGE CXString +clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit); + +/** + * \brief Return the CXTranslationUnit for a given source file and the provided + * command line arguments one would pass to the compiler. + * + * Note: The 'source_filename' argument is optional. If the caller provides a + * NULL pointer, the name of the source file is expected to reside in the + * specified command line arguments. + * + * Note: When encountered in 'clang_command_line_args', the following options + * are ignored: + * + * '-c' + * '-emit-ast' + * '-fsyntax-only' + * '-o ' (both '-o' and '' are ignored) + * + * \param CIdx The index object with which the translation unit will be + * associated. + * + * \param source_filename - The name of the source file to load, or NULL if the + * source file is included in \p clang_command_line_args. + * + * \param num_clang_command_line_args The number of command-line arguments in + * \p clang_command_line_args. + * + * \param clang_command_line_args The command-line arguments that would be + * passed to the \c clang executable if it were being invoked out-of-process. + * These command-line options will be parsed and will affect how the translation + * unit is parsed. Note that the following options are ignored: '-c', + * '-emit-ast', '-fsyntex-only' (which is the default), and '-o '. + * + * \param num_unsaved_files the number of unsaved file entries in \p + * unsaved_files. + * + * \param unsaved_files the files that have not yet been saved to disk + * but may be required for code completion, including the contents of + * those files. The contents and name of these files (as specified by + * CXUnsavedFile) are copied when necessary, so the client only needs to + * guarantee their validity until the call to this function returns. + */ +CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnitFromSourceFile( + CXIndex CIdx, + const char *source_filename, + int num_clang_command_line_args, + const char * const *clang_command_line_args, + unsigned num_unsaved_files, + struct CXUnsavedFile *unsaved_files); + +/** + * \brief Create a translation unit from an AST file (-emit-ast). + */ +CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnit(CXIndex, + const char *ast_filename); + +/** + * \brief Flags that control the creation of translation units. + * + * The enumerators in this enumeration type are meant to be bitwise + * ORed together to specify which options should be used when + * constructing the translation unit. + */ +enum CXTranslationUnit_Flags { + /** + * \brief Used to indicate that no special translation-unit options are + * needed. + */ + CXTranslationUnit_None = 0x0, + + /** + * \brief Used to indicate that the parser should construct a "detailed" + * preprocessing record, including all macro definitions and instantiations. + * + * Constructing a detailed preprocessing record requires more memory + * and time to parse, since the information contained in the record + * is usually not retained. However, it can be useful for + * applications that require more detailed information about the + * behavior of the preprocessor. + */ + CXTranslationUnit_DetailedPreprocessingRecord = 0x01, + + /** + * \brief Used to indicate that the translation unit is incomplete. + * + * When a translation unit is considered "incomplete", semantic + * analysis that is typically performed at the end of the + * translation unit will be suppressed. For example, this suppresses + * the completion of tentative declarations in C and of + * instantiation of implicitly-instantiation function templates in + * C++. This option is typically used when parsing a header with the + * intent of producing a precompiled header. + */ + CXTranslationUnit_Incomplete = 0x02, + + /** + * \brief Used to indicate that the translation unit should be built with an + * implicit precompiled header for the preamble. + * + * An implicit precompiled header is used as an optimization when a + * particular translation unit is likely to be reparsed many times + * when the sources aren't changing that often. In this case, an + * implicit precompiled header will be built containing all of the + * initial includes at the top of the main file (what we refer to as + * the "preamble" of the file). In subsequent parses, if the + * preamble or the files in it have not changed, \c + * clang_reparseTranslationUnit() will re-use the implicit + * precompiled header to improve parsing performance. + */ + CXTranslationUnit_PrecompiledPreamble = 0x04, + + /** + * \brief Used to indicate that the translation unit should cache some + * code-completion results with each reparse of the source file. + * + * Caching of code-completion results is a performance optimization that + * introduces some overhead to reparsing but improves the performance of + * code-completion operations. + */ + CXTranslationUnit_CacheCompletionResults = 0x08, + /** + * \brief DEPRECATED: Enable precompiled preambles in C++. + * + * Note: this is a *temporary* option that is available only while + * we are testing C++ precompiled preamble support. It is deprecated. + */ + CXTranslationUnit_CXXPrecompiledPreamble = 0x10, + + /** + * \brief DEPRECATED: Enabled chained precompiled preambles in C++. + * + * Note: this is a *temporary* option that is available only while + * we are testing C++ precompiled preamble support. It is deprecated. + */ + CXTranslationUnit_CXXChainedPCH = 0x20, + + /** + * \brief Used to indicate that function/method bodies should be skipped while + * parsing. + * + * This option can be used to search for declarations/definitions while + * ignoring the usages. + */ + CXTranslationUnit_SkipFunctionBodies = 0x40 +}; + +/** + * \brief Returns the set of flags that is suitable for parsing a translation + * unit that is being edited. + * + * The set of flags returned provide options for \c clang_parseTranslationUnit() + * to indicate that the translation unit is likely to be reparsed many times, + * either explicitly (via \c clang_reparseTranslationUnit()) or implicitly + * (e.g., by code completion (\c clang_codeCompletionAt())). The returned flag + * set contains an unspecified set of optimizations (e.g., the precompiled + * preamble) geared toward improving the performance of these routines. The + * set of optimizations enabled may change from one version to the next. + */ +CINDEX_LINKAGE unsigned clang_defaultEditingTranslationUnitOptions(void); + +/** + * \brief Parse the given source file and the translation unit corresponding + * to that file. + * + * This routine is the main entry point for the Clang C API, providing the + * ability to parse a source file into a translation unit that can then be + * queried by other functions in the API. This routine accepts a set of + * command-line arguments so that the compilation can be configured in the same + * way that the compiler is configured on the command line. + * + * \param CIdx The index object with which the translation unit will be + * associated. + * + * \param source_filename The name of the source file to load, or NULL if the + * source file is included in \p command_line_args. + * + * \param command_line_args The command-line arguments that would be + * passed to the \c clang executable if it were being invoked out-of-process. + * These command-line options will be parsed and will affect how the translation + * unit is parsed. Note that the following options are ignored: '-c', + * '-emit-ast', '-fsyntex-only' (which is the default), and '-o '. + * + * \param num_command_line_args The number of command-line arguments in + * \p command_line_args. + * + * \param unsaved_files the files that have not yet been saved to disk + * but may be required for parsing, including the contents of + * those files. The contents and name of these files (as specified by + * CXUnsavedFile) are copied when necessary, so the client only needs to + * guarantee their validity until the call to this function returns. + * + * \param num_unsaved_files the number of unsaved file entries in \p + * unsaved_files. + * + * \param options A bitmask of options that affects how the translation unit + * is managed but not its compilation. This should be a bitwise OR of the + * CXTranslationUnit_XXX flags. + * + * \returns A new translation unit describing the parsed code and containing + * any diagnostics produced by the compiler. If there is a failure from which + * the compiler cannot recover, returns NULL. + */ +CINDEX_LINKAGE CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, + const char *source_filename, + const char * const *command_line_args, + int num_command_line_args, + struct CXUnsavedFile *unsaved_files, + unsigned num_unsaved_files, + unsigned options); + +/** + * \brief Flags that control how translation units are saved. + * + * The enumerators in this enumeration type are meant to be bitwise + * ORed together to specify which options should be used when + * saving the translation unit. + */ +enum CXSaveTranslationUnit_Flags { + /** + * \brief Used to indicate that no special saving options are needed. + */ + CXSaveTranslationUnit_None = 0x0 +}; + +/** + * \brief Returns the set of flags that is suitable for saving a translation + * unit. + * + * The set of flags returned provide options for + * \c clang_saveTranslationUnit() by default. The returned flag + * set contains an unspecified set of options that save translation units with + * the most commonly-requested data. + */ +CINDEX_LINKAGE unsigned clang_defaultSaveOptions(CXTranslationUnit TU); + +/** + * \brief Describes the kind of error that occurred (if any) in a call to + * \c clang_saveTranslationUnit(). + */ +enum CXSaveError { + /** + * \brief Indicates that no error occurred while saving a translation unit. + */ + CXSaveError_None = 0, + + /** + * \brief Indicates that an unknown error occurred while attempting to save + * the file. + * + * This error typically indicates that file I/O failed when attempting to + * write the file. + */ + CXSaveError_Unknown = 1, + + /** + * \brief Indicates that errors during translation prevented this attempt + * to save the translation unit. + * + * Errors that prevent the translation unit from being saved can be + * extracted using \c clang_getNumDiagnostics() and \c clang_getDiagnostic(). + */ + CXSaveError_TranslationErrors = 2, + + /** + * \brief Indicates that the translation unit to be saved was somehow + * invalid (e.g., NULL). + */ + CXSaveError_InvalidTU = 3 +}; + +/** + * \brief Saves a translation unit into a serialized representation of + * that translation unit on disk. + * + * Any translation unit that was parsed without error can be saved + * into a file. The translation unit can then be deserialized into a + * new \c CXTranslationUnit with \c clang_createTranslationUnit() or, + * if it is an incomplete translation unit that corresponds to a + * header, used as a precompiled header when parsing other translation + * units. + * + * \param TU The translation unit to save. + * + * \param FileName The file to which the translation unit will be saved. + * + * \param options A bitmask of options that affects how the translation unit + * is saved. This should be a bitwise OR of the + * CXSaveTranslationUnit_XXX flags. + * + * \returns A value that will match one of the enumerators of the CXSaveError + * enumeration. Zero (CXSaveError_None) indicates that the translation unit was + * saved successfully, while a non-zero value indicates that a problem occurred. + */ +CINDEX_LINKAGE int clang_saveTranslationUnit(CXTranslationUnit TU, + const char *FileName, + unsigned options); + +/** + * \brief Destroy the specified CXTranslationUnit object. + */ +CINDEX_LINKAGE void clang_disposeTranslationUnit(CXTranslationUnit); + +/** + * \brief Flags that control the reparsing of translation units. + * + * The enumerators in this enumeration type are meant to be bitwise + * ORed together to specify which options should be used when + * reparsing the translation unit. + */ +enum CXReparse_Flags { + /** + * \brief Used to indicate that no special reparsing options are needed. + */ + CXReparse_None = 0x0 +}; + +/** + * \brief Returns the set of flags that is suitable for reparsing a translation + * unit. + * + * The set of flags returned provide options for + * \c clang_reparseTranslationUnit() by default. The returned flag + * set contains an unspecified set of optimizations geared toward common uses + * of reparsing. The set of optimizations enabled may change from one version + * to the next. + */ +CINDEX_LINKAGE unsigned clang_defaultReparseOptions(CXTranslationUnit TU); + +/** + * \brief Reparse the source files that produced this translation unit. + * + * This routine can be used to re-parse the source files that originally + * created the given translation unit, for example because those source files + * have changed (either on disk or as passed via \p unsaved_files). The + * source code will be reparsed with the same command-line options as it + * was originally parsed. + * + * Reparsing a translation unit invalidates all cursors and source locations + * that refer into that translation unit. This makes reparsing a translation + * unit semantically equivalent to destroying the translation unit and then + * creating a new translation unit with the same command-line arguments. + * However, it may be more efficient to reparse a translation + * unit using this routine. + * + * \param TU The translation unit whose contents will be re-parsed. The + * translation unit must originally have been built with + * \c clang_createTranslationUnitFromSourceFile(). + * + * \param num_unsaved_files The number of unsaved file entries in \p + * unsaved_files. + * + * \param unsaved_files The files that have not yet been saved to disk + * but may be required for parsing, including the contents of + * those files. The contents and name of these files (as specified by + * CXUnsavedFile) are copied when necessary, so the client only needs to + * guarantee their validity until the call to this function returns. + * + * \param options A bitset of options composed of the flags in CXReparse_Flags. + * The function \c clang_defaultReparseOptions() produces a default set of + * options recommended for most uses, based on the translation unit. + * + * \returns 0 if the sources could be reparsed. A non-zero value will be + * returned if reparsing was impossible, such that the translation unit is + * invalid. In such cases, the only valid call for \p TU is + * \c clang_disposeTranslationUnit(TU). + */ +CINDEX_LINKAGE int clang_reparseTranslationUnit(CXTranslationUnit TU, + unsigned num_unsaved_files, + struct CXUnsavedFile *unsaved_files, + unsigned options); + +/** + * \brief Categorizes how memory is being used by a translation unit. + */ +enum CXTUResourceUsageKind { + CXTUResourceUsage_AST = 1, + CXTUResourceUsage_Identifiers = 2, + CXTUResourceUsage_Selectors = 3, + CXTUResourceUsage_GlobalCompletionResults = 4, + CXTUResourceUsage_SourceManagerContentCache = 5, + CXTUResourceUsage_AST_SideTables = 6, + CXTUResourceUsage_SourceManager_Membuffer_Malloc = 7, + CXTUResourceUsage_SourceManager_Membuffer_MMap = 8, + CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc = 9, + CXTUResourceUsage_ExternalASTSource_Membuffer_MMap = 10, + CXTUResourceUsage_Preprocessor = 11, + CXTUResourceUsage_PreprocessingRecord = 12, + CXTUResourceUsage_SourceManager_DataStructures = 13, + CXTUResourceUsage_Preprocessor_HeaderSearch = 14, + CXTUResourceUsage_MEMORY_IN_BYTES_BEGIN = CXTUResourceUsage_AST, + CXTUResourceUsage_MEMORY_IN_BYTES_END = + CXTUResourceUsage_Preprocessor_HeaderSearch, + + CXTUResourceUsage_First = CXTUResourceUsage_AST, + CXTUResourceUsage_Last = CXTUResourceUsage_Preprocessor_HeaderSearch +}; + +/** + * \brief Returns the human-readable null-terminated C string that represents + * the name of the memory category. This string should never be freed. + */ +CINDEX_LINKAGE +const char *clang_getTUResourceUsageName(enum CXTUResourceUsageKind kind); + +typedef struct CXTUResourceUsageEntry { + /* \brief The memory usage category. */ + enum CXTUResourceUsageKind kind; + /* \brief Amount of resources used. + The units will depend on the resource kind. */ + unsigned long amount; +} CXTUResourceUsageEntry; + +/** + * \brief The memory usage of a CXTranslationUnit, broken into categories. + */ +typedef struct CXTUResourceUsage { + /* \brief Private data member, used for queries. */ + void *data; + + /* \brief The number of entries in the 'entries' array. */ + unsigned numEntries; + + /* \brief An array of key-value pairs, representing the breakdown of memory + usage. */ + CXTUResourceUsageEntry *entries; + +} CXTUResourceUsage; + +/** + * \brief Return the memory usage of a translation unit. This object + * should be released with clang_disposeCXTUResourceUsage(). + */ +CINDEX_LINKAGE CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU); + +CINDEX_LINKAGE void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage); + +/** + * @} + */ + +/** + * \brief Describes the kind of entity that a cursor refers to. + */ +enum CXCursorKind { + /* Declarations */ + /** + * \brief A declaration whose specific kind is not exposed via this + * interface. + * + * Unexposed declarations have the same operations as any other kind + * of declaration; one can extract their location information, + * spelling, find their definitions, etc. However, the specific kind + * of the declaration is not reported. + */ + CXCursor_UnexposedDecl = 1, + /** \brief A C or C++ struct. */ + CXCursor_StructDecl = 2, + /** \brief A C or C++ union. */ + CXCursor_UnionDecl = 3, + /** \brief A C++ class. */ + CXCursor_ClassDecl = 4, + /** \brief An enumeration. */ + CXCursor_EnumDecl = 5, + /** + * \brief A field (in C) or non-static data member (in C++) in a + * struct, union, or C++ class. + */ + CXCursor_FieldDecl = 6, + /** \brief An enumerator constant. */ + CXCursor_EnumConstantDecl = 7, + /** \brief A function. */ + CXCursor_FunctionDecl = 8, + /** \brief A variable. */ + CXCursor_VarDecl = 9, + /** \brief A function or method parameter. */ + CXCursor_ParmDecl = 10, + /** \brief An Objective-C @interface. */ + CXCursor_ObjCInterfaceDecl = 11, + /** \brief An Objective-C @interface for a category. */ + CXCursor_ObjCCategoryDecl = 12, + /** \brief An Objective-C @protocol declaration. */ + CXCursor_ObjCProtocolDecl = 13, + /** \brief An Objective-C @property declaration. */ + CXCursor_ObjCPropertyDecl = 14, + /** \brief An Objective-C instance variable. */ + CXCursor_ObjCIvarDecl = 15, + /** \brief An Objective-C instance method. */ + CXCursor_ObjCInstanceMethodDecl = 16, + /** \brief An Objective-C class method. */ + CXCursor_ObjCClassMethodDecl = 17, + /** \brief An Objective-C @implementation. */ + CXCursor_ObjCImplementationDecl = 18, + /** \brief An Objective-C @implementation for a category. */ + CXCursor_ObjCCategoryImplDecl = 19, + /** \brief A typedef */ + CXCursor_TypedefDecl = 20, + /** \brief A C++ class method. */ + CXCursor_CXXMethod = 21, + /** \brief A C++ namespace. */ + CXCursor_Namespace = 22, + /** \brief A linkage specification, e.g. 'extern "C"'. */ + CXCursor_LinkageSpec = 23, + /** \brief A C++ constructor. */ + CXCursor_Constructor = 24, + /** \brief A C++ destructor. */ + CXCursor_Destructor = 25, + /** \brief A C++ conversion function. */ + CXCursor_ConversionFunction = 26, + /** \brief A C++ template type parameter. */ + CXCursor_TemplateTypeParameter = 27, + /** \brief A C++ non-type template parameter. */ + CXCursor_NonTypeTemplateParameter = 28, + /** \brief A C++ template template parameter. */ + CXCursor_TemplateTemplateParameter = 29, + /** \brief A C++ function template. */ + CXCursor_FunctionTemplate = 30, + /** \brief A C++ class template. */ + CXCursor_ClassTemplate = 31, + /** \brief A C++ class template partial specialization. */ + CXCursor_ClassTemplatePartialSpecialization = 32, + /** \brief A C++ namespace alias declaration. */ + CXCursor_NamespaceAlias = 33, + /** \brief A C++ using directive. */ + CXCursor_UsingDirective = 34, + /** \brief A C++ using declaration. */ + CXCursor_UsingDeclaration = 35, + /** \brief A C++ alias declaration */ + CXCursor_TypeAliasDecl = 36, + /** \brief An Objective-C @synthesize definition. */ + CXCursor_ObjCSynthesizeDecl = 37, + /** \brief An Objective-C @dynamic definition. */ + CXCursor_ObjCDynamicDecl = 38, + /** \brief An access specifier. */ + CXCursor_CXXAccessSpecifier = 39, + + CXCursor_FirstDecl = CXCursor_UnexposedDecl, + CXCursor_LastDecl = CXCursor_CXXAccessSpecifier, + + /* References */ + CXCursor_FirstRef = 40, /* Decl references */ + CXCursor_ObjCSuperClassRef = 40, + CXCursor_ObjCProtocolRef = 41, + CXCursor_ObjCClassRef = 42, + /** + * \brief A reference to a type declaration. + * + * A type reference occurs anywhere where a type is named but not + * declared. For example, given: + * + * \code + * typedef unsigned size_type; + * size_type size; + * \endcode + * + * The typedef is a declaration of size_type (CXCursor_TypedefDecl), + * while the type of the variable "size" is referenced. The cursor + * referenced by the type of size is the typedef for size_type. + */ + CXCursor_TypeRef = 43, + CXCursor_CXXBaseSpecifier = 44, + /** + * \brief A reference to a class template, function template, template + * template parameter, or class template partial specialization. + */ + CXCursor_TemplateRef = 45, + /** + * \brief A reference to a namespace or namespace alias. + */ + CXCursor_NamespaceRef = 46, + /** + * \brief A reference to a member of a struct, union, or class that occurs in + * some non-expression context, e.g., a designated initializer. + */ + CXCursor_MemberRef = 47, + /** + * \brief A reference to a labeled statement. + * + * This cursor kind is used to describe the jump to "start_over" in the + * goto statement in the following example: + * + * \code + * start_over: + * ++counter; + * + * goto start_over; + * \endcode + * + * A label reference cursor refers to a label statement. + */ + CXCursor_LabelRef = 48, + + /** + * \brief A reference to a set of overloaded functions or function templates + * that has not yet been resolved to a specific function or function template. + * + * An overloaded declaration reference cursor occurs in C++ templates where + * a dependent name refers to a function. For example: + * + * \code + * template void swap(T&, T&); + * + * struct X { ... }; + * void swap(X&, X&); + * + * template + * void reverse(T* first, T* last) { + * while (first < last - 1) { + * swap(*first, *--last); + * ++first; + * } + * } + * + * struct Y { }; + * void swap(Y&, Y&); + * \endcode + * + * Here, the identifier "swap" is associated with an overloaded declaration + * reference. In the template definition, "swap" refers to either of the two + * "swap" functions declared above, so both results will be available. At + * instantiation time, "swap" may also refer to other functions found via + * argument-dependent lookup (e.g., the "swap" function at the end of the + * example). + * + * The functions \c clang_getNumOverloadedDecls() and + * \c clang_getOverloadedDecl() can be used to retrieve the definitions + * referenced by this cursor. + */ + CXCursor_OverloadedDeclRef = 49, + + /** + * \brief A reference to a variable that occurs in some non-expression + * context, e.g., a C++ lambda capture list. + */ + CXCursor_VariableRef = 50, + + CXCursor_LastRef = CXCursor_VariableRef, + + /* Error conditions */ + CXCursor_FirstInvalid = 70, + CXCursor_InvalidFile = 70, + CXCursor_NoDeclFound = 71, + CXCursor_NotImplemented = 72, + CXCursor_InvalidCode = 73, + CXCursor_LastInvalid = CXCursor_InvalidCode, + + /* Expressions */ + CXCursor_FirstExpr = 100, + + /** + * \brief An expression whose specific kind is not exposed via this + * interface. + * + * Unexposed expressions have the same operations as any other kind + * of expression; one can extract their location information, + * spelling, children, etc. However, the specific kind of the + * expression is not reported. + */ + CXCursor_UnexposedExpr = 100, + + /** + * \brief An expression that refers to some value declaration, such + * as a function, varible, or enumerator. + */ + CXCursor_DeclRefExpr = 101, + + /** + * \brief An expression that refers to a member of a struct, union, + * class, Objective-C class, etc. + */ + CXCursor_MemberRefExpr = 102, + + /** \brief An expression that calls a function. */ + CXCursor_CallExpr = 103, + + /** \brief An expression that sends a message to an Objective-C + object or class. */ + CXCursor_ObjCMessageExpr = 104, + + /** \brief An expression that represents a block literal. */ + CXCursor_BlockExpr = 105, + + /** \brief An integer literal. + */ + CXCursor_IntegerLiteral = 106, + + /** \brief A floating point number literal. + */ + CXCursor_FloatingLiteral = 107, + + /** \brief An imaginary number literal. + */ + CXCursor_ImaginaryLiteral = 108, + + /** \brief A string literal. + */ + CXCursor_StringLiteral = 109, + + /** \brief A character literal. + */ + CXCursor_CharacterLiteral = 110, + + /** \brief A parenthesized expression, e.g. "(1)". + * + * This AST node is only formed if full location information is requested. + */ + CXCursor_ParenExpr = 111, + + /** \brief This represents the unary-expression's (except sizeof and + * alignof). + */ + CXCursor_UnaryOperator = 112, + + /** \brief [C99 6.5.2.1] Array Subscripting. + */ + CXCursor_ArraySubscriptExpr = 113, + + /** \brief A builtin binary operation expression such as "x + y" or + * "x <= y". + */ + CXCursor_BinaryOperator = 114, + + /** \brief Compound assignment such as "+=". + */ + CXCursor_CompoundAssignOperator = 115, + + /** \brief The ?: ternary operator. + */ + CXCursor_ConditionalOperator = 116, + + /** \brief An explicit cast in C (C99 6.5.4) or a C-style cast in C++ + * (C++ [expr.cast]), which uses the syntax (Type)expr. + * + * For example: (int)f. + */ + CXCursor_CStyleCastExpr = 117, + + /** \brief [C99 6.5.2.5] + */ + CXCursor_CompoundLiteralExpr = 118, + + /** \brief Describes an C or C++ initializer list. + */ + CXCursor_InitListExpr = 119, + + /** \brief The GNU address of label extension, representing &&label. + */ + CXCursor_AddrLabelExpr = 120, + + /** \brief This is the GNU Statement Expression extension: ({int X=4; X;}) + */ + CXCursor_StmtExpr = 121, + + /** \brief Represents a C11 generic selection. + */ + CXCursor_GenericSelectionExpr = 122, + + /** \brief Implements the GNU __null extension, which is a name for a null + * pointer constant that has integral type (e.g., int or long) and is the same + * size and alignment as a pointer. + * + * The __null extension is typically only used by system headers, which define + * NULL as __null in C++ rather than using 0 (which is an integer that may not + * match the size of a pointer). + */ + CXCursor_GNUNullExpr = 123, + + /** \brief C++'s static_cast<> expression. + */ + CXCursor_CXXStaticCastExpr = 124, + + /** \brief C++'s dynamic_cast<> expression. + */ + CXCursor_CXXDynamicCastExpr = 125, + + /** \brief C++'s reinterpret_cast<> expression. + */ + CXCursor_CXXReinterpretCastExpr = 126, + + /** \brief C++'s const_cast<> expression. + */ + CXCursor_CXXConstCastExpr = 127, + + /** \brief Represents an explicit C++ type conversion that uses "functional" + * notion (C++ [expr.type.conv]). + * + * Example: + * \code + * x = int(0.5); + * \endcode + */ + CXCursor_CXXFunctionalCastExpr = 128, + + /** \brief A C++ typeid expression (C++ [expr.typeid]). + */ + CXCursor_CXXTypeidExpr = 129, + + /** \brief [C++ 2.13.5] C++ Boolean Literal. + */ + CXCursor_CXXBoolLiteralExpr = 130, + + /** \brief [C++0x 2.14.7] C++ Pointer Literal. + */ + CXCursor_CXXNullPtrLiteralExpr = 131, + + /** \brief Represents the "this" expression in C++ + */ + CXCursor_CXXThisExpr = 132, + + /** \brief [C++ 15] C++ Throw Expression. + * + * This handles 'throw' and 'throw' assignment-expression. When + * assignment-expression isn't present, Op will be null. + */ + CXCursor_CXXThrowExpr = 133, + + /** \brief A new expression for memory allocation and constructor calls, e.g: + * "new CXXNewExpr(foo)". + */ + CXCursor_CXXNewExpr = 134, + + /** \brief A delete expression for memory deallocation and destructor calls, + * e.g. "delete[] pArray". + */ + CXCursor_CXXDeleteExpr = 135, + + /** \brief A unary expression. + */ + CXCursor_UnaryExpr = 136, + + /** \brief An Objective-C string literal i.e. @"foo". + */ + CXCursor_ObjCStringLiteral = 137, + + /** \brief An Objective-C @encode expression. + */ + CXCursor_ObjCEncodeExpr = 138, + + /** \brief An Objective-C @selector expression. + */ + CXCursor_ObjCSelectorExpr = 139, + + /** \brief An Objective-C @protocol expression. + */ + CXCursor_ObjCProtocolExpr = 140, + + /** \brief An Objective-C "bridged" cast expression, which casts between + * Objective-C pointers and C pointers, transferring ownership in the process. + * + * \code + * NSString *str = (__bridge_transfer NSString *)CFCreateString(); + * \endcode + */ + CXCursor_ObjCBridgedCastExpr = 141, + + /** \brief Represents a C++0x pack expansion that produces a sequence of + * expressions. + * + * A pack expansion expression contains a pattern (which itself is an + * expression) followed by an ellipsis. For example: + * + * \code + * template + * void forward(F f, Types &&...args) { + * f(static_cast(args)...); + * } + * \endcode + */ + CXCursor_PackExpansionExpr = 142, + + /** \brief Represents an expression that computes the length of a parameter + * pack. + * + * \code + * template + * struct count { + * static const unsigned value = sizeof...(Types); + * }; + * \endcode + */ + CXCursor_SizeOfPackExpr = 143, + + /* \brief Represents a C++ lambda expression that produces a local function + * object. + * + * \code + * void abssort(float *x, unsigned N) { + * std::sort(x, x + N, + * [](float a, float b) { + * return std::abs(a) < std::abs(b); + * }); + * } + * \endcode + */ + CXCursor_LambdaExpr = 144, + + /** \brief Objective-c Boolean Literal. + */ + CXCursor_ObjCBoolLiteralExpr = 145, + + CXCursor_LastExpr = CXCursor_ObjCBoolLiteralExpr, + + /* Statements */ + CXCursor_FirstStmt = 200, + /** + * \brief A statement whose specific kind is not exposed via this + * interface. + * + * Unexposed statements have the same operations as any other kind of + * statement; one can extract their location information, spelling, + * children, etc. However, the specific kind of the statement is not + * reported. + */ + CXCursor_UnexposedStmt = 200, + + /** \brief A labelled statement in a function. + * + * This cursor kind is used to describe the "start_over:" label statement in + * the following example: + * + * \code + * start_over: + * ++counter; + * \endcode + * + */ + CXCursor_LabelStmt = 201, + + /** \brief A group of statements like { stmt stmt }. + * + * This cursor kind is used to describe compound statements, e.g. function + * bodies. + */ + CXCursor_CompoundStmt = 202, + + /** \brief A case statment. + */ + CXCursor_CaseStmt = 203, + + /** \brief A default statement. + */ + CXCursor_DefaultStmt = 204, + + /** \brief An if statement + */ + CXCursor_IfStmt = 205, + + /** \brief A switch statement. + */ + CXCursor_SwitchStmt = 206, + + /** \brief A while statement. + */ + CXCursor_WhileStmt = 207, + + /** \brief A do statement. + */ + CXCursor_DoStmt = 208, + + /** \brief A for statement. + */ + CXCursor_ForStmt = 209, + + /** \brief A goto statement. + */ + CXCursor_GotoStmt = 210, + + /** \brief An indirect goto statement. + */ + CXCursor_IndirectGotoStmt = 211, + + /** \brief A continue statement. + */ + CXCursor_ContinueStmt = 212, + + /** \brief A break statement. + */ + CXCursor_BreakStmt = 213, + + /** \brief A return statement. + */ + CXCursor_ReturnStmt = 214, + + /** \brief A GNU inline assembly statement extension. + */ + CXCursor_AsmStmt = 215, + + /** \brief Objective-C's overall @try-@catch-@finally statement. + */ + CXCursor_ObjCAtTryStmt = 216, + + /** \brief Objective-C's @catch statement. + */ + CXCursor_ObjCAtCatchStmt = 217, + + /** \brief Objective-C's @finally statement. + */ + CXCursor_ObjCAtFinallyStmt = 218, + + /** \brief Objective-C's @throw statement. + */ + CXCursor_ObjCAtThrowStmt = 219, + + /** \brief Objective-C's @synchronized statement. + */ + CXCursor_ObjCAtSynchronizedStmt = 220, + + /** \brief Objective-C's autorelease pool statement. + */ + CXCursor_ObjCAutoreleasePoolStmt = 221, + + /** \brief Objective-C's collection statement. + */ + CXCursor_ObjCForCollectionStmt = 222, + + /** \brief C++'s catch statement. + */ + CXCursor_CXXCatchStmt = 223, + + /** \brief C++'s try statement. + */ + CXCursor_CXXTryStmt = 224, + + /** \brief C++'s for (* : *) statement. + */ + CXCursor_CXXForRangeStmt = 225, + + /** \brief Windows Structured Exception Handling's try statement. + */ + CXCursor_SEHTryStmt = 226, + + /** \brief Windows Structured Exception Handling's except statement. + */ + CXCursor_SEHExceptStmt = 227, + + /** \brief Windows Structured Exception Handling's finally statement. + */ + CXCursor_SEHFinallyStmt = 228, + + /** \brief The null satement ";": C99 6.8.3p3. + * + * This cursor kind is used to describe the null statement. + */ + CXCursor_NullStmt = 230, + + /** \brief Adaptor class for mixing declarations with statements and + * expressions. + */ + CXCursor_DeclStmt = 231, + + CXCursor_LastStmt = CXCursor_DeclStmt, + + /** + * \brief Cursor that represents the translation unit itself. + * + * The translation unit cursor exists primarily to act as the root + * cursor for traversing the contents of a translation unit. + */ + CXCursor_TranslationUnit = 300, + + /* Attributes */ + CXCursor_FirstAttr = 400, + /** + * \brief An attribute whose specific kind is not exposed via this + * interface. + */ + CXCursor_UnexposedAttr = 400, + + CXCursor_IBActionAttr = 401, + CXCursor_IBOutletAttr = 402, + CXCursor_IBOutletCollectionAttr = 403, + CXCursor_CXXFinalAttr = 404, + CXCursor_CXXOverrideAttr = 405, + CXCursor_AnnotateAttr = 406, + CXCursor_AsmLabelAttr = 407, + CXCursor_LastAttr = CXCursor_AsmLabelAttr, + + /* Preprocessing */ + CXCursor_PreprocessingDirective = 500, + CXCursor_MacroDefinition = 501, + CXCursor_MacroExpansion = 502, + CXCursor_MacroInstantiation = CXCursor_MacroExpansion, + CXCursor_InclusionDirective = 503, + CXCursor_FirstPreprocessing = CXCursor_PreprocessingDirective, + CXCursor_LastPreprocessing = CXCursor_InclusionDirective +}; + +/** + * \brief A cursor representing some element in the abstract syntax tree for + * a translation unit. + * + * The cursor abstraction unifies the different kinds of entities in a + * program--declaration, statements, expressions, references to declarations, + * etc.--under a single "cursor" abstraction with a common set of operations. + * Common operation for a cursor include: getting the physical location in + * a source file where the cursor points, getting the name associated with a + * cursor, and retrieving cursors for any child nodes of a particular cursor. + * + * Cursors can be produced in two specific ways. + * clang_getTranslationUnitCursor() produces a cursor for a translation unit, + * from which one can use clang_visitChildren() to explore the rest of the + * translation unit. clang_getCursor() maps from a physical source location + * to the entity that resides at that location, allowing one to map from the + * source code into the AST. + */ +typedef struct { + enum CXCursorKind kind; + int xdata; + void *data[3]; +} CXCursor; + +/** + * \defgroup CINDEX_CURSOR_MANIP Cursor manipulations + * + * @{ + */ + +/** + * \brief Retrieve the NULL cursor, which represents no entity. + */ +CINDEX_LINKAGE CXCursor clang_getNullCursor(void); + +/** + * \brief Retrieve the cursor that represents the given translation unit. + * + * The translation unit cursor can be used to start traversing the + * various declarations within the given translation unit. + */ +CINDEX_LINKAGE CXCursor clang_getTranslationUnitCursor(CXTranslationUnit); + +/** + * \brief Determine whether two cursors are equivalent. + */ +CINDEX_LINKAGE unsigned clang_equalCursors(CXCursor, CXCursor); + +/** + * \brief Returns non-zero if \arg cursor is null. + */ +CINDEX_LINKAGE int clang_Cursor_isNull(CXCursor); + +/** + * \brief Compute a hash value for the given cursor. + */ +CINDEX_LINKAGE unsigned clang_hashCursor(CXCursor); + +/** + * \brief Retrieve the kind of the given cursor. + */ +CINDEX_LINKAGE enum CXCursorKind clang_getCursorKind(CXCursor); + +/** + * \brief Determine whether the given cursor kind represents a declaration. + */ +CINDEX_LINKAGE unsigned clang_isDeclaration(enum CXCursorKind); + +/** + * \brief Determine whether the given cursor kind represents a simple + * reference. + * + * Note that other kinds of cursors (such as expressions) can also refer to + * other cursors. Use clang_getCursorReferenced() to determine whether a + * particular cursor refers to another entity. + */ +CINDEX_LINKAGE unsigned clang_isReference(enum CXCursorKind); + +/** + * \brief Determine whether the given cursor kind represents an expression. + */ +CINDEX_LINKAGE unsigned clang_isExpression(enum CXCursorKind); + +/** + * \brief Determine whether the given cursor kind represents a statement. + */ +CINDEX_LINKAGE unsigned clang_isStatement(enum CXCursorKind); + +/** + * \brief Determine whether the given cursor kind represents an attribute. + */ +CINDEX_LINKAGE unsigned clang_isAttribute(enum CXCursorKind); + +/** + * \brief Determine whether the given cursor kind represents an invalid + * cursor. + */ +CINDEX_LINKAGE unsigned clang_isInvalid(enum CXCursorKind); + +/** + * \brief Determine whether the given cursor kind represents a translation + * unit. + */ +CINDEX_LINKAGE unsigned clang_isTranslationUnit(enum CXCursorKind); + +/*** + * \brief Determine whether the given cursor represents a preprocessing + * element, such as a preprocessor directive or macro instantiation. + */ +CINDEX_LINKAGE unsigned clang_isPreprocessing(enum CXCursorKind); + +/*** + * \brief Determine whether the given cursor represents a currently + * unexposed piece of the AST (e.g., CXCursor_UnexposedStmt). + */ +CINDEX_LINKAGE unsigned clang_isUnexposed(enum CXCursorKind); + +/** + * \brief Describe the linkage of the entity referred to by a cursor. + */ +enum CXLinkageKind { + /** \brief This value indicates that no linkage information is available + * for a provided CXCursor. */ + CXLinkage_Invalid, + /** + * \brief This is the linkage for variables, parameters, and so on that + * have automatic storage. This covers normal (non-extern) local variables. + */ + CXLinkage_NoLinkage, + /** \brief This is the linkage for static variables and static functions. */ + CXLinkage_Internal, + /** \brief This is the linkage for entities with external linkage that live + * in C++ anonymous namespaces.*/ + CXLinkage_UniqueExternal, + /** \brief This is the linkage for entities with true, external linkage. */ + CXLinkage_External +}; + +/** + * \brief Determine the linkage of the entity referred to by a given cursor. + */ +CINDEX_LINKAGE enum CXLinkageKind clang_getCursorLinkage(CXCursor cursor); + +/** + * \brief Determine the availability of the entity that this cursor refers to. + * + * \param cursor The cursor to query. + * + * \returns The availability of the cursor. + */ +CINDEX_LINKAGE enum CXAvailabilityKind +clang_getCursorAvailability(CXCursor cursor); + +/** + * \brief Describe the "language" of the entity referred to by a cursor. + */ +CINDEX_LINKAGE enum CXLanguageKind { + CXLanguage_Invalid = 0, + CXLanguage_C, + CXLanguage_ObjC, + CXLanguage_CPlusPlus +}; + +/** + * \brief Determine the "language" of the entity referred to by a given cursor. + */ +CINDEX_LINKAGE enum CXLanguageKind clang_getCursorLanguage(CXCursor cursor); + +/** + * \brief Returns the translation unit that a cursor originated from. + */ +CINDEX_LINKAGE CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor); + + +/** + * \brief A fast container representing a set of CXCursors. + */ +typedef struct CXCursorSetImpl *CXCursorSet; + +/** + * \brief Creates an empty CXCursorSet. + */ +CINDEX_LINKAGE CXCursorSet clang_createCXCursorSet(); + +/** + * \brief Disposes a CXCursorSet and releases its associated memory. + */ +CINDEX_LINKAGE void clang_disposeCXCursorSet(CXCursorSet cset); + +/** + * \brief Queries a CXCursorSet to see if it contains a specific CXCursor. + * + * \returns non-zero if the set contains the specified cursor. +*/ +CINDEX_LINKAGE unsigned clang_CXCursorSet_contains(CXCursorSet cset, + CXCursor cursor); + +/** + * \brief Inserts a CXCursor into a CXCursorSet. + * + * \returns zero if the CXCursor was already in the set, and non-zero otherwise. +*/ +CINDEX_LINKAGE unsigned clang_CXCursorSet_insert(CXCursorSet cset, + CXCursor cursor); + +/** + * \brief Determine the semantic parent of the given cursor. + * + * The semantic parent of a cursor is the cursor that semantically contains + * the given \p cursor. For many declarations, the lexical and semantic parents + * are equivalent (the lexical parent is returned by + * \c clang_getCursorLexicalParent()). They diverge when declarations or + * definitions are provided out-of-line. For example: + * + * \code + * class C { + * void f(); + * }; + * + * void C::f() { } + * \endcode + * + * In the out-of-line definition of \c C::f, the semantic parent is the + * the class \c C, of which this function is a member. The lexical parent is + * the place where the declaration actually occurs in the source code; in this + * case, the definition occurs in the translation unit. In general, the + * lexical parent for a given entity can change without affecting the semantics + * of the program, and the lexical parent of different declarations of the + * same entity may be different. Changing the semantic parent of a declaration, + * on the other hand, can have a major impact on semantics, and redeclarations + * of a particular entity should all have the same semantic context. + * + * In the example above, both declarations of \c C::f have \c C as their + * semantic context, while the lexical context of the first \c C::f is \c C + * and the lexical context of the second \c C::f is the translation unit. + * + * For global declarations, the semantic parent is the translation unit. + */ +CINDEX_LINKAGE CXCursor clang_getCursorSemanticParent(CXCursor cursor); + +/** + * \brief Determine the lexical parent of the given cursor. + * + * The lexical parent of a cursor is the cursor in which the given \p cursor + * was actually written. For many declarations, the lexical and semantic parents + * are equivalent (the semantic parent is returned by + * \c clang_getCursorSemanticParent()). They diverge when declarations or + * definitions are provided out-of-line. For example: + * + * \code + * class C { + * void f(); + * }; + * + * void C::f() { } + * \endcode + * + * In the out-of-line definition of \c C::f, the semantic parent is the + * the class \c C, of which this function is a member. The lexical parent is + * the place where the declaration actually occurs in the source code; in this + * case, the definition occurs in the translation unit. In general, the + * lexical parent for a given entity can change without affecting the semantics + * of the program, and the lexical parent of different declarations of the + * same entity may be different. Changing the semantic parent of a declaration, + * on the other hand, can have a major impact on semantics, and redeclarations + * of a particular entity should all have the same semantic context. + * + * In the example above, both declarations of \c C::f have \c C as their + * semantic context, while the lexical context of the first \c C::f is \c C + * and the lexical context of the second \c C::f is the translation unit. + * + * For declarations written in the global scope, the lexical parent is + * the translation unit. + */ +CINDEX_LINKAGE CXCursor clang_getCursorLexicalParent(CXCursor cursor); + +/** + * \brief Determine the set of methods that are overridden by the given + * method. + * + * In both Objective-C and C++, a method (aka virtual member function, + * in C++) can override a virtual method in a base class. For + * Objective-C, a method is said to override any method in the class's + * base class, its protocols, or its categories' protocols, that has the same + * selector and is of the same kind (class or instance). + * If no such method exists, the search continues to the class's superclass, + * its protocols, and its categories, and so on. A method from an Objective-C + * implementation is considered to override the same methods as its + * corresponding method in the interface. + * + * For C++, a virtual member function overrides any virtual member + * function with the same signature that occurs in its base + * classes. With multiple inheritance, a virtual member function can + * override several virtual member functions coming from different + * base classes. + * + * In all cases, this function determines the immediate overridden + * method, rather than all of the overridden methods. For example, if + * a method is originally declared in a class A, then overridden in B + * (which in inherits from A) and also in C (which inherited from B), + * then the only overridden method returned from this function when + * invoked on C's method will be B's method. The client may then + * invoke this function again, given the previously-found overridden + * methods, to map out the complete method-override set. + * + * \param cursor A cursor representing an Objective-C or C++ + * method. This routine will compute the set of methods that this + * method overrides. + * + * \param overridden A pointer whose pointee will be replaced with a + * pointer to an array of cursors, representing the set of overridden + * methods. If there are no overridden methods, the pointee will be + * set to NULL. The pointee must be freed via a call to + * \c clang_disposeOverriddenCursors(). + * + * \param num_overridden A pointer to the number of overridden + * functions, will be set to the number of overridden functions in the + * array pointed to by \p overridden. + */ +CINDEX_LINKAGE void clang_getOverriddenCursors(CXCursor cursor, + CXCursor **overridden, + unsigned *num_overridden); + +/** + * \brief Free the set of overridden cursors returned by \c + * clang_getOverriddenCursors(). + */ +CINDEX_LINKAGE void clang_disposeOverriddenCursors(CXCursor *overridden); + +/** + * \brief Retrieve the file that is included by the given inclusion directive + * cursor. + */ +CINDEX_LINKAGE CXFile clang_getIncludedFile(CXCursor cursor); + +/** + * @} + */ + +/** + * \defgroup CINDEX_CURSOR_SOURCE Mapping between cursors and source code + * + * Cursors represent a location within the Abstract Syntax Tree (AST). These + * routines help map between cursors and the physical locations where the + * described entities occur in the source code. The mapping is provided in + * both directions, so one can map from source code to the AST and back. + * + * @{ + */ + +/** + * \brief Map a source location to the cursor that describes the entity at that + * location in the source code. + * + * clang_getCursor() maps an arbitrary source location within a translation + * unit down to the most specific cursor that describes the entity at that + * location. For example, given an expression \c x + y, invoking + * clang_getCursor() with a source location pointing to "x" will return the + * cursor for "x"; similarly for "y". If the cursor points anywhere between + * "x" or "y" (e.g., on the + or the whitespace around it), clang_getCursor() + * will return a cursor referring to the "+" expression. + * + * \returns a cursor representing the entity at the given source location, or + * a NULL cursor if no such entity can be found. + */ +CINDEX_LINKAGE CXCursor clang_getCursor(CXTranslationUnit, CXSourceLocation); + +/** + * \brief Retrieve the physical location of the source constructor referenced + * by the given cursor. + * + * The location of a declaration is typically the location of the name of that + * declaration, where the name of that declaration would occur if it is + * unnamed, or some keyword that introduces that particular declaration. + * The location of a reference is where that reference occurs within the + * source code. + */ +CINDEX_LINKAGE CXSourceLocation clang_getCursorLocation(CXCursor); + +/** + * \brief Retrieve the physical extent of the source construct referenced by + * the given cursor. + * + * The extent of a cursor starts with the file/line/column pointing at the + * first character within the source construct that the cursor refers to and + * ends with the last character withinin that source construct. For a + * declaration, the extent covers the declaration itself. For a reference, + * the extent covers the location of the reference (e.g., where the referenced + * entity was actually used). + */ +CINDEX_LINKAGE CXSourceRange clang_getCursorExtent(CXCursor); + +/** + * @} + */ + +/** + * \defgroup CINDEX_TYPES Type information for CXCursors + * + * @{ + */ + +/** + * \brief Describes the kind of type + */ +enum CXTypeKind { + /** + * \brief Reprents an invalid type (e.g., where no type is available). + */ + CXType_Invalid = 0, + + /** + * \brief A type whose specific kind is not exposed via this + * interface. + */ + CXType_Unexposed = 1, + + /* Builtin types */ + CXType_Void = 2, + CXType_Bool = 3, + CXType_Char_U = 4, + CXType_UChar = 5, + CXType_Char16 = 6, + CXType_Char32 = 7, + CXType_UShort = 8, + CXType_UInt = 9, + CXType_ULong = 10, + CXType_ULongLong = 11, + CXType_UInt128 = 12, + CXType_Char_S = 13, + CXType_SChar = 14, + CXType_WChar = 15, + CXType_Short = 16, + CXType_Int = 17, + CXType_Long = 18, + CXType_LongLong = 19, + CXType_Int128 = 20, + CXType_Float = 21, + CXType_Double = 22, + CXType_LongDouble = 23, + CXType_NullPtr = 24, + CXType_Overload = 25, + CXType_Dependent = 26, + CXType_ObjCId = 27, + CXType_ObjCClass = 28, + CXType_ObjCSel = 29, + CXType_FirstBuiltin = CXType_Void, + CXType_LastBuiltin = CXType_ObjCSel, + + CXType_Complex = 100, + CXType_Pointer = 101, + CXType_BlockPointer = 102, + CXType_LValueReference = 103, + CXType_RValueReference = 104, + CXType_Record = 105, + CXType_Enum = 106, + CXType_Typedef = 107, + CXType_ObjCInterface = 108, + CXType_ObjCObjectPointer = 109, + CXType_FunctionNoProto = 110, + CXType_FunctionProto = 111, + CXType_ConstantArray = 112, + CXType_Vector = 113 +}; + +/** + * \brief Describes the calling convention of a function type + */ +enum CXCallingConv { + CXCallingConv_Default = 0, + CXCallingConv_C = 1, + CXCallingConv_X86StdCall = 2, + CXCallingConv_X86FastCall = 3, + CXCallingConv_X86ThisCall = 4, + CXCallingConv_X86Pascal = 5, + CXCallingConv_AAPCS = 6, + CXCallingConv_AAPCS_VFP = 7, + + CXCallingConv_Invalid = 100, + CXCallingConv_Unexposed = 200 +}; + + +/** + * \brief The type of an element in the abstract syntax tree. + * + */ +typedef struct { + enum CXTypeKind kind; + void *data[2]; +} CXType; + +/** + * \brief Retrieve the type of a CXCursor (if any). + */ +CINDEX_LINKAGE CXType clang_getCursorType(CXCursor C); + +/** + * \brief Retrieve the underlying type of a typedef declaration. + * + * If the cursor does not reference a typedef declaration, an invalid type is + * returned. + */ +CINDEX_LINKAGE CXType clang_getTypedefDeclUnderlyingType(CXCursor C); + +/** + * \brief Retrieve the integer type of an enum declaration. + * + * If the cursor does not reference an enum declaration, an invalid type is + * returned. + */ +CINDEX_LINKAGE CXType clang_getEnumDeclIntegerType(CXCursor C); + +/** + * \brief Retrieve the integer value of an enum constant declaration as a signed + * long long. + * + * If the cursor does not reference an enum constant declaration, LLONG_MIN is returned. + * Since this is also potentially a valid constant value, the kind of the cursor + * must be verified before calling this function. + */ +CINDEX_LINKAGE long long clang_getEnumConstantDeclValue(CXCursor C); + +/** + * \brief Retrieve the integer value of an enum constant declaration as an unsigned + * long long. + * + * If the cursor does not reference an enum constant declaration, ULLONG_MAX is returned. + * Since this is also potentially a valid constant value, the kind of the cursor + * must be verified before calling this function. + */ +CINDEX_LINKAGE unsigned long long clang_getEnumConstantDeclUnsignedValue(CXCursor C); + +/** + * \brief Retrieve the number of non-variadic arguments associated with a given + * cursor. + * + * If a cursor that is not a function or method is passed in, -1 is returned. + */ +CINDEX_LINKAGE int clang_Cursor_getNumArguments(CXCursor C); + +/** + * \brief Retrieve the argument cursor of a function or method. + * + * If a cursor that is not a function or method is passed in or the index + * exceeds the number of arguments, an invalid cursor is returned. + */ +CINDEX_LINKAGE CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i); + +/** + * \determine Determine whether two CXTypes represent the same type. + * + * \returns non-zero if the CXTypes represent the same type and + zero otherwise. + */ +CINDEX_LINKAGE unsigned clang_equalTypes(CXType A, CXType B); + +/** + * \brief Return the canonical type for a CXType. + * + * Clang's type system explicitly models typedefs and all the ways + * a specific type can be represented. The canonical type is the underlying + * type with all the "sugar" removed. For example, if 'T' is a typedef + * for 'int', the canonical type for 'T' would be 'int'. + */ +CINDEX_LINKAGE CXType clang_getCanonicalType(CXType T); + +/** + * \determine Determine whether a CXType has the "const" qualifier set, + * without looking through typedefs that may have added "const" at a different level. + */ +CINDEX_LINKAGE unsigned clang_isConstQualifiedType(CXType T); + +/** + * \determine Determine whether a CXType has the "volatile" qualifier set, + * without looking through typedefs that may have added "volatile" at a different level. + */ +CINDEX_LINKAGE unsigned clang_isVolatileQualifiedType(CXType T); + +/** + * \determine Determine whether a CXType has the "restrict" qualifier set, + * without looking through typedefs that may have added "restrict" at a different level. + */ +CINDEX_LINKAGE unsigned clang_isRestrictQualifiedType(CXType T); + +/** + * \brief For pointer types, returns the type of the pointee. + * + */ +CINDEX_LINKAGE CXType clang_getPointeeType(CXType T); + +/** + * \brief Return the cursor for the declaration of the given type. + */ +CINDEX_LINKAGE CXCursor clang_getTypeDeclaration(CXType T); + +/** + * Returns the Objective-C type encoding for the specified declaration. + */ +CINDEX_LINKAGE CXString clang_getDeclObjCTypeEncoding(CXCursor C); + +/** + * \brief Retrieve the spelling of a given CXTypeKind. + */ +CINDEX_LINKAGE CXString clang_getTypeKindSpelling(enum CXTypeKind K); + +/** + * \brief Retrieve the calling convention associated with a function type. + * + * If a non-function type is passed in, CXCallingConv_Invalid is returned. + */ +CINDEX_LINKAGE enum CXCallingConv clang_getFunctionTypeCallingConv(CXType T); + +/** + * \brief Retrieve the result type associated with a function type. + * + * If a non-function type is passed in, an invalid type is returned. + */ +CINDEX_LINKAGE CXType clang_getResultType(CXType T); + +/** + * \brief Retrieve the number of non-variadic arguments associated with a function type. + * + * If a non-function type is passed in, -1 is returned. + */ +CINDEX_LINKAGE int clang_getNumArgTypes(CXType T); + +/** + * \brief Retrieve the type of an argument of a function type. + * + * If a non-function type is passed in or the function does not have enough parameters, + * an invalid type is returned. + */ +CINDEX_LINKAGE CXType clang_getArgType(CXType T, unsigned i); + +/** + * \brief Return 1 if the CXType is a variadic function type, and 0 otherwise. + * + */ +CINDEX_LINKAGE unsigned clang_isFunctionTypeVariadic(CXType T); + +/** + * \brief Retrieve the result type associated with a given cursor. + * + * This only returns a valid type if the cursor refers to a function or method. + */ +CINDEX_LINKAGE CXType clang_getCursorResultType(CXCursor C); + +/** + * \brief Return 1 if the CXType is a POD (plain old data) type, and 0 + * otherwise. + */ +CINDEX_LINKAGE unsigned clang_isPODType(CXType T); + +/** + * \brief Return the element type of an array, complex, or vector type. + * + * If a type is passed in that is not an array, complex, or vector type, + * an invalid type is returned. + */ +CINDEX_LINKAGE CXType clang_getElementType(CXType T); + +/** + * \brief Return the number of elements of an array or vector type. + * + * If a type is passed in that is not an array or vector type, + * -1 is returned. + */ +CINDEX_LINKAGE long long clang_getNumElements(CXType T); + +/** + * \brief Return the element type of an array type. + * + * If a non-array type is passed in, an invalid type is returned. + */ +CINDEX_LINKAGE CXType clang_getArrayElementType(CXType T); + +/** + * \brief Return the the array size of a constant array. + * + * If a non-array type is passed in, -1 is returned. + */ +CINDEX_LINKAGE long long clang_getArraySize(CXType T); + +/** + * \brief Returns 1 if the base class specified by the cursor with kind + * CX_CXXBaseSpecifier is virtual. + */ +CINDEX_LINKAGE unsigned clang_isVirtualBase(CXCursor); + +/** + * \brief Represents the C++ access control level to a base class for a + * cursor with kind CX_CXXBaseSpecifier. + */ +enum CX_CXXAccessSpecifier { + CX_CXXInvalidAccessSpecifier, + CX_CXXPublic, + CX_CXXProtected, + CX_CXXPrivate +}; + +/** + * \brief Returns the access control level for the C++ base specifier + * represented by a cursor with kind CXCursor_CXXBaseSpecifier or + * CXCursor_AccessSpecifier. + */ +CINDEX_LINKAGE enum CX_CXXAccessSpecifier clang_getCXXAccessSpecifier(CXCursor); + +/** + * \brief Determine the number of overloaded declarations referenced by a + * \c CXCursor_OverloadedDeclRef cursor. + * + * \param cursor The cursor whose overloaded declarations are being queried. + * + * \returns The number of overloaded declarations referenced by \c cursor. If it + * is not a \c CXCursor_OverloadedDeclRef cursor, returns 0. + */ +CINDEX_LINKAGE unsigned clang_getNumOverloadedDecls(CXCursor cursor); + +/** + * \brief Retrieve a cursor for one of the overloaded declarations referenced + * by a \c CXCursor_OverloadedDeclRef cursor. + * + * \param cursor The cursor whose overloaded declarations are being queried. + * + * \param index The zero-based index into the set of overloaded declarations in + * the cursor. + * + * \returns A cursor representing the declaration referenced by the given + * \c cursor at the specified \c index. If the cursor does not have an + * associated set of overloaded declarations, or if the index is out of bounds, + * returns \c clang_getNullCursor(); + */ +CINDEX_LINKAGE CXCursor clang_getOverloadedDecl(CXCursor cursor, + unsigned index); + +/** + * @} + */ + +/** + * \defgroup CINDEX_ATTRIBUTES Information for attributes + * + * @{ + */ + + +/** + * \brief For cursors representing an iboutletcollection attribute, + * this function returns the collection element type. + * + */ +CINDEX_LINKAGE CXType clang_getIBOutletCollectionType(CXCursor); + +/** + * @} + */ + +/** + * \defgroup CINDEX_CURSOR_TRAVERSAL Traversing the AST with cursors + * + * These routines provide the ability to traverse the abstract syntax tree + * using cursors. + * + * @{ + */ + +/** + * \brief Describes how the traversal of the children of a particular + * cursor should proceed after visiting a particular child cursor. + * + * A value of this enumeration type should be returned by each + * \c CXCursorVisitor to indicate how clang_visitChildren() proceed. + */ +enum CXChildVisitResult { + /** + * \brief Terminates the cursor traversal. + */ + CXChildVisit_Break, + /** + * \brief Continues the cursor traversal with the next sibling of + * the cursor just visited, without visiting its children. + */ + CXChildVisit_Continue, + /** + * \brief Recursively traverse the children of this cursor, using + * the same visitor and client data. + */ + CXChildVisit_Recurse +}; + +/** + * \brief Visitor invoked for each cursor found by a traversal. + * + * This visitor function will be invoked for each cursor found by + * clang_visitCursorChildren(). Its first argument is the cursor being + * visited, its second argument is the parent visitor for that cursor, + * and its third argument is the client data provided to + * clang_visitCursorChildren(). + * + * The visitor should return one of the \c CXChildVisitResult values + * to direct clang_visitCursorChildren(). + */ +typedef enum CXChildVisitResult (*CXCursorVisitor)(CXCursor cursor, + CXCursor parent, + CXClientData client_data); + +/** + * \brief Visit the children of a particular cursor. + * + * This function visits all the direct children of the given cursor, + * invoking the given \p visitor function with the cursors of each + * visited child. The traversal may be recursive, if the visitor returns + * \c CXChildVisit_Recurse. The traversal may also be ended prematurely, if + * the visitor returns \c CXChildVisit_Break. + * + * \param parent the cursor whose child may be visited. All kinds of + * cursors can be visited, including invalid cursors (which, by + * definition, have no children). + * + * \param visitor the visitor function that will be invoked for each + * child of \p parent. + * + * \param client_data pointer data supplied by the client, which will + * be passed to the visitor each time it is invoked. + * + * \returns a non-zero value if the traversal was terminated + * prematurely by the visitor returning \c CXChildVisit_Break. + */ +CINDEX_LINKAGE unsigned clang_visitChildren(CXCursor parent, + CXCursorVisitor visitor, + CXClientData client_data); +#ifdef __has_feature +# if __has_feature(blocks) +/** + * \brief Visitor invoked for each cursor found by a traversal. + * + * This visitor block will be invoked for each cursor found by + * clang_visitChildrenWithBlock(). Its first argument is the cursor being + * visited, its second argument is the parent visitor for that cursor. + * + * The visitor should return one of the \c CXChildVisitResult values + * to direct clang_visitChildrenWithBlock(). + */ +typedef enum CXChildVisitResult + (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); + +/** + * Visits the children of a cursor using the specified block. Behaves + * identically to clang_visitChildren() in all other respects. + */ +unsigned clang_visitChildrenWithBlock(CXCursor parent, + CXCursorVisitorBlock block); +# endif +#endif + +/** + * @} + */ + +/** + * \defgroup CINDEX_CURSOR_XREF Cross-referencing in the AST + * + * These routines provide the ability to determine references within and + * across translation units, by providing the names of the entities referenced + * by cursors, follow reference cursors to the declarations they reference, + * and associate declarations with their definitions. + * + * @{ + */ + +/** + * \brief Retrieve a Unified Symbol Resolution (USR) for the entity referenced + * by the given cursor. + * + * A Unified Symbol Resolution (USR) is a string that identifies a particular + * entity (function, class, variable, etc.) within a program. USRs can be + * compared across translation units to determine, e.g., when references in + * one translation refer to an entity defined in another translation unit. + */ +CINDEX_LINKAGE CXString clang_getCursorUSR(CXCursor); + +/** + * \brief Construct a USR for a specified Objective-C class. + */ +CINDEX_LINKAGE CXString clang_constructUSR_ObjCClass(const char *class_name); + +/** + * \brief Construct a USR for a specified Objective-C category. + */ +CINDEX_LINKAGE CXString + clang_constructUSR_ObjCCategory(const char *class_name, + const char *category_name); + +/** + * \brief Construct a USR for a specified Objective-C protocol. + */ +CINDEX_LINKAGE CXString + clang_constructUSR_ObjCProtocol(const char *protocol_name); + + +/** + * \brief Construct a USR for a specified Objective-C instance variable and + * the USR for its containing class. + */ +CINDEX_LINKAGE CXString clang_constructUSR_ObjCIvar(const char *name, + CXString classUSR); + +/** + * \brief Construct a USR for a specified Objective-C method and + * the USR for its containing class. + */ +CINDEX_LINKAGE CXString clang_constructUSR_ObjCMethod(const char *name, + unsigned isInstanceMethod, + CXString classUSR); + +/** + * \brief Construct a USR for a specified Objective-C property and the USR + * for its containing class. + */ +CINDEX_LINKAGE CXString clang_constructUSR_ObjCProperty(const char *property, + CXString classUSR); + +/** + * \brief Retrieve a name for the entity referenced by this cursor. + */ +CINDEX_LINKAGE CXString clang_getCursorSpelling(CXCursor); + +/** + * \brief Retrieve a range for a piece that forms the cursors spelling name. + * Most of the times there is only one range for the complete spelling but for + * objc methods and objc message expressions, there are multiple pieces for each + * selector identifier. + * + * \param pieceIndex the index of the spelling name piece. If this is greater + * than the actual number of pieces, it will return a NULL (invalid) range. + * + * \param options Reserved. + */ +CINDEX_LINKAGE CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor, + unsigned pieceIndex, + unsigned options); + +/** + * \brief Retrieve the display name for the entity referenced by this cursor. + * + * The display name contains extra information that helps identify the cursor, + * such as the parameters of a function or template or the arguments of a + * class template specialization. + */ +CINDEX_LINKAGE CXString clang_getCursorDisplayName(CXCursor); + +/** \brief For a cursor that is a reference, retrieve a cursor representing the + * entity that it references. + * + * Reference cursors refer to other entities in the AST. For example, an + * Objective-C superclass reference cursor refers to an Objective-C class. + * This function produces the cursor for the Objective-C class from the + * cursor for the superclass reference. If the input cursor is a declaration or + * definition, it returns that declaration or definition unchanged. + * Otherwise, returns the NULL cursor. + */ +CINDEX_LINKAGE CXCursor clang_getCursorReferenced(CXCursor); + +/** + * \brief For a cursor that is either a reference to or a declaration + * of some entity, retrieve a cursor that describes the definition of + * that entity. + * + * Some entities can be declared multiple times within a translation + * unit, but only one of those declarations can also be a + * definition. For example, given: + * + * \code + * int f(int, int); + * int g(int x, int y) { return f(x, y); } + * int f(int a, int b) { return a + b; } + * int f(int, int); + * \endcode + * + * there are three declarations of the function "f", but only the + * second one is a definition. The clang_getCursorDefinition() + * function will take any cursor pointing to a declaration of "f" + * (the first or fourth lines of the example) or a cursor referenced + * that uses "f" (the call to "f' inside "g") and will return a + * declaration cursor pointing to the definition (the second "f" + * declaration). + * + * If given a cursor for which there is no corresponding definition, + * e.g., because there is no definition of that entity within this + * translation unit, returns a NULL cursor. + */ +CINDEX_LINKAGE CXCursor clang_getCursorDefinition(CXCursor); + +/** + * \brief Determine whether the declaration pointed to by this cursor + * is also a definition of that entity. + */ +CINDEX_LINKAGE unsigned clang_isCursorDefinition(CXCursor); + +/** + * \brief Retrieve the canonical cursor corresponding to the given cursor. + * + * In the C family of languages, many kinds of entities can be declared several + * times within a single translation unit. For example, a structure type can + * be forward-declared (possibly multiple times) and later defined: + * + * \code + * struct X; + * struct X; + * struct X { + * int member; + * }; + * \endcode + * + * The declarations and the definition of \c X are represented by three + * different cursors, all of which are declarations of the same underlying + * entity. One of these cursor is considered the "canonical" cursor, which + * is effectively the representative for the underlying entity. One can + * determine if two cursors are declarations of the same underlying entity by + * comparing their canonical cursors. + * + * \returns The canonical cursor for the entity referred to by the given cursor. + */ +CINDEX_LINKAGE CXCursor clang_getCanonicalCursor(CXCursor); + + +/** + * \brief If the cursor points to a selector identifier in a objc method or + * message expression, this returns the selector index. + * + * After getting a cursor with \see clang_getCursor, this can be called to + * determine if the location points to a selector identifier. + * + * \returns The selector index if the cursor is an objc method or message + * expression and the cursor is pointing to a selector identifier, or -1 + * otherwise. + */ +CINDEX_LINKAGE int clang_Cursor_getObjCSelectorIndex(CXCursor); + +/** + * @} + */ + +/** + * \defgroup CINDEX_CPP C++ AST introspection + * + * The routines in this group provide access information in the ASTs specific + * to C++ language features. + * + * @{ + */ + +/** + * \brief Determine if a C++ member function or member function template is + * declared 'static'. + */ +CINDEX_LINKAGE unsigned clang_CXXMethod_isStatic(CXCursor C); + +/** + * \brief Determine if a C++ member function or member function template is + * explicitly declared 'virtual' or if it overrides a virtual method from + * one of the base classes. + */ +CINDEX_LINKAGE unsigned clang_CXXMethod_isVirtual(CXCursor C); + +/** + * \brief Given a cursor that represents a template, determine + * the cursor kind of the specializations would be generated by instantiating + * the template. + * + * This routine can be used to determine what flavor of function template, + * class template, or class template partial specialization is stored in the + * cursor. For example, it can describe whether a class template cursor is + * declared with "struct", "class" or "union". + * + * \param C The cursor to query. This cursor should represent a template + * declaration. + * + * \returns The cursor kind of the specializations that would be generated + * by instantiating the template \p C. If \p C is not a template, returns + * \c CXCursor_NoDeclFound. + */ +CINDEX_LINKAGE enum CXCursorKind clang_getTemplateCursorKind(CXCursor C); + +/** + * \brief Given a cursor that may represent a specialization or instantiation + * of a template, retrieve the cursor that represents the template that it + * specializes or from which it was instantiated. + * + * This routine determines the template involved both for explicit + * specializations of templates and for implicit instantiations of the template, + * both of which are referred to as "specializations". For a class template + * specialization (e.g., \c std::vector), this routine will return + * either the primary template (\c std::vector) or, if the specialization was + * instantiated from a class template partial specialization, the class template + * partial specialization. For a class template partial specialization and a + * function template specialization (including instantiations), this + * this routine will return the specialized template. + * + * For members of a class template (e.g., member functions, member classes, or + * static data members), returns the specialized or instantiated member. + * Although not strictly "templates" in the C++ language, members of class + * templates have the same notions of specializations and instantiations that + * templates do, so this routine treats them similarly. + * + * \param C A cursor that may be a specialization of a template or a member + * of a template. + * + * \returns If the given cursor is a specialization or instantiation of a + * template or a member thereof, the template or member that it specializes or + * from which it was instantiated. Otherwise, returns a NULL cursor. + */ +CINDEX_LINKAGE CXCursor clang_getSpecializedCursorTemplate(CXCursor C); + +/** + * \brief Given a cursor that references something else, return the source range + * covering that reference. + * + * \param C A cursor pointing to a member reference, a declaration reference, or + * an operator call. + * \param NameFlags A bitset with three independent flags: + * CXNameRange_WantQualifier, CXNameRange_WantTemplateArgs, and + * CXNameRange_WantSinglePiece. + * \param PieceIndex For contiguous names or when passing the flag + * CXNameRange_WantSinglePiece, only one piece with index 0 is + * available. When the CXNameRange_WantSinglePiece flag is not passed for a + * non-contiguous names, this index can be used to retreive the individual + * pieces of the name. See also CXNameRange_WantSinglePiece. + * + * \returns The piece of the name pointed to by the given cursor. If there is no + * name, or if the PieceIndex is out-of-range, a null-cursor will be returned. + */ +CINDEX_LINKAGE CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, + unsigned NameFlags, + unsigned PieceIndex); + +enum CXNameRefFlags { + /** + * \brief Include the nested-name-specifier, e.g. Foo:: in x.Foo::y, in the + * range. + */ + CXNameRange_WantQualifier = 0x1, + + /** + * \brief Include the explicit template arguments, e.g. in x.f, in + * the range. + */ + CXNameRange_WantTemplateArgs = 0x2, + + /** + * \brief If the name is non-contiguous, return the full spanning range. + * + * Non-contiguous names occur in Objective-C when a selector with two or more + * parameters is used, or in C++ when using an operator: + * \code + * [object doSomething:here withValue:there]; // ObjC + * return some_vector[1]; // C++ + * \endcode + */ + CXNameRange_WantSinglePiece = 0x4 +}; + +/** + * @} + */ + +/** + * \defgroup CINDEX_LEX Token extraction and manipulation + * + * The routines in this group provide access to the tokens within a + * translation unit, along with a semantic mapping of those tokens to + * their corresponding cursors. + * + * @{ + */ + +/** + * \brief Describes a kind of token. + */ +typedef enum CXTokenKind { + /** + * \brief A token that contains some kind of punctuation. + */ + CXToken_Punctuation, + + /** + * \brief A language keyword. + */ + CXToken_Keyword, + + /** + * \brief An identifier (that is not a keyword). + */ + CXToken_Identifier, + + /** + * \brief A numeric, string, or character literal. + */ + CXToken_Literal, + + /** + * \brief A comment. + */ + CXToken_Comment +} CXTokenKind; + +/** + * \brief Describes a single preprocessing token. + */ +typedef struct { + unsigned int_data[4]; + void *ptr_data; +} CXToken; + +/** + * \brief Determine the kind of the given token. + */ +CINDEX_LINKAGE CXTokenKind clang_getTokenKind(CXToken); + +/** + * \brief Determine the spelling of the given token. + * + * The spelling of a token is the textual representation of that token, e.g., + * the text of an identifier or keyword. + */ +CINDEX_LINKAGE CXString clang_getTokenSpelling(CXTranslationUnit, CXToken); + +/** + * \brief Retrieve the source location of the given token. + */ +CINDEX_LINKAGE CXSourceLocation clang_getTokenLocation(CXTranslationUnit, + CXToken); + +/** + * \brief Retrieve a source range that covers the given token. + */ +CINDEX_LINKAGE CXSourceRange clang_getTokenExtent(CXTranslationUnit, CXToken); + +/** + * \brief Tokenize the source code described by the given range into raw + * lexical tokens. + * + * \param TU the translation unit whose text is being tokenized. + * + * \param Range the source range in which text should be tokenized. All of the + * tokens produced by tokenization will fall within this source range, + * + * \param Tokens this pointer will be set to point to the array of tokens + * that occur within the given source range. The returned pointer must be + * freed with clang_disposeTokens() before the translation unit is destroyed. + * + * \param NumTokens will be set to the number of tokens in the \c *Tokens + * array. + * + */ +CINDEX_LINKAGE void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, + CXToken **Tokens, unsigned *NumTokens); + +/** + * \brief Annotate the given set of tokens by providing cursors for each token + * that can be mapped to a specific entity within the abstract syntax tree. + * + * This token-annotation routine is equivalent to invoking + * clang_getCursor() for the source locations of each of the + * tokens. The cursors provided are filtered, so that only those + * cursors that have a direct correspondence to the token are + * accepted. For example, given a function call \c f(x), + * clang_getCursor() would provide the following cursors: + * + * * when the cursor is over the 'f', a DeclRefExpr cursor referring to 'f'. + * * when the cursor is over the '(' or the ')', a CallExpr referring to 'f'. + * * when the cursor is over the 'x', a DeclRefExpr cursor referring to 'x'. + * + * Only the first and last of these cursors will occur within the + * annotate, since the tokens "f" and "x' directly refer to a function + * and a variable, respectively, but the parentheses are just a small + * part of the full syntax of the function call expression, which is + * not provided as an annotation. + * + * \param TU the translation unit that owns the given tokens. + * + * \param Tokens the set of tokens to annotate. + * + * \param NumTokens the number of tokens in \p Tokens. + * + * \param Cursors an array of \p NumTokens cursors, whose contents will be + * replaced with the cursors corresponding to each token. + */ +CINDEX_LINKAGE void clang_annotateTokens(CXTranslationUnit TU, + CXToken *Tokens, unsigned NumTokens, + CXCursor *Cursors); + +/** + * \brief Free the given set of tokens. + */ +CINDEX_LINKAGE void clang_disposeTokens(CXTranslationUnit TU, + CXToken *Tokens, unsigned NumTokens); + +/** + * @} + */ + +/** + * \defgroup CINDEX_DEBUG Debugging facilities + * + * These routines are used for testing and debugging, only, and should not + * be relied upon. + * + * @{ + */ + +/* for debug/testing */ +CINDEX_LINKAGE CXString clang_getCursorKindSpelling(enum CXCursorKind Kind); +CINDEX_LINKAGE void clang_getDefinitionSpellingAndExtent(CXCursor, + const char **startBuf, + const char **endBuf, + unsigned *startLine, + unsigned *startColumn, + unsigned *endLine, + unsigned *endColumn); +CINDEX_LINKAGE void clang_enableStackTraces(void); +CINDEX_LINKAGE void clang_executeOnThread(void (*fn)(void*), void *user_data, + unsigned stack_size); + +/** + * @} + */ + +/** + * \defgroup CINDEX_CODE_COMPLET Code completion + * + * Code completion involves taking an (incomplete) source file, along with + * knowledge of where the user is actively editing that file, and suggesting + * syntactically- and semantically-valid constructs that the user might want to + * use at that particular point in the source code. These data structures and + * routines provide support for code completion. + * + * @{ + */ + +/** + * \brief A semantic string that describes a code-completion result. + * + * A semantic string that describes the formatting of a code-completion + * result as a single "template" of text that should be inserted into the + * source buffer when a particular code-completion result is selected. + * Each semantic string is made up of some number of "chunks", each of which + * contains some text along with a description of what that text means, e.g., + * the name of the entity being referenced, whether the text chunk is part of + * the template, or whether it is a "placeholder" that the user should replace + * with actual code,of a specific kind. See \c CXCompletionChunkKind for a + * description of the different kinds of chunks. + */ +typedef void *CXCompletionString; + +/** + * \brief A single result of code completion. + */ +typedef struct { + /** + * \brief The kind of entity that this completion refers to. + * + * The cursor kind will be a macro, keyword, or a declaration (one of the + * *Decl cursor kinds), describing the entity that the completion is + * referring to. + * + * \todo In the future, we would like to provide a full cursor, to allow + * the client to extract additional information from declaration. + */ + enum CXCursorKind CursorKind; + + /** + * \brief The code-completion string that describes how to insert this + * code-completion result into the editing buffer. + */ + CXCompletionString CompletionString; +} CXCompletionResult; + +/** + * \brief Describes a single piece of text within a code-completion string. + * + * Each "chunk" within a code-completion string (\c CXCompletionString) is + * either a piece of text with a specific "kind" that describes how that text + * should be interpreted by the client or is another completion string. + */ +enum CXCompletionChunkKind { + /** + * \brief A code-completion string that describes "optional" text that + * could be a part of the template (but is not required). + * + * The Optional chunk is the only kind of chunk that has a code-completion + * string for its representation, which is accessible via + * \c clang_getCompletionChunkCompletionString(). The code-completion string + * describes an additional part of the template that is completely optional. + * For example, optional chunks can be used to describe the placeholders for + * arguments that match up with defaulted function parameters, e.g. given: + * + * \code + * void f(int x, float y = 3.14, double z = 2.71828); + * \endcode + * + * The code-completion string for this function would contain: + * - a TypedText chunk for "f". + * - a LeftParen chunk for "(". + * - a Placeholder chunk for "int x" + * - an Optional chunk containing the remaining defaulted arguments, e.g., + * - a Comma chunk for "," + * - a Placeholder chunk for "float y" + * - an Optional chunk containing the last defaulted argument: + * - a Comma chunk for "," + * - a Placeholder chunk for "double z" + * - a RightParen chunk for ")" + * + * There are many ways to handle Optional chunks. Two simple approaches are: + * - Completely ignore optional chunks, in which case the template for the + * function "f" would only include the first parameter ("int x"). + * - Fully expand all optional chunks, in which case the template for the + * function "f" would have all of the parameters. + */ + CXCompletionChunk_Optional, + /** + * \brief Text that a user would be expected to type to get this + * code-completion result. + * + * There will be exactly one "typed text" chunk in a semantic string, which + * will typically provide the spelling of a keyword or the name of a + * declaration that could be used at the current code point. Clients are + * expected to filter the code-completion results based on the text in this + * chunk. + */ + CXCompletionChunk_TypedText, + /** + * \brief Text that should be inserted as part of a code-completion result. + * + * A "text" chunk represents text that is part of the template to be + * inserted into user code should this particular code-completion result + * be selected. + */ + CXCompletionChunk_Text, + /** + * \brief Placeholder text that should be replaced by the user. + * + * A "placeholder" chunk marks a place where the user should insert text + * into the code-completion template. For example, placeholders might mark + * the function parameters for a function declaration, to indicate that the + * user should provide arguments for each of those parameters. The actual + * text in a placeholder is a suggestion for the text to display before + * the user replaces the placeholder with real code. + */ + CXCompletionChunk_Placeholder, + /** + * \brief Informative text that should be displayed but never inserted as + * part of the template. + * + * An "informative" chunk contains annotations that can be displayed to + * help the user decide whether a particular code-completion result is the + * right option, but which is not part of the actual template to be inserted + * by code completion. + */ + CXCompletionChunk_Informative, + /** + * \brief Text that describes the current parameter when code-completion is + * referring to function call, message send, or template specialization. + * + * A "current parameter" chunk occurs when code-completion is providing + * information about a parameter corresponding to the argument at the + * code-completion point. For example, given a function + * + * \code + * int add(int x, int y); + * \endcode + * + * and the source code \c add(, where the code-completion point is after the + * "(", the code-completion string will contain a "current parameter" chunk + * for "int x", indicating that the current argument will initialize that + * parameter. After typing further, to \c add(17, (where the code-completion + * point is after the ","), the code-completion string will contain a + * "current paremeter" chunk to "int y". + */ + CXCompletionChunk_CurrentParameter, + /** + * \brief A left parenthesis ('('), used to initiate a function call or + * signal the beginning of a function parameter list. + */ + CXCompletionChunk_LeftParen, + /** + * \brief A right parenthesis (')'), used to finish a function call or + * signal the end of a function parameter list. + */ + CXCompletionChunk_RightParen, + /** + * \brief A left bracket ('['). + */ + CXCompletionChunk_LeftBracket, + /** + * \brief A right bracket (']'). + */ + CXCompletionChunk_RightBracket, + /** + * \brief A left brace ('{'). + */ + CXCompletionChunk_LeftBrace, + /** + * \brief A right brace ('}'). + */ + CXCompletionChunk_RightBrace, + /** + * \brief A left angle bracket ('<'). + */ + CXCompletionChunk_LeftAngle, + /** + * \brief A right angle bracket ('>'). + */ + CXCompletionChunk_RightAngle, + /** + * \brief A comma separator (','). + */ + CXCompletionChunk_Comma, + /** + * \brief Text that specifies the result type of a given result. + * + * This special kind of informative chunk is not meant to be inserted into + * the text buffer. Rather, it is meant to illustrate the type that an + * expression using the given completion string would have. + */ + CXCompletionChunk_ResultType, + /** + * \brief A colon (':'). + */ + CXCompletionChunk_Colon, + /** + * \brief A semicolon (';'). + */ + CXCompletionChunk_SemiColon, + /** + * \brief An '=' sign. + */ + CXCompletionChunk_Equal, + /** + * Horizontal space (' '). + */ + CXCompletionChunk_HorizontalSpace, + /** + * Vertical space ('\n'), after which it is generally a good idea to + * perform indentation. + */ + CXCompletionChunk_VerticalSpace +}; + +/** + * \brief Determine the kind of a particular chunk within a completion string. + * + * \param completion_string the completion string to query. + * + * \param chunk_number the 0-based index of the chunk in the completion string. + * + * \returns the kind of the chunk at the index \c chunk_number. + */ +CINDEX_LINKAGE enum CXCompletionChunkKind +clang_getCompletionChunkKind(CXCompletionString completion_string, + unsigned chunk_number); + +/** + * \brief Retrieve the text associated with a particular chunk within a + * completion string. + * + * \param completion_string the completion string to query. + * + * \param chunk_number the 0-based index of the chunk in the completion string. + * + * \returns the text associated with the chunk at index \c chunk_number. + */ +CINDEX_LINKAGE CXString +clang_getCompletionChunkText(CXCompletionString completion_string, + unsigned chunk_number); + +/** + * \brief Retrieve the completion string associated with a particular chunk + * within a completion string. + * + * \param completion_string the completion string to query. + * + * \param chunk_number the 0-based index of the chunk in the completion string. + * + * \returns the completion string associated with the chunk at index + * \c chunk_number. + */ +CINDEX_LINKAGE CXCompletionString +clang_getCompletionChunkCompletionString(CXCompletionString completion_string, + unsigned chunk_number); + +/** + * \brief Retrieve the number of chunks in the given code-completion string. + */ +CINDEX_LINKAGE unsigned +clang_getNumCompletionChunks(CXCompletionString completion_string); + +/** + * \brief Determine the priority of this code completion. + * + * The priority of a code completion indicates how likely it is that this + * particular completion is the completion that the user will select. The + * priority is selected by various internal heuristics. + * + * \param completion_string The completion string to query. + * + * \returns The priority of this completion string. Smaller values indicate + * higher-priority (more likely) completions. + */ +CINDEX_LINKAGE unsigned +clang_getCompletionPriority(CXCompletionString completion_string); + +/** + * \brief Determine the availability of the entity that this code-completion + * string refers to. + * + * \param completion_string The completion string to query. + * + * \returns The availability of the completion string. + */ +CINDEX_LINKAGE enum CXAvailabilityKind +clang_getCompletionAvailability(CXCompletionString completion_string); + +/** + * \brief Retrieve the number of annotations associated with the given + * completion string. + * + * \param completion_string the completion string to query. + * + * \returns the number of annotations associated with the given completion + * string. + */ +CINDEX_LINKAGE unsigned +clang_getCompletionNumAnnotations(CXCompletionString completion_string); + +/** + * \brief Retrieve the annotation associated with the given completion string. + * + * \param completion_string the completion string to query. + * + * \param annotation_number the 0-based index of the annotation of the + * completion string. + * + * \returns annotation string associated with the completion at index + * \c annotation_number, or a NULL string if that annotation is not available. + */ +CINDEX_LINKAGE CXString +clang_getCompletionAnnotation(CXCompletionString completion_string, + unsigned annotation_number); + +/** + * \brief Retrieve the parent context of the given completion string. + * + * The parent context of a completion string is the semantic parent of + * the declaration (if any) that the code completion represents. For example, + * a code completion for an Objective-C method would have the method's class + * or protocol as its context. + * + * \param completion_string The code completion string whose parent is + * being queried. + * + * \param kind If non-NULL, will be set to the kind of the parent context, + * or CXCursor_NotImplemented if there is no context. + * + * \param Returns the name of the completion parent, e.g., "NSObject" if + * the completion string represents a method in the NSObject class. + */ +CINDEX_LINKAGE CXString +clang_getCompletionParent(CXCompletionString completion_string, + enum CXCursorKind *kind); +/** + * \brief Retrieve a completion string for an arbitrary declaration or macro + * definition cursor. + * + * \param cursor The cursor to query. + * + * \returns A non-context-sensitive completion string for declaration and macro + * definition cursors, or NULL for other kinds of cursors. + */ +CINDEX_LINKAGE CXCompletionString +clang_getCursorCompletionString(CXCursor cursor); + +/** + * \brief Contains the results of code-completion. + * + * This data structure contains the results of code completion, as + * produced by \c clang_codeCompleteAt(). Its contents must be freed by + * \c clang_disposeCodeCompleteResults. + */ +typedef struct { + /** + * \brief The code-completion results. + */ + CXCompletionResult *Results; + + /** + * \brief The number of code-completion results stored in the + * \c Results array. + */ + unsigned NumResults; +} CXCodeCompleteResults; + +/** + * \brief Flags that can be passed to \c clang_codeCompleteAt() to + * modify its behavior. + * + * The enumerators in this enumeration can be bitwise-OR'd together to + * provide multiple options to \c clang_codeCompleteAt(). + */ +enum CXCodeComplete_Flags { + /** + * \brief Whether to include macros within the set of code + * completions returned. + */ + CXCodeComplete_IncludeMacros = 0x01, + + /** + * \brief Whether to include code patterns for language constructs + * within the set of code completions, e.g., for loops. + */ + CXCodeComplete_IncludeCodePatterns = 0x02 +}; + +/** + * \brief Bits that represent the context under which completion is occurring. + * + * The enumerators in this enumeration may be bitwise-OR'd together if multiple + * contexts are occurring simultaneously. + */ +enum CXCompletionContext { + /** + * \brief The context for completions is unexposed, as only Clang results + * should be included. (This is equivalent to having no context bits set.) + */ + CXCompletionContext_Unexposed = 0, + + /** + * \brief Completions for any possible type should be included in the results. + */ + CXCompletionContext_AnyType = 1 << 0, + + /** + * \brief Completions for any possible value (variables, function calls, etc.) + * should be included in the results. + */ + CXCompletionContext_AnyValue = 1 << 1, + /** + * \brief Completions for values that resolve to an Objective-C object should + * be included in the results. + */ + CXCompletionContext_ObjCObjectValue = 1 << 2, + /** + * \brief Completions for values that resolve to an Objective-C selector + * should be included in the results. + */ + CXCompletionContext_ObjCSelectorValue = 1 << 3, + /** + * \brief Completions for values that resolve to a C++ class type should be + * included in the results. + */ + CXCompletionContext_CXXClassTypeValue = 1 << 4, + + /** + * \brief Completions for fields of the member being accessed using the dot + * operator should be included in the results. + */ + CXCompletionContext_DotMemberAccess = 1 << 5, + /** + * \brief Completions for fields of the member being accessed using the arrow + * operator should be included in the results. + */ + CXCompletionContext_ArrowMemberAccess = 1 << 6, + /** + * \brief Completions for properties of the Objective-C object being accessed + * using the dot operator should be included in the results. + */ + CXCompletionContext_ObjCPropertyAccess = 1 << 7, + + /** + * \brief Completions for enum tags should be included in the results. + */ + CXCompletionContext_EnumTag = 1 << 8, + /** + * \brief Completions for union tags should be included in the results. + */ + CXCompletionContext_UnionTag = 1 << 9, + /** + * \brief Completions for struct tags should be included in the results. + */ + CXCompletionContext_StructTag = 1 << 10, + + /** + * \brief Completions for C++ class names should be included in the results. + */ + CXCompletionContext_ClassTag = 1 << 11, + /** + * \brief Completions for C++ namespaces and namespace aliases should be + * included in the results. + */ + CXCompletionContext_Namespace = 1 << 12, + /** + * \brief Completions for C++ nested name specifiers should be included in + * the results. + */ + CXCompletionContext_NestedNameSpecifier = 1 << 13, + + /** + * \brief Completions for Objective-C interfaces (classes) should be included + * in the results. + */ + CXCompletionContext_ObjCInterface = 1 << 14, + /** + * \brief Completions for Objective-C protocols should be included in + * the results. + */ + CXCompletionContext_ObjCProtocol = 1 << 15, + /** + * \brief Completions for Objective-C categories should be included in + * the results. + */ + CXCompletionContext_ObjCCategory = 1 << 16, + /** + * \brief Completions for Objective-C instance messages should be included + * in the results. + */ + CXCompletionContext_ObjCInstanceMessage = 1 << 17, + /** + * \brief Completions for Objective-C class messages should be included in + * the results. + */ + CXCompletionContext_ObjCClassMessage = 1 << 18, + /** + * \brief Completions for Objective-C selector names should be included in + * the results. + */ + CXCompletionContext_ObjCSelectorName = 1 << 19, + + /** + * \brief Completions for preprocessor macro names should be included in + * the results. + */ + CXCompletionContext_MacroName = 1 << 20, + + /** + * \brief Natural language completions should be included in the results. + */ + CXCompletionContext_NaturalLanguage = 1 << 21, + + /** + * \brief The current context is unknown, so set all contexts. + */ + CXCompletionContext_Unknown = ((1 << 22) - 1) +}; + +/** + * \brief Returns a default set of code-completion options that can be + * passed to\c clang_codeCompleteAt(). + */ +CINDEX_LINKAGE unsigned clang_defaultCodeCompleteOptions(void); + +/** + * \brief Perform code completion at a given location in a translation unit. + * + * This function performs code completion at a particular file, line, and + * column within source code, providing results that suggest potential + * code snippets based on the context of the completion. The basic model + * for code completion is that Clang will parse a complete source file, + * performing syntax checking up to the location where code-completion has + * been requested. At that point, a special code-completion token is passed + * to the parser, which recognizes this token and determines, based on the + * current location in the C/Objective-C/C++ grammar and the state of + * semantic analysis, what completions to provide. These completions are + * returned via a new \c CXCodeCompleteResults structure. + * + * Code completion itself is meant to be triggered by the client when the + * user types punctuation characters or whitespace, at which point the + * code-completion location will coincide with the cursor. For example, if \c p + * is a pointer, code-completion might be triggered after the "-" and then + * after the ">" in \c p->. When the code-completion location is afer the ">", + * the completion results will provide, e.g., the members of the struct that + * "p" points to. The client is responsible for placing the cursor at the + * beginning of the token currently being typed, then filtering the results + * based on the contents of the token. For example, when code-completing for + * the expression \c p->get, the client should provide the location just after + * the ">" (e.g., pointing at the "g") to this code-completion hook. Then, the + * client can filter the results based on the current token text ("get"), only + * showing those results that start with "get". The intent of this interface + * is to separate the relatively high-latency acquisition of code-completion + * results from the filtering of results on a per-character basis, which must + * have a lower latency. + * + * \param TU The translation unit in which code-completion should + * occur. The source files for this translation unit need not be + * completely up-to-date (and the contents of those source files may + * be overridden via \p unsaved_files). Cursors referring into the + * translation unit may be invalidated by this invocation. + * + * \param complete_filename The name of the source file where code + * completion should be performed. This filename may be any file + * included in the translation unit. + * + * \param complete_line The line at which code-completion should occur. + * + * \param complete_column The column at which code-completion should occur. + * Note that the column should point just after the syntactic construct that + * initiated code completion, and not in the middle of a lexical token. + * + * \param unsaved_files the Tiles that have not yet been saved to disk + * but may be required for parsing or code completion, including the + * contents of those files. The contents and name of these files (as + * specified by CXUnsavedFile) are copied when necessary, so the + * client only needs to guarantee their validity until the call to + * this function returns. + * + * \param num_unsaved_files The number of unsaved file entries in \p + * unsaved_files. + * + * \param options Extra options that control the behavior of code + * completion, expressed as a bitwise OR of the enumerators of the + * CXCodeComplete_Flags enumeration. The + * \c clang_defaultCodeCompleteOptions() function returns a default set + * of code-completion options. + * + * \returns If successful, a new \c CXCodeCompleteResults structure + * containing code-completion results, which should eventually be + * freed with \c clang_disposeCodeCompleteResults(). If code + * completion fails, returns NULL. + */ +CINDEX_LINKAGE +CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU, + const char *complete_filename, + unsigned complete_line, + unsigned complete_column, + struct CXUnsavedFile *unsaved_files, + unsigned num_unsaved_files, + unsigned options); + +/** + * \brief Sort the code-completion results in case-insensitive alphabetical + * order. + * + * \param Results The set of results to sort. + * \param NumResults The number of results in \p Results. + */ +CINDEX_LINKAGE +void clang_sortCodeCompletionResults(CXCompletionResult *Results, + unsigned NumResults); + +/** + * \brief Free the given set of code-completion results. + */ +CINDEX_LINKAGE +void clang_disposeCodeCompleteResults(CXCodeCompleteResults *Results); + +/** + * \brief Determine the number of diagnostics produced prior to the + * location where code completion was performed. + */ +CINDEX_LINKAGE +unsigned clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *Results); + +/** + * \brief Retrieve a diagnostic associated with the given code completion. + * + * \param Result the code completion results to query. + * \param Index the zero-based diagnostic number to retrieve. + * + * \returns the requested diagnostic. This diagnostic must be freed + * via a call to \c clang_disposeDiagnostic(). + */ +CINDEX_LINKAGE +CXDiagnostic clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *Results, + unsigned Index); + +/** + * \brief Determines what compeltions are appropriate for the context + * the given code completion. + * + * \param Results the code completion results to query + * + * \returns the kinds of completions that are appropriate for use + * along with the given code completion results. + */ +CINDEX_LINKAGE +unsigned long long clang_codeCompleteGetContexts( + CXCodeCompleteResults *Results); + +/** + * \brief Returns the cursor kind for the container for the current code + * completion context. The container is only guaranteed to be set for + * contexts where a container exists (i.e. member accesses or Objective-C + * message sends); if there is not a container, this function will return + * CXCursor_InvalidCode. + * + * \param Results the code completion results to query + * + * \param IsIncomplete on return, this value will be false if Clang has complete + * information about the container. If Clang does not have complete + * information, this value will be true. + * + * \returns the container kind, or CXCursor_InvalidCode if there is not a + * container + */ +CINDEX_LINKAGE +enum CXCursorKind clang_codeCompleteGetContainerKind( + CXCodeCompleteResults *Results, + unsigned *IsIncomplete); + +/** + * \brief Returns the USR for the container for the current code completion + * context. If there is not a container for the current context, this + * function will return the empty string. + * + * \param Results the code completion results to query + * + * \returns the USR for the container + */ +CINDEX_LINKAGE +CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *Results); + + +/** + * \brief Returns the currently-entered selector for an Objective-C message + * send, formatted like "initWithFoo:bar:". Only guaranteed to return a + * non-empty string for CXCompletionContext_ObjCInstanceMessage and + * CXCompletionContext_ObjCClassMessage. + * + * \param Results the code completion results to query + * + * \returns the selector (or partial selector) that has been entered thus far + * for an Objective-C message send. + */ +CINDEX_LINKAGE +CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *Results); + +/** + * @} + */ + + +/** + * \defgroup CINDEX_MISC Miscellaneous utility functions + * + * @{ + */ + +/** + * \brief Return a version string, suitable for showing to a user, but not + * intended to be parsed (the format is not guaranteed to be stable). + */ +CINDEX_LINKAGE CXString clang_getClangVersion(); + + +/** + * \brief Enable/disable crash recovery. + * + * \param Flag to indicate if crash recovery is enabled. A non-zero value + * enables crash recovery, while 0 disables it. + */ +CINDEX_LINKAGE void clang_toggleCrashRecovery(unsigned isEnabled); + + /** + * \brief Visitor invoked for each file in a translation unit + * (used with clang_getInclusions()). + * + * This visitor function will be invoked by clang_getInclusions() for each + * file included (either at the top-level or by #include directives) within + * a translation unit. The first argument is the file being included, and + * the second and third arguments provide the inclusion stack. The + * array is sorted in order of immediate inclusion. For example, + * the first element refers to the location that included 'included_file'. + */ +typedef void (*CXInclusionVisitor)(CXFile included_file, + CXSourceLocation* inclusion_stack, + unsigned include_len, + CXClientData client_data); + +/** + * \brief Visit the set of preprocessor inclusions in a translation unit. + * The visitor function is called with the provided data for every included + * file. This does not include headers included by the PCH file (unless one + * is inspecting the inclusions in the PCH file itself). + */ +CINDEX_LINKAGE void clang_getInclusions(CXTranslationUnit tu, + CXInclusionVisitor visitor, + CXClientData client_data); + +/** + * @} + */ + +/** \defgroup CINDEX_REMAPPING Remapping functions + * + * @{ + */ + +/** + * \brief A remapping of original source files and their translated files. + */ +typedef void *CXRemapping; + +/** + * \brief Retrieve a remapping. + * + * \param path the path that contains metadata about remappings. + * + * \returns the requested remapping. This remapping must be freed + * via a call to \c clang_remap_dispose(). Can return NULL if an error occurred. + */ +CINDEX_LINKAGE CXRemapping clang_getRemappings(const char *path); + +/** + * \brief Retrieve a remapping. + * + * \param filePaths pointer to an array of file paths containing remapping info. + * + * \param numFiles number of file paths. + * + * \returns the requested remapping. This remapping must be freed + * via a call to \c clang_remap_dispose(). Can return NULL if an error occurred. + */ +CINDEX_LINKAGE +CXRemapping clang_getRemappingsFromFileList(const char **filePaths, + unsigned numFiles); + +/** + * \brief Determine the number of remappings. + */ +CINDEX_LINKAGE unsigned clang_remap_getNumFiles(CXRemapping); + +/** + * \brief Get the original and the associated filename from the remapping. + * + * \param original If non-NULL, will be set to the original filename. + * + * \param transformed If non-NULL, will be set to the filename that the original + * is associated with. + */ +CINDEX_LINKAGE void clang_remap_getFilenames(CXRemapping, unsigned index, + CXString *original, CXString *transformed); + +/** + * \brief Dispose the remapping. + */ +CINDEX_LINKAGE void clang_remap_dispose(CXRemapping); + +/** + * @} + */ + +/** \defgroup CINDEX_HIGH Higher level API functions + * + * @{ + */ + +enum CXVisitorResult { + CXVisit_Break, + CXVisit_Continue +}; + +typedef struct { + void *context; + enum CXVisitorResult (*visit)(void *context, CXCursor, CXSourceRange); +} CXCursorAndRangeVisitor; + +/** + * \brief Find references of a declaration in a specific file. + * + * \param cursor pointing to a declaration or a reference of one. + * + * \param file to search for references. + * + * \param visitor callback that will receive pairs of CXCursor/CXSourceRange for + * each reference found. + * The CXSourceRange will point inside the file; if the reference is inside + * a macro (and not a macro argument) the CXSourceRange will be invalid. + */ +CINDEX_LINKAGE void clang_findReferencesInFile(CXCursor cursor, CXFile file, + CXCursorAndRangeVisitor visitor); + +#ifdef __has_feature +# if __has_feature(blocks) + +typedef enum CXVisitorResult + (^CXCursorAndRangeVisitorBlock)(CXCursor, CXSourceRange); + +CINDEX_LINKAGE +void clang_findReferencesInFileWithBlock(CXCursor, CXFile, + CXCursorAndRangeVisitorBlock); + +# endif +#endif + +/** + * \brief The client's data object that is associated with a CXFile. + */ +typedef void *CXIdxClientFile; + +/** + * \brief The client's data object that is associated with a semantic entity. + */ +typedef void *CXIdxClientEntity; + +/** + * \brief The client's data object that is associated with a semantic container + * of entities. + */ +typedef void *CXIdxClientContainer; + +/** + * \brief The client's data object that is associated with an AST file (PCH + * or module). + */ +typedef void *CXIdxClientASTFile; + +/** + * \brief Source location passed to index callbacks. + */ +typedef struct { + void *ptr_data[2]; + unsigned int_data; +} CXIdxLoc; + +/** + * \brief Data for \see ppIncludedFile callback. + */ +typedef struct { + /** + * \brief Location of '#' in the #include/#import directive. + */ + CXIdxLoc hashLoc; + /** + * \brief Filename as written in the #include/#import directive. + */ + const char *filename; + /** + * \brief The actual file that the #include/#import directive resolved to. + */ + CXFile file; + int isImport; + int isAngled; +} CXIdxIncludedFileInfo; + +/** + * \brief Data for \see importedASTFile callback. + */ +typedef struct { + CXFile file; + /** + * \brief Location where the file is imported. It is useful mostly for + * modules. + */ + CXIdxLoc loc; + /** + * \brief Non-zero if the AST file is a module otherwise it's a PCH. + */ + int isModule; +} CXIdxImportedASTFileInfo; + +typedef enum { + CXIdxEntity_Unexposed = 0, + CXIdxEntity_Typedef = 1, + CXIdxEntity_Function = 2, + CXIdxEntity_Variable = 3, + CXIdxEntity_Field = 4, + CXIdxEntity_EnumConstant = 5, + + CXIdxEntity_ObjCClass = 6, + CXIdxEntity_ObjCProtocol = 7, + CXIdxEntity_ObjCCategory = 8, + + CXIdxEntity_ObjCInstanceMethod = 9, + CXIdxEntity_ObjCClassMethod = 10, + CXIdxEntity_ObjCProperty = 11, + CXIdxEntity_ObjCIvar = 12, + + CXIdxEntity_Enum = 13, + CXIdxEntity_Struct = 14, + CXIdxEntity_Union = 15, + + CXIdxEntity_CXXClass = 16, + CXIdxEntity_CXXNamespace = 17, + CXIdxEntity_CXXNamespaceAlias = 18, + CXIdxEntity_CXXStaticVariable = 19, + CXIdxEntity_CXXStaticMethod = 20, + CXIdxEntity_CXXInstanceMethod = 21, + CXIdxEntity_CXXConstructor = 22, + CXIdxEntity_CXXDestructor = 23, + CXIdxEntity_CXXConversionFunction = 24, + CXIdxEntity_CXXTypeAlias = 25 + +} CXIdxEntityKind; + +typedef enum { + CXIdxEntityLang_None = 0, + CXIdxEntityLang_C = 1, + CXIdxEntityLang_ObjC = 2, + CXIdxEntityLang_CXX = 3 +} CXIdxEntityLanguage; + +/** + * \brief Extra C++ template information for an entity. This can apply to: + * CXIdxEntity_Function + * CXIdxEntity_CXXClass + * CXIdxEntity_CXXStaticMethod + * CXIdxEntity_CXXInstanceMethod + * CXIdxEntity_CXXConstructor + * CXIdxEntity_CXXConversionFunction + * CXIdxEntity_CXXTypeAlias + */ +typedef enum { + CXIdxEntity_NonTemplate = 0, + CXIdxEntity_Template = 1, + CXIdxEntity_TemplatePartialSpecialization = 2, + CXIdxEntity_TemplateSpecialization = 3 +} CXIdxEntityCXXTemplateKind; + +typedef enum { + CXIdxAttr_Unexposed = 0, + CXIdxAttr_IBAction = 1, + CXIdxAttr_IBOutlet = 2, + CXIdxAttr_IBOutletCollection = 3 +} CXIdxAttrKind; + +typedef struct { + CXIdxAttrKind kind; + CXCursor cursor; + CXIdxLoc loc; +} CXIdxAttrInfo; + +typedef struct { + CXIdxEntityKind kind; + CXIdxEntityCXXTemplateKind templateKind; + CXIdxEntityLanguage lang; + const char *name; + const char *USR; + CXCursor cursor; + const CXIdxAttrInfo *const *attributes; + unsigned numAttributes; +} CXIdxEntityInfo; + +typedef struct { + CXCursor cursor; +} CXIdxContainerInfo; + +typedef struct { + const CXIdxAttrInfo *attrInfo; + const CXIdxEntityInfo *objcClass; + CXCursor classCursor; + CXIdxLoc classLoc; +} CXIdxIBOutletCollectionAttrInfo; + +typedef struct { + const CXIdxEntityInfo *entityInfo; + CXCursor cursor; + CXIdxLoc loc; + const CXIdxContainerInfo *semanticContainer; + /** + * \brief Generally same as \see semanticContainer but can be different in + * cases like out-of-line C++ member functions. + */ + const CXIdxContainerInfo *lexicalContainer; + int isRedeclaration; + int isDefinition; + int isContainer; + const CXIdxContainerInfo *declAsContainer; + /** + * \brief Whether the declaration exists in code or was created implicitly + * by the compiler, e.g. implicit objc methods for properties. + */ + int isImplicit; + const CXIdxAttrInfo *const *attributes; + unsigned numAttributes; +} CXIdxDeclInfo; + +typedef enum { + CXIdxObjCContainer_ForwardRef = 0, + CXIdxObjCContainer_Interface = 1, + CXIdxObjCContainer_Implementation = 2 +} CXIdxObjCContainerKind; + +typedef struct { + const CXIdxDeclInfo *declInfo; + CXIdxObjCContainerKind kind; +} CXIdxObjCContainerDeclInfo; + +typedef struct { + const CXIdxEntityInfo *base; + CXCursor cursor; + CXIdxLoc loc; +} CXIdxBaseClassInfo; + +typedef struct { + const CXIdxEntityInfo *protocol; + CXCursor cursor; + CXIdxLoc loc; +} CXIdxObjCProtocolRefInfo; + +typedef struct { + const CXIdxObjCProtocolRefInfo *const *protocols; + unsigned numProtocols; +} CXIdxObjCProtocolRefListInfo; + +typedef struct { + const CXIdxObjCContainerDeclInfo *containerInfo; + const CXIdxBaseClassInfo *superInfo; + const CXIdxObjCProtocolRefListInfo *protocols; +} CXIdxObjCInterfaceDeclInfo; + +typedef struct { + const CXIdxObjCContainerDeclInfo *containerInfo; + const CXIdxEntityInfo *objcClass; + CXCursor classCursor; + CXIdxLoc classLoc; + const CXIdxObjCProtocolRefListInfo *protocols; +} CXIdxObjCCategoryDeclInfo; + +typedef struct { + const CXIdxDeclInfo *declInfo; + const CXIdxEntityInfo *getter; + const CXIdxEntityInfo *setter; +} CXIdxObjCPropertyDeclInfo; + +typedef struct { + const CXIdxDeclInfo *declInfo; + const CXIdxBaseClassInfo *const *bases; + unsigned numBases; +} CXIdxCXXClassDeclInfo; + +/** + * \brief Data for \see indexEntityReference callback. + */ +typedef enum { + /** + * \brief The entity is referenced directly in user's code. + */ + CXIdxEntityRef_Direct = 1, + /** + * \brief An implicit reference, e.g. a reference of an ObjC method via the + * dot syntax. + */ + CXIdxEntityRef_Implicit = 2 +} CXIdxEntityRefKind; + +/** + * \brief Data for \see indexEntityReference callback. + */ +typedef struct { + CXIdxEntityRefKind kind; + /** + * \brief Reference cursor. + */ + CXCursor cursor; + CXIdxLoc loc; + /** + * \brief The entity that gets referenced. + */ + const CXIdxEntityInfo *referencedEntity; + /** + * \brief Immediate "parent" of the reference. For example: + * + * \code + * Foo *var; + * \endcode + * + * The parent of reference of type 'Foo' is the variable 'var'. + * For references inside statement bodies of functions/methods, + * the parentEntity will be the function/method. + */ + const CXIdxEntityInfo *parentEntity; + /** + * \brief Lexical container context of the reference. + */ + const CXIdxContainerInfo *container; +} CXIdxEntityRefInfo; + +typedef struct { + /** + * \brief Called periodically to check whether indexing should be aborted. + * Should return 0 to continue, and non-zero to abort. + */ + int (*abortQuery)(CXClientData client_data, void *reserved); + + /** + * \brief Called at the end of indexing; passes the complete diagnostic set. + */ + void (*diagnostic)(CXClientData client_data, + CXDiagnosticSet, void *reserved); + + CXIdxClientFile (*enteredMainFile)(CXClientData client_data, + CXFile mainFile, void *reserved); + + /** + * \brief Called when a file gets #included/#imported. + */ + CXIdxClientFile (*ppIncludedFile)(CXClientData client_data, + const CXIdxIncludedFileInfo *); + + /** + * \brief Called when a AST file (PCH or module) gets imported. + * + * AST files will not get indexed (there will not be callbacks to index all + * the entities in an AST file). The recommended action is that, if the AST + * file is not already indexed, to block further indexing and initiate a new + * indexing job specific to the AST file. + */ + CXIdxClientASTFile (*importedASTFile)(CXClientData client_data, + const CXIdxImportedASTFileInfo *); + + /** + * \brief Called at the beginning of indexing a translation unit. + */ + CXIdxClientContainer (*startedTranslationUnit)(CXClientData client_data, + void *reserved); + + void (*indexDeclaration)(CXClientData client_data, + const CXIdxDeclInfo *); + + /** + * \brief Called to index a reference of an entity. + */ + void (*indexEntityReference)(CXClientData client_data, + const CXIdxEntityRefInfo *); + +} IndexerCallbacks; + +CINDEX_LINKAGE int clang_index_isEntityObjCContainerKind(CXIdxEntityKind); +CINDEX_LINKAGE const CXIdxObjCContainerDeclInfo * +clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *); + +CINDEX_LINKAGE const CXIdxObjCInterfaceDeclInfo * +clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *); + +CINDEX_LINKAGE +const CXIdxObjCCategoryDeclInfo * +clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *); + +CINDEX_LINKAGE const CXIdxObjCProtocolRefListInfo * +clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *); + +CINDEX_LINKAGE const CXIdxObjCPropertyDeclInfo * +clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *); + +CINDEX_LINKAGE const CXIdxIBOutletCollectionAttrInfo * +clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *); + +CINDEX_LINKAGE const CXIdxCXXClassDeclInfo * +clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *); + +/** + * \brief For retrieving a custom CXIdxClientContainer attached to a + * container. + */ +CINDEX_LINKAGE CXIdxClientContainer +clang_index_getClientContainer(const CXIdxContainerInfo *); + +/** + * \brief For setting a custom CXIdxClientContainer attached to a + * container. + */ +CINDEX_LINKAGE void +clang_index_setClientContainer(const CXIdxContainerInfo *,CXIdxClientContainer); + +/** + * \brief For retrieving a custom CXIdxClientEntity attached to an entity. + */ +CINDEX_LINKAGE CXIdxClientEntity +clang_index_getClientEntity(const CXIdxEntityInfo *); + +/** + * \brief For setting a custom CXIdxClientEntity attached to an entity. + */ +CINDEX_LINKAGE void +clang_index_setClientEntity(const CXIdxEntityInfo *, CXIdxClientEntity); + +/** + * \brief An indexing action, to be applied to one or multiple translation units + * but not on concurrent threads. If there are threads doing indexing + * concurrently, they should use different CXIndexAction objects. + */ +typedef void *CXIndexAction; + +/** + * \brief An indexing action, to be applied to one or multiple translation units + * but not on concurrent threads. If there are threads doing indexing + * concurrently, they should use different CXIndexAction objects. + * + * \param CIdx The index object with which the index action will be associated. + */ +CINDEX_LINKAGE CXIndexAction clang_IndexAction_create(CXIndex CIdx); + +/** + * \brief Destroy the given index action. + * + * The index action must not be destroyed until all of the translation units + * created within that index action have been destroyed. + */ +CINDEX_LINKAGE void clang_IndexAction_dispose(CXIndexAction); + +typedef enum { + /** + * \brief Used to indicate that no special indexing options are needed. + */ + CXIndexOpt_None = 0x0, + + /** + * \brief Used to indicate that \see indexEntityReference should be invoked + * for only one reference of an entity per source file that does not also + * include a declaration/definition of the entity. + */ + CXIndexOpt_SuppressRedundantRefs = 0x1, + + /** + * \brief Function-local symbols should be indexed. If this is not set + * function-local symbols will be ignored. + */ + CXIndexOpt_IndexFunctionLocalSymbols = 0x2, + + /** + * \brief Implicit function/class template instantiations should be indexed. + * If this is not set, implicit instantiations will be ignored. + */ + CXIndexOpt_IndexImplicitTemplateInstantiations = 0x4, + + /** + * \brief Suppress all compiler warnings when parsing for indexing. + */ + CXIndexOpt_SuppressWarnings = 0x8 +} CXIndexOptFlags; + +/** + * \brief Index the given source file and the translation unit corresponding + * to that file via callbacks implemented through \see IndexerCallbacks. + * + * \param client_data pointer data supplied by the client, which will + * be passed to the invoked callbacks. + * + * \param index_callbacks Pointer to indexing callbacks that the client + * implements. + * + * \param index_callbacks_size Size of \see IndexerCallbacks structure that gets + * passed in index_callbacks. + * + * \param index_options A bitmask of options that affects how indexing is + * performed. This should be a bitwise OR of the CXIndexOpt_XXX flags. + * + * \param out_TU [out] pointer to store a CXTranslationUnit that can be reused + * after indexing is finished. Set to NULL if you do not require it. + * + * \returns If there is a failure from which the there is no recovery, returns + * non-zero, otherwise returns 0. + * + * The rest of the parameters are the same as \see clang_parseTranslationUnit. + */ +CINDEX_LINKAGE int clang_indexSourceFile(CXIndexAction, + CXClientData client_data, + IndexerCallbacks *index_callbacks, + unsigned index_callbacks_size, + unsigned index_options, + const char *source_filename, + const char * const *command_line_args, + int num_command_line_args, + struct CXUnsavedFile *unsaved_files, + unsigned num_unsaved_files, + CXTranslationUnit *out_TU, + unsigned TU_options); + +/** + * \brief Index the given translation unit via callbacks implemented through + * \see IndexerCallbacks. + * + * The order of callback invocations is not guaranteed to be the same as + * when indexing a source file. The high level order will be: + * + * -Preprocessor callbacks invocations + * -Declaration/reference callbacks invocations + * -Diagnostic callback invocations + * + * The parameters are the same as \see clang_indexSourceFile. + * + * \returns If there is a failure from which the there is no recovery, returns + * non-zero, otherwise returns 0. + */ +CINDEX_LINKAGE int clang_indexTranslationUnit(CXIndexAction, + CXClientData client_data, + IndexerCallbacks *index_callbacks, + unsigned index_callbacks_size, + unsigned index_options, + CXTranslationUnit); + +/** + * \brief Retrieve the CXIdxFile, file, line, column, and offset represented by + * the given CXIdxLoc. + * + * If the location refers into a macro expansion, retrieves the + * location of the macro expansion and if it refers into a macro argument + * retrieves the location of the argument. + */ +CINDEX_LINKAGE void clang_indexLoc_getFileLocation(CXIdxLoc loc, + CXIdxClientFile *indexFile, + CXFile *file, + unsigned *line, + unsigned *column, + unsigned *offset); + +/** + * \brief Retrieve the CXSourceLocation represented by the given CXIdxLoc. + */ +CINDEX_LINKAGE +CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc loc); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/cpp/llvm/tools/clang/include/clang-c/Makefile b/cpp/llvm/tools/clang/include/clang-c/Makefile new file mode 100644 index 00000000..b29e29ea --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang-c/Makefile @@ -0,0 +1,38 @@ +CLANG_LEVEL := ../.. +DIRS := + +include $(CLANG_LEVEL)/Makefile + +IntIncludeDir = $(DESTDIR)$(PROJ_internal_prefix)/include + +install-local:: + $(Echo) Installing Clang C API include files + $(Verb) $(MKDIR) $(IntIncludeDir) + $(Verb) if test -d "$(PROJ_SRC_DIR)" ; then \ + cd $(PROJ_SRC_DIR)/.. && \ + for hdr in `find clang-c -type f '!' '(' -name '*~' \ + -o -name '.#*' -o -name '*.in' -o -name '*.txt' \ + -o -name 'Makefile' -o -name '*.td' ')' -print \ + | grep -v CVS | grep -v .svn | grep -v .dir` ; do \ + instdir=`dirname "$(IntIncludeDir)/$$hdr"` ; \ + if test \! -d "$$instdir" ; then \ + $(EchoCmd) Making install directory $$instdir ; \ + $(MKDIR) $$instdir ;\ + fi ; \ + $(DataInstall) $$hdr $(IntIncludeDir)/$$hdr ; \ + done ; \ + fi +ifneq ($(PROJ_SRC_ROOT),$(PROJ_OBJ_ROOT)) + $(Verb) if test -d "$(PROJ_OBJ_ROOT)/tools/clang/include/clang-c" ; then \ + cd $(PROJ_OBJ_ROOT)/tools/clang/include && \ + for hdr in `find clang-c -type f '!' '(' -name 'Makefile' ')' -print \ + | grep -v CVS | grep -v .tmp | grep -v .dir` ; do \ + instdir=`dirname "$(IntIncludeDir)/$$hdr"` ; \ + if test \! -d "$$instdir" ; then \ + $(EchoCmd) Making install directory $$instdir ; \ + $(MKDIR) $$instdir ;\ + fi ; \ + $(DataInstall) $$hdr $(IntIncludeDir)/$$hdr ; \ + done ; \ + fi +endif diff --git a/cpp/llvm/tools/clang/include/clang/ARCMigrate/ARCMT.h b/cpp/llvm/tools/clang/include/clang/ARCMigrate/ARCMT.h new file mode 100644 index 00000000..86a6cbb2 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/ARCMigrate/ARCMT.h @@ -0,0 +1,122 @@ +//===-- ARCMT.h - ARC Migration Rewriter ------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_ARCMIGRATE_ARCMT_H +#define LLVM_CLANG_ARCMIGRATE_ARCMT_H + +#include "clang/ARCMigrate/FileRemapper.h" +#include "clang/Frontend/CompilerInvocation.h" + +namespace clang { + class ASTContext; + class DiagnosticConsumer; + +namespace arcmt { + class MigrationPass; + +/// \brief Creates an AST with the provided CompilerInvocation but with these +/// changes: +/// -if a PCH/PTH is set, the original header is used instead +/// -Automatic Reference Counting mode is enabled +/// +/// It then checks the AST and produces errors/warning for ARC migration issues +/// that the user needs to handle manually. +/// +/// \param emitPremigrationARCErrors if true all ARC errors will get emitted +/// even if the migrator can fix them, but the function will still return false +/// if all ARC errors can be fixed. +/// +/// \param plistOut if non-empty, it is the file path to store the plist with +/// the pre-migration ARC diagnostics. +/// +/// \returns false if no error is produced, true otherwise. +bool checkForManualIssues(CompilerInvocation &CI, + const FrontendInputFile &Input, + DiagnosticConsumer *DiagClient, + bool emitPremigrationARCErrors = false, + StringRef plistOut = StringRef()); + +/// \brief Works similar to checkForManualIssues but instead of checking, it +/// applies automatic modifications to source files to conform to ARC. +/// +/// \returns false if no error is produced, true otherwise. +bool applyTransformations(CompilerInvocation &origCI, + const FrontendInputFile &Input, + DiagnosticConsumer *DiagClient); + +/// \brief Applies automatic modifications and produces temporary files +/// and metadata into the \arg outputDir path. +/// +/// \param emitPremigrationARCErrors if true all ARC errors will get emitted +/// even if the migrator can fix them, but the function will still return false +/// if all ARC errors can be fixed. +/// +/// \param plistOut if non-empty, it is the file path to store the plist with +/// the pre-migration ARC diagnostics. +/// +/// \returns false if no error is produced, true otherwise. +bool migrateWithTemporaryFiles(CompilerInvocation &origCI, + const FrontendInputFile &Input, + DiagnosticConsumer *DiagClient, + StringRef outputDir, + bool emitPremigrationARCErrors, + StringRef plistOut); + +/// \brief Get the set of file remappings from the \arg outputDir path that +/// migrateWithTemporaryFiles produced. +/// +/// \returns false if no error is produced, true otherwise. +bool getFileRemappings(std::vector > &remap, + StringRef outputDir, + DiagnosticConsumer *DiagClient); + +/// \brief Get the set of file remappings from a list of files with remapping +/// info. +/// +/// \returns false if no error is produced, true otherwise. +bool getFileRemappingsFromFileList( + std::vector > &remap, + ArrayRef remapFiles, + DiagnosticConsumer *DiagClient); + +typedef void (*TransformFn)(MigrationPass &pass); + +std::vector getAllTransformations(LangOptions::GCMode OrigGCMode, + bool NoFinalizeRemoval); + +class MigrationProcess { + CompilerInvocation OrigCI; + DiagnosticConsumer *DiagClient; + FileRemapper Remapper; + +public: + MigrationProcess(const CompilerInvocation &CI, DiagnosticConsumer *diagClient, + StringRef outputDir = StringRef()); + + class RewriteListener { + public: + virtual ~RewriteListener(); + + virtual void start(ASTContext &Ctx) { } + virtual void finish() { } + + virtual void insert(SourceLocation loc, StringRef text) { } + virtual void remove(CharSourceRange range) { } + }; + + bool applyTransform(TransformFn trans, RewriteListener *listener = 0); + + FileRemapper &getRemapper() { return Remapper; } +}; + +} // end namespace arcmt + +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/ARCMigrate/ARCMTActions.h b/cpp/llvm/tools/clang/include/clang/ARCMigrate/ARCMTActions.h new file mode 100644 index 00000000..e0752521 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/ARCMigrate/ARCMTActions.h @@ -0,0 +1,77 @@ +//===--- ARCMTActions.h - ARC Migrate Tool Frontend Actions -----*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_ARCMIGRATE_ARCMT_ACTION_H +#define LLVM_CLANG_ARCMIGRATE_ARCMT_ACTION_H + +#include "clang/Frontend/FrontendAction.h" +#include "clang/ARCMigrate/FileRemapper.h" +#include "llvm/ADT/OwningPtr.h" + +namespace clang { +namespace arcmt { + +class CheckAction : public WrapperFrontendAction { +protected: + virtual bool BeginInvocation(CompilerInstance &CI); + +public: + CheckAction(FrontendAction *WrappedAction); +}; + +class ModifyAction : public WrapperFrontendAction { +protected: + virtual bool BeginInvocation(CompilerInstance &CI); + +public: + ModifyAction(FrontendAction *WrappedAction); +}; + +class MigrateSourceAction : public ASTFrontendAction { + FileRemapper Remapper; +protected: + virtual bool BeginInvocation(CompilerInstance &CI); + virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, + StringRef InFile); +}; + +class MigrateAction : public WrapperFrontendAction { + std::string MigrateDir; + std::string PlistOut; + bool EmitPremigrationARCErros; +protected: + virtual bool BeginInvocation(CompilerInstance &CI); + +public: + MigrateAction(FrontendAction *WrappedAction, StringRef migrateDir, + StringRef plistOut, + bool emitPremigrationARCErrors); +}; + +/// \brief Migrates to modern ObjC syntax. +class ObjCMigrateAction : public WrapperFrontendAction { + std::string MigrateDir; + bool MigrateLiterals; + bool MigrateSubscripting; + FileRemapper Remapper; + CompilerInstance *CompInst; +public: + ObjCMigrateAction(FrontendAction *WrappedAction, StringRef migrateDir, + bool migrateLiterals, + bool migrateSubscripting); + +protected: + virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,StringRef InFile); + virtual bool BeginInvocation(CompilerInstance &CI); +}; + +} +} + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/ARCMigrate/FileRemapper.h b/cpp/llvm/tools/clang/include/clang/ARCMigrate/FileRemapper.h new file mode 100644 index 00000000..fe7cfadb --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/ARCMigrate/FileRemapper.h @@ -0,0 +1,80 @@ +//===-- FileRemapper.h - File Remapping Helper ------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_ARCMIGRATE_FILEREMAPPER_H +#define LLVM_CLANG_ARCMIGRATE_FILEREMAPPER_H + +#include "clang/Basic/LLVM.h" +#include "llvm/ADT/OwningPtr.h" +#include "llvm/ADT/PointerUnion.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/StringRef.h" + +namespace llvm { + class MemoryBuffer; +} + +namespace clang { + class FileManager; + class FileEntry; + class DiagnosticsEngine; + class PreprocessorOptions; + +namespace arcmt { + +class FileRemapper { + // FIXME: Reuse the same FileManager for multiple ASTContexts. + OwningPtr FileMgr; + + typedef llvm::PointerUnion Target; + typedef llvm::DenseMap MappingsTy; + MappingsTy FromToMappings; + + llvm::DenseMap ToFromMappings; + +public: + FileRemapper(); + ~FileRemapper(); + + bool initFromDisk(StringRef outputDir, DiagnosticsEngine &Diag, + bool ignoreIfFilesChanged); + bool initFromFile(StringRef filePath, DiagnosticsEngine &Diag, + bool ignoreIfFilesChanged); + bool flushToDisk(StringRef outputDir, DiagnosticsEngine &Diag); + bool flushToFile(StringRef outputPath, DiagnosticsEngine &Diag); + + bool overwriteOriginal(DiagnosticsEngine &Diag, + StringRef outputDir = StringRef()); + + void remap(StringRef filePath, llvm::MemoryBuffer *memBuf); + void remap(StringRef filePath, StringRef newPath); + + void applyMappings(PreprocessorOptions &PPOpts) const; + + void transferMappingsAndClear(PreprocessorOptions &PPOpts); + + void clear(StringRef outputDir = StringRef()); + +private: + void remap(const FileEntry *file, llvm::MemoryBuffer *memBuf); + void remap(const FileEntry *file, const FileEntry *newfile); + + const FileEntry *getOriginalFile(StringRef filePath); + void resetTarget(Target &targ); + + bool report(const Twine &err, DiagnosticsEngine &Diag); + + std::string getRemapInfoFile(StringRef outputDir); +}; + +} // end namespace arcmt + +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/APValue.h b/cpp/llvm/tools/clang/include/clang/AST/APValue.h new file mode 100644 index 00000000..1b6e90cf --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/APValue.h @@ -0,0 +1,446 @@ +//===--- APValue.h - Union class for APFloat/APSInt/Complex -----*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the APValue class. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_APVALUE_H +#define LLVM_CLANG_AST_APVALUE_H + +#include "clang/Basic/LLVM.h" +#include "llvm/ADT/APSInt.h" +#include "llvm/ADT/APFloat.h" +#include "llvm/ADT/PointerIntPair.h" +#include "llvm/ADT/PointerUnion.h" + +namespace clang { + class AddrLabelExpr; + class ASTContext; + class CharUnits; + class DiagnosticBuilder; + class Expr; + class FieldDecl; + class Decl; + class ValueDecl; + class CXXRecordDecl; + class QualType; + +/// APValue - This class implements a discriminated union of [uninitialized] +/// [APSInt] [APFloat], [Complex APSInt] [Complex APFloat], [Expr + Offset], +/// [Vector: N * APValue], [Array: N * APValue] +class APValue { + typedef llvm::APSInt APSInt; + typedef llvm::APFloat APFloat; +public: + enum ValueKind { + Uninitialized, + Int, + Float, + ComplexInt, + ComplexFloat, + LValue, + Vector, + Array, + Struct, + Union, + MemberPointer, + AddrLabelDiff + }; + typedef llvm::PointerUnion LValueBase; + typedef llvm::PointerIntPair BaseOrMemberType; + union LValuePathEntry { + /// BaseOrMember - The FieldDecl or CXXRecordDecl indicating the next item + /// in the path. An opaque value of type BaseOrMemberType. + void *BaseOrMember; + /// ArrayIndex - The array index of the next item in the path. + uint64_t ArrayIndex; + }; + struct NoLValuePath {}; + struct UninitArray {}; + struct UninitStruct {}; +private: + ValueKind Kind; + + struct ComplexAPSInt { + APSInt Real, Imag; + ComplexAPSInt() : Real(1), Imag(1) {} + }; + struct ComplexAPFloat { + APFloat Real, Imag; + ComplexAPFloat() : Real(0.0), Imag(0.0) {} + }; + struct LV; + struct Vec { + APValue *Elts; + unsigned NumElts; + Vec() : Elts(0), NumElts(0) {} + ~Vec() { delete[] Elts; } + }; + struct Arr { + APValue *Elts; + unsigned NumElts, ArrSize; + Arr(unsigned NumElts, unsigned ArrSize); + ~Arr(); + }; + struct StructData { + APValue *Elts; + unsigned NumBases; + unsigned NumFields; + StructData(unsigned NumBases, unsigned NumFields); + ~StructData(); + }; + struct UnionData { + const FieldDecl *Field; + APValue *Value; + UnionData(); + ~UnionData(); + }; + struct AddrLabelDiffData { + const AddrLabelExpr* LHSExpr; + const AddrLabelExpr* RHSExpr; + }; + struct MemberPointerData; + + enum { + MaxSize = (sizeof(ComplexAPSInt) > sizeof(ComplexAPFloat) ? + sizeof(ComplexAPSInt) : sizeof(ComplexAPFloat)) + }; + + union { + void *Aligner; + char Data[MaxSize]; + }; + +public: + APValue() : Kind(Uninitialized) {} + explicit APValue(const APSInt &I) : Kind(Uninitialized) { + MakeInt(); setInt(I); + } + explicit APValue(const APFloat &F) : Kind(Uninitialized) { + MakeFloat(); setFloat(F); + } + explicit APValue(const APValue *E, unsigned N) : Kind(Uninitialized) { + MakeVector(); setVector(E, N); + } + APValue(const APSInt &R, const APSInt &I) : Kind(Uninitialized) { + MakeComplexInt(); setComplexInt(R, I); + } + APValue(const APFloat &R, const APFloat &I) : Kind(Uninitialized) { + MakeComplexFloat(); setComplexFloat(R, I); + } + APValue(const APValue &RHS); + APValue(LValueBase B, const CharUnits &O, NoLValuePath N, unsigned CallIndex) + : Kind(Uninitialized) { + MakeLValue(); setLValue(B, O, N, CallIndex); + } + APValue(LValueBase B, const CharUnits &O, ArrayRef Path, + bool OnePastTheEnd, unsigned CallIndex) + : Kind(Uninitialized) { + MakeLValue(); setLValue(B, O, Path, OnePastTheEnd, CallIndex); + } + APValue(UninitArray, unsigned InitElts, unsigned Size) : Kind(Uninitialized) { + MakeArray(InitElts, Size); + } + APValue(UninitStruct, unsigned B, unsigned M) : Kind(Uninitialized) { + MakeStruct(B, M); + } + explicit APValue(const FieldDecl *D, const APValue &V = APValue()) + : Kind(Uninitialized) { + MakeUnion(); setUnion(D, V); + } + APValue(const ValueDecl *Member, bool IsDerivedMember, + ArrayRef Path) : Kind(Uninitialized) { + MakeMemberPointer(Member, IsDerivedMember, Path); + } + APValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) + : Kind(Uninitialized) { + MakeAddrLabelDiff(); setAddrLabelDiff(LHSExpr, RHSExpr); + } + + ~APValue() { + MakeUninit(); + } + + /// \brief Swaps the contents of this and the given APValue. + void swap(APValue &RHS); + + ValueKind getKind() const { return Kind; } + bool isUninit() const { return Kind == Uninitialized; } + bool isInt() const { return Kind == Int; } + bool isFloat() const { return Kind == Float; } + bool isComplexInt() const { return Kind == ComplexInt; } + bool isComplexFloat() const { return Kind == ComplexFloat; } + bool isLValue() const { return Kind == LValue; } + bool isVector() const { return Kind == Vector; } + bool isArray() const { return Kind == Array; } + bool isStruct() const { return Kind == Struct; } + bool isUnion() const { return Kind == Union; } + bool isMemberPointer() const { return Kind == MemberPointer; } + bool isAddrLabelDiff() const { return Kind == AddrLabelDiff; } + + void dump() const; + void dump(raw_ostream &OS) const; + + void printPretty(raw_ostream &OS, ASTContext &Ctx, QualType Ty) const; + std::string getAsString(ASTContext &Ctx, QualType Ty) const; + + APSInt &getInt() { + assert(isInt() && "Invalid accessor"); + return *(APSInt*)(char*)Data; + } + const APSInt &getInt() const { + return const_cast(this)->getInt(); + } + + APFloat &getFloat() { + assert(isFloat() && "Invalid accessor"); + return *(APFloat*)(char*)Data; + } + const APFloat &getFloat() const { + return const_cast(this)->getFloat(); + } + + APSInt &getComplexIntReal() { + assert(isComplexInt() && "Invalid accessor"); + return ((ComplexAPSInt*)(char*)Data)->Real; + } + const APSInt &getComplexIntReal() const { + return const_cast(this)->getComplexIntReal(); + } + + APSInt &getComplexIntImag() { + assert(isComplexInt() && "Invalid accessor"); + return ((ComplexAPSInt*)(char*)Data)->Imag; + } + const APSInt &getComplexIntImag() const { + return const_cast(this)->getComplexIntImag(); + } + + APFloat &getComplexFloatReal() { + assert(isComplexFloat() && "Invalid accessor"); + return ((ComplexAPFloat*)(char*)Data)->Real; + } + const APFloat &getComplexFloatReal() const { + return const_cast(this)->getComplexFloatReal(); + } + + APFloat &getComplexFloatImag() { + assert(isComplexFloat() && "Invalid accessor"); + return ((ComplexAPFloat*)(char*)Data)->Imag; + } + const APFloat &getComplexFloatImag() const { + return const_cast(this)->getComplexFloatImag(); + } + + const LValueBase getLValueBase() const; + CharUnits &getLValueOffset(); + const CharUnits &getLValueOffset() const { + return const_cast(this)->getLValueOffset(); + } + bool isLValueOnePastTheEnd() const; + bool hasLValuePath() const; + ArrayRef getLValuePath() const; + unsigned getLValueCallIndex() const; + + APValue &getVectorElt(unsigned I) { + assert(isVector() && "Invalid accessor"); + assert(I < getVectorLength() && "Index out of range"); + return ((Vec*)(char*)Data)->Elts[I]; + } + const APValue &getVectorElt(unsigned I) const { + return const_cast(this)->getVectorElt(I); + } + unsigned getVectorLength() const { + assert(isVector() && "Invalid accessor"); + return ((const Vec*)(const void *)Data)->NumElts; + } + + APValue &getArrayInitializedElt(unsigned I) { + assert(isArray() && "Invalid accessor"); + assert(I < getArrayInitializedElts() && "Index out of range"); + return ((Arr*)(char*)Data)->Elts[I]; + } + const APValue &getArrayInitializedElt(unsigned I) const { + return const_cast(this)->getArrayInitializedElt(I); + } + bool hasArrayFiller() const { + return getArrayInitializedElts() != getArraySize(); + } + APValue &getArrayFiller() { + assert(isArray() && "Invalid accessor"); + assert(hasArrayFiller() && "No array filler"); + return ((Arr*)(char*)Data)->Elts[getArrayInitializedElts()]; + } + const APValue &getArrayFiller() const { + return const_cast(this)->getArrayFiller(); + } + unsigned getArrayInitializedElts() const { + assert(isArray() && "Invalid accessor"); + return ((const Arr*)(const void *)Data)->NumElts; + } + unsigned getArraySize() const { + assert(isArray() && "Invalid accessor"); + return ((const Arr*)(const void *)Data)->ArrSize; + } + + unsigned getStructNumBases() const { + assert(isStruct() && "Invalid accessor"); + return ((const StructData*)(const char*)Data)->NumBases; + } + unsigned getStructNumFields() const { + assert(isStruct() && "Invalid accessor"); + return ((const StructData*)(const char*)Data)->NumFields; + } + APValue &getStructBase(unsigned i) { + assert(isStruct() && "Invalid accessor"); + return ((StructData*)(char*)Data)->Elts[i]; + } + APValue &getStructField(unsigned i) { + assert(isStruct() && "Invalid accessor"); + return ((StructData*)(char*)Data)->Elts[getStructNumBases() + i]; + } + const APValue &getStructBase(unsigned i) const { + return const_cast(this)->getStructBase(i); + } + const APValue &getStructField(unsigned i) const { + return const_cast(this)->getStructField(i); + } + + const FieldDecl *getUnionField() const { + assert(isUnion() && "Invalid accessor"); + return ((const UnionData*)(const char*)Data)->Field; + } + APValue &getUnionValue() { + assert(isUnion() && "Invalid accessor"); + return *((UnionData*)(char*)Data)->Value; + } + const APValue &getUnionValue() const { + return const_cast(this)->getUnionValue(); + } + + const ValueDecl *getMemberPointerDecl() const; + bool isMemberPointerToDerivedMember() const; + ArrayRef getMemberPointerPath() const; + + const AddrLabelExpr* getAddrLabelDiffLHS() const { + assert(isAddrLabelDiff() && "Invalid accessor"); + return ((const AddrLabelDiffData*)(const char*)Data)->LHSExpr; + } + const AddrLabelExpr* getAddrLabelDiffRHS() const { + assert(isAddrLabelDiff() && "Invalid accessor"); + return ((const AddrLabelDiffData*)(const char*)Data)->RHSExpr; + } + + void setInt(const APSInt &I) { + assert(isInt() && "Invalid accessor"); + *(APSInt*)(char*)Data = I; + } + void setFloat(const APFloat &F) { + assert(isFloat() && "Invalid accessor"); + *(APFloat*)(char*)Data = F; + } + void setVector(const APValue *E, unsigned N) { + assert(isVector() && "Invalid accessor"); + ((Vec*)(char*)Data)->Elts = new APValue[N]; + ((Vec*)(char*)Data)->NumElts = N; + for (unsigned i = 0; i != N; ++i) + ((Vec*)(char*)Data)->Elts[i] = E[i]; + } + void setComplexInt(const APSInt &R, const APSInt &I) { + assert(R.getBitWidth() == I.getBitWidth() && + "Invalid complex int (type mismatch)."); + assert(isComplexInt() && "Invalid accessor"); + ((ComplexAPSInt*)(char*)Data)->Real = R; + ((ComplexAPSInt*)(char*)Data)->Imag = I; + } + void setComplexFloat(const APFloat &R, const APFloat &I) { + assert(&R.getSemantics() == &I.getSemantics() && + "Invalid complex float (type mismatch)."); + assert(isComplexFloat() && "Invalid accessor"); + ((ComplexAPFloat*)(char*)Data)->Real = R; + ((ComplexAPFloat*)(char*)Data)->Imag = I; + } + void setLValue(LValueBase B, const CharUnits &O, NoLValuePath, + unsigned CallIndex); + void setLValue(LValueBase B, const CharUnits &O, + ArrayRef Path, bool OnePastTheEnd, + unsigned CallIndex); + void setUnion(const FieldDecl *Field, const APValue &Value) { + assert(isUnion() && "Invalid accessor"); + ((UnionData*)(char*)Data)->Field = Field; + *((UnionData*)(char*)Data)->Value = Value; + } + void setAddrLabelDiff(const AddrLabelExpr* LHSExpr, + const AddrLabelExpr* RHSExpr) { + ((AddrLabelDiffData*)(char*)Data)->LHSExpr = LHSExpr; + ((AddrLabelDiffData*)(char*)Data)->RHSExpr = RHSExpr; + } + + /// Assign by swapping from a copy of the RHS. + APValue &operator=(APValue RHS) { + swap(RHS); + return *this; + } + +private: + void DestroyDataAndMakeUninit(); + void MakeUninit() { + if (Kind != Uninitialized) + DestroyDataAndMakeUninit(); + } + void MakeInt() { + assert(isUninit() && "Bad state change"); + new ((void*)Data) APSInt(1); + Kind = Int; + } + void MakeFloat() { + assert(isUninit() && "Bad state change"); + new ((void*)(char*)Data) APFloat(0.0); + Kind = Float; + } + void MakeVector() { + assert(isUninit() && "Bad state change"); + new ((void*)(char*)Data) Vec(); + Kind = Vector; + } + void MakeComplexInt() { + assert(isUninit() && "Bad state change"); + new ((void*)(char*)Data) ComplexAPSInt(); + Kind = ComplexInt; + } + void MakeComplexFloat() { + assert(isUninit() && "Bad state change"); + new ((void*)(char*)Data) ComplexAPFloat(); + Kind = ComplexFloat; + } + void MakeLValue(); + void MakeArray(unsigned InitElts, unsigned Size); + void MakeStruct(unsigned B, unsigned M) { + assert(isUninit() && "Bad state change"); + new ((void*)(char*)Data) StructData(B, M); + Kind = Struct; + } + void MakeUnion() { + assert(isUninit() && "Bad state change"); + new ((void*)(char*)Data) UnionData(); + Kind = Union; + } + void MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember, + ArrayRef Path); + void MakeAddrLabelDiff() { + assert(isUninit() && "Bad state change"); + new ((void*)(char*)Data) AddrLabelDiffData(); + Kind = AddrLabelDiff; + } +}; + +} // end namespace clang. + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/AST.h b/cpp/llvm/tools/clang/include/clang/AST/AST.h new file mode 100644 index 00000000..164c5fbb --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/AST.h @@ -0,0 +1,28 @@ +//===--- AST.h - "Umbrella" header for AST library --------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the interface to the AST classes. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_AST_H +#define LLVM_CLANG_AST_AST_H + +// This header exports all AST interfaces. +#include "clang/AST/ASTContext.h" +#include "clang/AST/Decl.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/DeclObjC.h" +#include "clang/AST/DeclTemplate.h" +#include "clang/AST/Expr.h" +#include "clang/AST/ExprObjC.h" +#include "clang/AST/Type.h" +#include "clang/AST/StmtVisitor.h" + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/ASTConsumer.h b/cpp/llvm/tools/clang/include/clang/AST/ASTConsumer.h new file mode 100644 index 00000000..69a38669 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/ASTConsumer.h @@ -0,0 +1,128 @@ +//===--- ASTConsumer.h - Abstract interface for reading ASTs ----*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the ASTConsumer class. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_ASTCONSUMER_H +#define LLVM_CLANG_AST_ASTCONSUMER_H + +namespace clang { + class ASTContext; + class CXXRecordDecl; + class DeclGroupRef; + class HandleTagDeclDefinition; + class ASTMutationListener; + class ASTDeserializationListener; // layering violation because void* is ugly + class SemaConsumer; // layering violation required for safe SemaConsumer + class TagDecl; + class VarDecl; + class FunctionDecl; + +/// ASTConsumer - This is an abstract interface that should be implemented by +/// clients that read ASTs. This abstraction layer allows the client to be +/// independent of the AST producer (e.g. parser vs AST dump file reader, etc). +class ASTConsumer { + /// \brief Whether this AST consumer also requires information about + /// semantic analysis. + bool SemaConsumer; + + friend class SemaConsumer; + +public: + ASTConsumer() : SemaConsumer(false) { } + + virtual ~ASTConsumer() {} + + /// Initialize - This is called to initialize the consumer, providing the + /// ASTContext. + virtual void Initialize(ASTContext &Context) {} + + /// HandleTopLevelDecl - Handle the specified top-level declaration. This is + /// called by the parser to process every top-level Decl*. Note that D can be + /// the head of a chain of Decls (e.g. for `int a, b` the chain will have two + /// elements). Use Decl::getNextDeclarator() to walk the chain. + /// + /// \returns true to continue parsing, or false to abort parsing. + virtual bool HandleTopLevelDecl(DeclGroupRef D); + + /// HandleInterestingDecl - Handle the specified interesting declaration. This + /// is called by the AST reader when deserializing things that might interest + /// the consumer. The default implementation forwards to HandleTopLevelDecl. + virtual void HandleInterestingDecl(DeclGroupRef D); + + /// HandleTranslationUnit - This method is called when the ASTs for entire + /// translation unit have been parsed. + virtual void HandleTranslationUnit(ASTContext &Ctx) {} + + /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl + /// (e.g. struct, union, enum, class) is completed. This allows the client to + /// hack on the type, which can occur at any point in the file (because these + /// can be defined in declspecs). + virtual void HandleTagDeclDefinition(TagDecl *D) {} + + /// \brief Invoked when a function is implicitly instantiated. + /// Note that at this point point it does not have a body, its body is + /// instantiated at the end of the translation unit and passed to + /// HandleTopLevelDecl. + virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) {} + + /// \brief Handle the specified top-level declaration that occurred inside + /// and ObjC container. + /// The default implementation ignored them. + virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D); + + /// CompleteTentativeDefinition - Callback invoked at the end of a translation + /// unit to notify the consumer that the given tentative definition should be + /// completed. + /// + /// The variable declaration itself will be a tentative + /// definition. If it had an incomplete array type, its type will + /// have already been changed to an array of size 1. However, the + /// declaration remains a tentative definition and has not been + /// modified by the introduction of an implicit zero initializer. + virtual void CompleteTentativeDefinition(VarDecl *D) {} + + /// HandleCXXStaticMemberVarInstantiation - Tell the consumer that this + // variable has been instantiated. + virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D) {} + + /// \brief Callback involved at the end of a translation unit to + /// notify the consumer that a vtable for the given C++ class is + /// required. + /// + /// \param RD The class whose vtable was used. + /// + /// \param DefinitionRequired Whether a definition of this vtable is + /// required in this translation unit; otherwise, it is only needed if + /// it was actually used. + virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {} + + /// \brief If the consumer is interested in entities getting modified after + /// their initial creation, it should return a pointer to + /// an ASTMutationListener here. + virtual ASTMutationListener *GetASTMutationListener() { return 0; } + + /// \brief If the consumer is interested in entities being deserialized from + /// AST files, it should return a pointer to a ASTDeserializationListener here + virtual ASTDeserializationListener *GetASTDeserializationListener() { + return 0; + } + + /// PrintStats - If desired, print any statistics. + virtual void PrintStats() {} + + // Support isa/cast/dyn_cast + static bool classof(const ASTConsumer *) { return true; } +}; + +} // end namespace clang. + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/ASTContext.h b/cpp/llvm/tools/clang/include/clang/AST/ASTContext.h new file mode 100644 index 00000000..96e41c5d --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/ASTContext.h @@ -0,0 +1,1998 @@ +//===--- ASTContext.h - Context to hold long-lived AST nodes ----*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the ASTContext interface. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_ASTCONTEXT_H +#define LLVM_CLANG_AST_ASTCONTEXT_H + +#include "clang/Basic/AddressSpaces.h" +#include "clang/Basic/IdentifierTable.h" +#include "clang/Basic/LangOptions.h" +#include "clang/Basic/OperatorKinds.h" +#include "clang/Basic/PartialDiagnostic.h" +#include "clang/Basic/VersionTuple.h" +#include "clang/AST/Decl.h" +#include "clang/AST/LambdaMangleContext.h" +#include "clang/AST/NestedNameSpecifier.h" +#include "clang/AST/PrettyPrinter.h" +#include "clang/AST/TemplateName.h" +#include "clang/AST/Type.h" +#include "clang/AST/CanonicalType.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/FoldingSet.h" +#include "llvm/ADT/IntrusiveRefCntPtr.h" +#include "llvm/ADT/OwningPtr.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/TinyPtrVector.h" +#include "llvm/Support/Allocator.h" +#include + +namespace llvm { + struct fltSemantics; +} + +namespace clang { + class FileManager; + class ASTRecordLayout; + class BlockExpr; + class CharUnits; + class DiagnosticsEngine; + class Expr; + class ExternalASTSource; + class ASTMutationListener; + class IdentifierTable; + class SelectorTable; + class SourceManager; + class TargetInfo; + class CXXABI; + // Decls + class DeclContext; + class CXXConversionDecl; + class CXXMethodDecl; + class CXXRecordDecl; + class Decl; + class FieldDecl; + class MangleContext; + class ObjCIvarDecl; + class ObjCIvarRefExpr; + class ObjCPropertyDecl; + class ParmVarDecl; + class RecordDecl; + class StoredDeclsMap; + class TagDecl; + class TemplateTemplateParmDecl; + class TemplateTypeParmDecl; + class TranslationUnitDecl; + class TypeDecl; + class TypedefNameDecl; + class UsingDecl; + class UsingShadowDecl; + class UnresolvedSetIterator; + + namespace Builtin { class Context; } + +/// ASTContext - This class holds long-lived AST nodes (such as types and +/// decls) that can be referred to throughout the semantic analysis of a file. +class ASTContext : public RefCountedBase { + ASTContext &this_() { return *this; } + + mutable std::vector Types; + mutable llvm::FoldingSet ExtQualNodes; + mutable llvm::FoldingSet ComplexTypes; + mutable llvm::FoldingSet PointerTypes; + mutable llvm::FoldingSet BlockPointerTypes; + mutable llvm::FoldingSet LValueReferenceTypes; + mutable llvm::FoldingSet RValueReferenceTypes; + mutable llvm::FoldingSet MemberPointerTypes; + mutable llvm::FoldingSet ConstantArrayTypes; + mutable llvm::FoldingSet IncompleteArrayTypes; + mutable std::vector VariableArrayTypes; + mutable llvm::FoldingSet DependentSizedArrayTypes; + mutable llvm::FoldingSet + DependentSizedExtVectorTypes; + mutable llvm::FoldingSet VectorTypes; + mutable llvm::FoldingSet FunctionNoProtoTypes; + mutable llvm::ContextualFoldingSet + FunctionProtoTypes; + mutable llvm::FoldingSet DependentTypeOfExprTypes; + mutable llvm::FoldingSet DependentDecltypeTypes; + mutable llvm::FoldingSet TemplateTypeParmTypes; + mutable llvm::FoldingSet + SubstTemplateTypeParmTypes; + mutable llvm::FoldingSet + SubstTemplateTypeParmPackTypes; + mutable llvm::ContextualFoldingSet + TemplateSpecializationTypes; + mutable llvm::FoldingSet ParenTypes; + mutable llvm::FoldingSet ElaboratedTypes; + mutable llvm::FoldingSet DependentNameTypes; + mutable llvm::ContextualFoldingSet + DependentTemplateSpecializationTypes; + llvm::FoldingSet PackExpansionTypes; + mutable llvm::FoldingSet ObjCObjectTypes; + mutable llvm::FoldingSet ObjCObjectPointerTypes; + mutable llvm::FoldingSet AutoTypes; + mutable llvm::FoldingSet AtomicTypes; + llvm::FoldingSet AttributedTypes; + + mutable llvm::FoldingSet QualifiedTemplateNames; + mutable llvm::FoldingSet DependentTemplateNames; + mutable llvm::FoldingSet + SubstTemplateTemplateParms; + mutable llvm::ContextualFoldingSet + SubstTemplateTemplateParmPacks; + + /// \brief The set of nested name specifiers. + /// + /// This set is managed by the NestedNameSpecifier class. + mutable llvm::FoldingSet NestedNameSpecifiers; + mutable NestedNameSpecifier *GlobalNestedNameSpecifier; + friend class NestedNameSpecifier; + + /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts. + /// This is lazily created. This is intentionally not serialized. + mutable llvm::DenseMap + ASTRecordLayouts; + mutable llvm::DenseMap + ObjCLayouts; + + /// TypeInfoMap - A cache from types to size and alignment information. + typedef llvm::DenseMap > TypeInfoMap; + mutable TypeInfoMap MemoizedTypeInfo; + + /// KeyFunctions - A cache mapping from CXXRecordDecls to key functions. + llvm::DenseMap KeyFunctions; + + /// \brief Mapping from ObjCContainers to their ObjCImplementations. + llvm::DenseMap ObjCImpls; + + /// \brief Mapping from ObjCMethod to its duplicate declaration in the same + /// interface. + llvm::DenseMap ObjCMethodRedecls; + + /// \brief Mapping from __block VarDecls to their copy initialization expr. + llvm::DenseMap BlockVarCopyInits; + + /// \brief Mapping from class scope functions specialization to their + /// template patterns. + llvm::DenseMap + ClassScopeSpecializationPattern; + + /// \brief Representation of a "canonical" template template parameter that + /// is used in canonical template names. + class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode { + TemplateTemplateParmDecl *Parm; + + public: + CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm) + : Parm(Parm) { } + + TemplateTemplateParmDecl *getParam() const { return Parm; } + + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); } + + static void Profile(llvm::FoldingSetNodeID &ID, + TemplateTemplateParmDecl *Parm); + }; + mutable llvm::FoldingSet + CanonTemplateTemplateParms; + + TemplateTemplateParmDecl * + getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const; + + /// \brief The typedef for the __int128_t type. + mutable TypedefDecl *Int128Decl; + + /// \brief The typedef for the __uint128_t type. + mutable TypedefDecl *UInt128Decl; + + /// BuiltinVaListType - built-in va list type. + /// This is initially null and set by Sema::LazilyCreateBuiltin when + /// a builtin that takes a valist is encountered. + QualType BuiltinVaListType; + + /// \brief The typedef for the predefined 'id' type. + mutable TypedefDecl *ObjCIdDecl; + + /// \brief The typedef for the predefined 'SEL' type. + mutable TypedefDecl *ObjCSelDecl; + + /// \brief The typedef for the predefined 'Class' type. + mutable TypedefDecl *ObjCClassDecl; + + /// \brief The typedef for the predefined 'Protocol' class in Objective-C. + mutable ObjCInterfaceDecl *ObjCProtocolClassDecl; + + // Typedefs which may be provided defining the structure of Objective-C + // pseudo-builtins + QualType ObjCIdRedefinitionType; + QualType ObjCClassRedefinitionType; + QualType ObjCSelRedefinitionType; + + QualType ObjCConstantStringType; + mutable RecordDecl *CFConstantStringTypeDecl; + + QualType ObjCNSStringType; + + /// \brief The typedef declaration for the Objective-C "instancetype" type. + TypedefDecl *ObjCInstanceTypeDecl; + + /// \brief The type for the C FILE type. + TypeDecl *FILEDecl; + + /// \brief The type for the C jmp_buf type. + TypeDecl *jmp_bufDecl; + + /// \brief The type for the C sigjmp_buf type. + TypeDecl *sigjmp_bufDecl; + + /// \brief The type for the C ucontext_t type. + TypeDecl *ucontext_tDecl; + + /// \brief Type for the Block descriptor for Blocks CodeGen. + /// + /// Since this is only used for generation of debug info, it is not + /// serialized. + mutable RecordDecl *BlockDescriptorType; + + /// \brief Type for the Block descriptor for Blocks CodeGen. + /// + /// Since this is only used for generation of debug info, it is not + /// serialized. + mutable RecordDecl *BlockDescriptorExtendedType; + + /// \brief Declaration for the CUDA cudaConfigureCall function. + FunctionDecl *cudaConfigureCallDecl; + + TypeSourceInfo NullTypeSourceInfo; + + /// \brief Keeps track of all declaration attributes. + /// + /// Since so few decls have attrs, we keep them in a hash map instead of + /// wasting space in the Decl class. + llvm::DenseMap DeclAttrs; + + /// \brief Keeps track of the static data member templates from which + /// static data members of class template specializations were instantiated. + /// + /// This data structure stores the mapping from instantiations of static + /// data members to the static data member representations within the + /// class template from which they were instantiated along with the kind + /// of instantiation or specialization (a TemplateSpecializationKind - 1). + /// + /// Given the following example: + /// + /// \code + /// template + /// struct X { + /// static T value; + /// }; + /// + /// template + /// T X::value = T(17); + /// + /// int *x = &X::value; + /// \endcode + /// + /// This mapping will contain an entry that maps from the VarDecl for + /// X::value to the corresponding VarDecl for X::value (within the + /// class template X) and will be marked TSK_ImplicitInstantiation. + llvm::DenseMap + InstantiatedFromStaticDataMember; + + /// \brief Keeps track of the declaration from which a UsingDecl was + /// created during instantiation. The source declaration is always + /// a UsingDecl, an UnresolvedUsingValueDecl, or an + /// UnresolvedUsingTypenameDecl. + /// + /// For example: + /// \code + /// template + /// struct A { + /// void f(); + /// }; + /// + /// template + /// struct B : A { + /// using A::f; + /// }; + /// + /// template struct B; + /// \endcode + /// + /// This mapping will contain an entry that maps from the UsingDecl in + /// B to the UnresolvedUsingDecl in B. + llvm::DenseMap InstantiatedFromUsingDecl; + + llvm::DenseMap + InstantiatedFromUsingShadowDecl; + + llvm::DenseMap InstantiatedFromUnnamedFieldDecl; + + /// \brief Mapping that stores the methods overridden by a given C++ + /// member function. + /// + /// Since most C++ member functions aren't virtual and therefore + /// don't override anything, we store the overridden functions in + /// this map on the side rather than within the CXXMethodDecl structure. + typedef llvm::TinyPtrVector CXXMethodVector; + llvm::DenseMap OverriddenMethods; + + /// \brief Mapping from each declaration context to its corresponding lambda + /// mangling context. + llvm::DenseMap LambdaMangleContexts; + + /// \brief Mapping that stores parameterIndex values for ParmVarDecls + /// when that value exceeds the bitfield size of + /// ParmVarDeclBits.ParameterIndex. + typedef llvm::DenseMap ParameterIndexTable; + ParameterIndexTable ParamIndices; + + ImportDecl *FirstLocalImport; + ImportDecl *LastLocalImport; + + TranslationUnitDecl *TUDecl; + + /// SourceMgr - The associated SourceManager object. + SourceManager &SourceMgr; + + /// LangOpts - The language options used to create the AST associated with + /// this ASTContext object. + LangOptions &LangOpts; + + /// \brief The allocator used to create AST objects. + /// + /// AST objects are never destructed; rather, all memory associated with the + /// AST objects will be released when the ASTContext itself is destroyed. + mutable llvm::BumpPtrAllocator BumpAlloc; + + /// \brief Allocator for partial diagnostics. + PartialDiagnostic::StorageAllocator DiagAllocator; + + /// \brief The current C++ ABI. + OwningPtr ABI; + CXXABI *createCXXABI(const TargetInfo &T); + + /// \brief The logical -> physical address space map. + const LangAS::Map *AddrSpaceMap; + + friend class ASTDeclReader; + friend class ASTReader; + friend class ASTWriter; + friend class CXXRecordDecl; + + const TargetInfo *Target; + clang::PrintingPolicy PrintingPolicy; + +public: + IdentifierTable &Idents; + SelectorTable &Selectors; + Builtin::Context &BuiltinInfo; + mutable DeclarationNameTable DeclarationNames; + OwningPtr ExternalSource; + ASTMutationListener *Listener; + + clang::PrintingPolicy getPrintingPolicy() const { return PrintingPolicy; } + + void setPrintingPolicy(clang::PrintingPolicy Policy) { + PrintingPolicy = Policy; + } + + SourceManager& getSourceManager() { return SourceMgr; } + const SourceManager& getSourceManager() const { return SourceMgr; } + void *Allocate(unsigned Size, unsigned Align = 8) const { + return BumpAlloc.Allocate(Size, Align); + } + void Deallocate(void *Ptr) const { } + + /// Return the total amount of physical memory allocated for representing + /// AST nodes and type information. + size_t getASTAllocatedMemory() const { + return BumpAlloc.getTotalMemory(); + } + /// Return the total memory used for various side tables. + size_t getSideTableAllocatedMemory() const; + + PartialDiagnostic::StorageAllocator &getDiagAllocator() { + return DiagAllocator; + } + + const TargetInfo &getTargetInfo() const { return *Target; } + + const LangOptions& getLangOpts() const { return LangOpts; } + + DiagnosticsEngine &getDiagnostics() const; + + FullSourceLoc getFullLoc(SourceLocation Loc) const { + return FullSourceLoc(Loc,SourceMgr); + } + + /// \brief Retrieve the attributes for the given declaration. + AttrVec& getDeclAttrs(const Decl *D); + + /// \brief Erase the attributes corresponding to the given declaration. + void eraseDeclAttrs(const Decl *D); + + /// \brief If this variable is an instantiated static data member of a + /// class template specialization, returns the templated static data member + /// from which it was instantiated. + MemberSpecializationInfo *getInstantiatedFromStaticDataMember( + const VarDecl *Var); + + FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD); + + void setClassScopeSpecializationPattern(FunctionDecl *FD, + FunctionDecl *Pattern); + + /// \brief Note that the static data member \p Inst is an instantiation of + /// the static data member template \p Tmpl of a class template. + void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, + TemplateSpecializationKind TSK, + SourceLocation PointOfInstantiation = SourceLocation()); + + /// \brief If the given using decl is an instantiation of a + /// (possibly unresolved) using decl from a template instantiation, + /// return it. + NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst); + + /// \brief Remember that the using decl \p Inst is an instantiation + /// of the using decl \p Pattern of a class template. + void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern); + + void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, + UsingShadowDecl *Pattern); + UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst); + + FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field); + + void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl); + + /// ZeroBitfieldFollowsNonBitfield - return 'true" if 'FD' is a zero-length + /// bitfield which follows the non-bitfield 'LastFD'. + bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD, + const FieldDecl *LastFD) const; + + /// ZeroBitfieldFollowsBitfield - return 'true" if 'FD' is a zero-length + /// bitfield which follows the bitfield 'LastFD'. + bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD, + const FieldDecl *LastFD) const; + + /// BitfieldFollowsBitfield - return 'true" if 'FD' is a + /// bitfield which follows the bitfield 'LastFD'. + bool BitfieldFollowsBitfield(const FieldDecl *FD, + const FieldDecl *LastFD) const; + + /// NonBitfieldFollowsBitfield - return 'true" if 'FD' is not a + /// bitfield which follows the bitfield 'LastFD'. + bool NonBitfieldFollowsBitfield(const FieldDecl *FD, + const FieldDecl *LastFD) const; + + /// BitfieldFollowsNonBitfield - return 'true" if 'FD' is a + /// bitfield which follows the none bitfield 'LastFD'. + bool BitfieldFollowsNonBitfield(const FieldDecl *FD, + const FieldDecl *LastFD) const; + + // Access to the set of methods overridden by the given C++ method. + typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator; + overridden_cxx_method_iterator + overridden_methods_begin(const CXXMethodDecl *Method) const; + + overridden_cxx_method_iterator + overridden_methods_end(const CXXMethodDecl *Method) const; + + unsigned overridden_methods_size(const CXXMethodDecl *Method) const; + + /// \brief Note that the given C++ \p Method overrides the given \p + /// Overridden method. + void addOverriddenMethod(const CXXMethodDecl *Method, + const CXXMethodDecl *Overridden); + + /// \brief Notify the AST context that a new import declaration has been + /// parsed or implicitly created within this translation unit. + void addedLocalImportDecl(ImportDecl *Import); + + static ImportDecl *getNextLocalImport(ImportDecl *Import) { + return Import->NextLocalImport; + } + + /// \brief Iterator that visits import declarations. + class import_iterator { + ImportDecl *Import; + + public: + typedef ImportDecl *value_type; + typedef ImportDecl *reference; + typedef ImportDecl *pointer; + typedef int difference_type; + typedef std::forward_iterator_tag iterator_category; + + import_iterator() : Import() { } + explicit import_iterator(ImportDecl *Import) : Import(Import) { } + + reference operator*() const { return Import; } + pointer operator->() const { return Import; } + + import_iterator &operator++() { + Import = ASTContext::getNextLocalImport(Import); + return *this; + } + + import_iterator operator++(int) { + import_iterator Other(*this); + ++(*this); + return Other; + } + + friend bool operator==(import_iterator X, import_iterator Y) { + return X.Import == Y.Import; + } + + friend bool operator!=(import_iterator X, import_iterator Y) { + return X.Import != Y.Import; + } + }; + + import_iterator local_import_begin() const { + return import_iterator(FirstLocalImport); + } + import_iterator local_import_end() const { return import_iterator(); } + + TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; } + + + // Builtin Types. + CanQualType VoidTy; + CanQualType BoolTy; + CanQualType CharTy; + CanQualType WCharTy; // [C++ 3.9.1p5], integer type in C99. + CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99. + CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99. + CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty; + CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy; + CanQualType UnsignedLongLongTy, UnsignedInt128Ty; + CanQualType FloatTy, DoubleTy, LongDoubleTy; + CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON + CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy; + CanQualType VoidPtrTy, NullPtrTy; + CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy; + CanQualType PseudoObjectTy, ARCUnbridgedCastTy; + CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy; + CanQualType ObjCBuiltinBoolTy; + + // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand. + mutable QualType AutoDeductTy; // Deduction against 'auto'. + mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'. + + ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t, + IdentifierTable &idents, SelectorTable &sels, + Builtin::Context &builtins, + unsigned size_reserve, + bool DelayInitialization = false); + + ~ASTContext(); + + /// \brief Attach an external AST source to the AST context. + /// + /// The external AST source provides the ability to load parts of + /// the abstract syntax tree as needed from some external storage, + /// e.g., a precompiled header. + void setExternalSource(OwningPtr &Source); + + /// \brief Retrieve a pointer to the external AST source associated + /// with this AST context, if any. + ExternalASTSource *getExternalSource() const { return ExternalSource.get(); } + + /// \brief Attach an AST mutation listener to the AST context. + /// + /// The AST mutation listener provides the ability to track modifications to + /// the abstract syntax tree entities committed after they were initially + /// created. + void setASTMutationListener(ASTMutationListener *Listener) { + this->Listener = Listener; + } + + /// \brief Retrieve a pointer to the AST mutation listener associated + /// with this AST context, if any. + ASTMutationListener *getASTMutationListener() const { return Listener; } + + void PrintStats() const; + const std::vector& getTypes() const { return Types; } + + /// \brief Retrieve the declaration for the 128-bit signed integer type. + TypedefDecl *getInt128Decl() const; + + /// \brief Retrieve the declaration for the 128-bit unsigned integer type. + TypedefDecl *getUInt128Decl() const; + + //===--------------------------------------------------------------------===// + // Type Constructors + //===--------------------------------------------------------------------===// + +private: + /// getExtQualType - Return a type with extended qualifiers. + QualType getExtQualType(const Type *Base, Qualifiers Quals) const; + + QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const; + +public: + /// getAddSpaceQualType - Return the uniqued reference to the type for an + /// address space qualified type with the specified type and address space. + /// The resulting type has a union of the qualifiers from T and the address + /// space. If T already has an address space specifier, it is silently + /// replaced. + QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const; + + /// getObjCGCQualType - Returns the uniqued reference to the type for an + /// objc gc qualified type. The retulting type has a union of the qualifiers + /// from T and the gc attribute. + QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const; + + /// getRestrictType - Returns the uniqued reference to the type for a + /// 'restrict' qualified type. The resulting type has a union of the + /// qualifiers from T and 'restrict'. + QualType getRestrictType(QualType T) const { + return T.withFastQualifiers(Qualifiers::Restrict); + } + + /// getVolatileType - Returns the uniqued reference to the type for a + /// 'volatile' qualified type. The resulting type has a union of the + /// qualifiers from T and 'volatile'. + QualType getVolatileType(QualType T) const { + return T.withFastQualifiers(Qualifiers::Volatile); + } + + /// getConstType - Returns the uniqued reference to the type for a + /// 'const' qualified type. The resulting type has a union of the + /// qualifiers from T and 'const'. + /// + /// It can be reasonably expected that this will always be + /// equivalent to calling T.withConst(). + QualType getConstType(QualType T) const { return T.withConst(); } + + /// adjustFunctionType - Change the ExtInfo on a function type. + const FunctionType *adjustFunctionType(const FunctionType *Fn, + FunctionType::ExtInfo EInfo); + + /// getComplexType - Return the uniqued reference to the type for a complex + /// number with the specified element type. + QualType getComplexType(QualType T) const; + CanQualType getComplexType(CanQualType T) const { + return CanQualType::CreateUnsafe(getComplexType((QualType) T)); + } + + /// getPointerType - Return the uniqued reference to the type for a pointer to + /// the specified type. + QualType getPointerType(QualType T) const; + CanQualType getPointerType(CanQualType T) const { + return CanQualType::CreateUnsafe(getPointerType((QualType) T)); + } + + /// getAtomicType - Return the uniqued reference to the atomic type for + /// the specified type. + QualType getAtomicType(QualType T) const; + + /// getBlockPointerType - Return the uniqued reference to the type for a block + /// of the specified type. + QualType getBlockPointerType(QualType T) const; + + /// This gets the struct used to keep track of the descriptor for pointer to + /// blocks. + QualType getBlockDescriptorType() const; + + /// This gets the struct used to keep track of the extended descriptor for + /// pointer to blocks. + QualType getBlockDescriptorExtendedType() const; + + void setcudaConfigureCallDecl(FunctionDecl *FD) { + cudaConfigureCallDecl = FD; + } + FunctionDecl *getcudaConfigureCallDecl() { + return cudaConfigureCallDecl; + } + + /// This builds the struct used for __block variables. + QualType BuildByRefType(StringRef DeclName, QualType Ty) const; + + /// Returns true iff we need copy/dispose helpers for the given type. + bool BlockRequiresCopying(QualType Ty) const; + + /// getLValueReferenceType - Return the uniqued reference to the type for an + /// lvalue reference to the specified type. + QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true) + const; + + /// getRValueReferenceType - Return the uniqued reference to the type for an + /// rvalue reference to the specified type. + QualType getRValueReferenceType(QualType T) const; + + /// getMemberPointerType - Return the uniqued reference to the type for a + /// member pointer to the specified type in the specified class. The class + /// is a Type because it could be a dependent name. + QualType getMemberPointerType(QualType T, const Type *Cls) const; + + /// getVariableArrayType - Returns a non-unique reference to the type for a + /// variable array of the specified element type. + QualType getVariableArrayType(QualType EltTy, Expr *NumElts, + ArrayType::ArraySizeModifier ASM, + unsigned IndexTypeQuals, + SourceRange Brackets) const; + + /// getDependentSizedArrayType - Returns a non-unique reference to + /// the type for a dependently-sized array of the specified element + /// type. FIXME: We will need these to be uniqued, or at least + /// comparable, at some point. + QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, + ArrayType::ArraySizeModifier ASM, + unsigned IndexTypeQuals, + SourceRange Brackets) const; + + /// getIncompleteArrayType - Returns a unique reference to the type for a + /// incomplete array of the specified element type. + QualType getIncompleteArrayType(QualType EltTy, + ArrayType::ArraySizeModifier ASM, + unsigned IndexTypeQuals) const; + + /// getConstantArrayType - Return the unique reference to the type for a + /// constant array of the specified element type. + QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, + ArrayType::ArraySizeModifier ASM, + unsigned IndexTypeQuals) const; + + /// getVariableArrayDecayedType - Returns a vla type where known sizes + /// are replaced with [*]. + QualType getVariableArrayDecayedType(QualType Ty) const; + + /// getVectorType - Return the unique reference to a vector type of + /// the specified element type and size. VectorType must be a built-in type. + QualType getVectorType(QualType VectorType, unsigned NumElts, + VectorType::VectorKind VecKind) const; + + /// getExtVectorType - Return the unique reference to an extended vector type + /// of the specified element type and size. VectorType must be a built-in + /// type. + QualType getExtVectorType(QualType VectorType, unsigned NumElts) const; + + /// getDependentSizedExtVectorType - Returns a non-unique reference to + /// the type for a dependently-sized vector of the specified element + /// type. FIXME: We will need these to be uniqued, or at least + /// comparable, at some point. + QualType getDependentSizedExtVectorType(QualType VectorType, + Expr *SizeExpr, + SourceLocation AttrLoc) const; + + /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. + /// + QualType getFunctionNoProtoType(QualType ResultTy, + const FunctionType::ExtInfo &Info) const; + + QualType getFunctionNoProtoType(QualType ResultTy) const { + return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo()); + } + + /// getFunctionType - Return a normal function type with a typed + /// argument list. + QualType getFunctionType(QualType ResultTy, + const QualType *Args, unsigned NumArgs, + const FunctionProtoType::ExtProtoInfo &EPI) const; + + /// getTypeDeclType - Return the unique reference to the type for + /// the specified type declaration. + QualType getTypeDeclType(const TypeDecl *Decl, + const TypeDecl *PrevDecl = 0) const { + assert(Decl && "Passed null for Decl param"); + if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); + + if (PrevDecl) { + assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); + Decl->TypeForDecl = PrevDecl->TypeForDecl; + return QualType(PrevDecl->TypeForDecl, 0); + } + + return getTypeDeclTypeSlow(Decl); + } + + /// getTypedefType - Return the unique reference to the type for the + /// specified typedef-name decl. + QualType getTypedefType(const TypedefNameDecl *Decl, + QualType Canon = QualType()) const; + + QualType getRecordType(const RecordDecl *Decl) const; + + QualType getEnumType(const EnumDecl *Decl) const; + + QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const; + + QualType getAttributedType(AttributedType::Kind attrKind, + QualType modifiedType, + QualType equivalentType); + + QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced, + QualType Replacement) const; + QualType getSubstTemplateTypeParmPackType( + const TemplateTypeParmType *Replaced, + const TemplateArgument &ArgPack); + + QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, + bool ParameterPack, + TemplateTypeParmDecl *ParmDecl = 0) const; + + QualType getTemplateSpecializationType(TemplateName T, + const TemplateArgument *Args, + unsigned NumArgs, + QualType Canon = QualType()) const; + + QualType getCanonicalTemplateSpecializationType(TemplateName T, + const TemplateArgument *Args, + unsigned NumArgs) const; + + QualType getTemplateSpecializationType(TemplateName T, + const TemplateArgumentListInfo &Args, + QualType Canon = QualType()) const; + + TypeSourceInfo * + getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, + const TemplateArgumentListInfo &Args, + QualType Canon = QualType()) const; + + QualType getParenType(QualType NamedType) const; + + QualType getElaboratedType(ElaboratedTypeKeyword Keyword, + NestedNameSpecifier *NNS, + QualType NamedType) const; + QualType getDependentNameType(ElaboratedTypeKeyword Keyword, + NestedNameSpecifier *NNS, + const IdentifierInfo *Name, + QualType Canon = QualType()) const; + + QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, + NestedNameSpecifier *NNS, + const IdentifierInfo *Name, + const TemplateArgumentListInfo &Args) const; + QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, + NestedNameSpecifier *NNS, + const IdentifierInfo *Name, + unsigned NumArgs, + const TemplateArgument *Args) const; + + QualType getPackExpansionType(QualType Pattern, + llvm::Optional NumExpansions); + + QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, + ObjCInterfaceDecl *PrevDecl = 0) const; + + QualType getObjCObjectType(QualType Base, + ObjCProtocolDecl * const *Protocols, + unsigned NumProtocols) const; + + /// getObjCObjectPointerType - Return a ObjCObjectPointerType type + /// for the given ObjCObjectType. + QualType getObjCObjectPointerType(QualType OIT) const; + + /// getTypeOfType - GCC extension. + QualType getTypeOfExprType(Expr *e) const; + QualType getTypeOfType(QualType t) const; + + /// getDecltypeType - C++0x decltype. + QualType getDecltypeType(Expr *e, QualType UnderlyingType) const; + + /// getUnaryTransformType - unary type transforms + QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, + UnaryTransformType::UTTKind UKind) const; + + /// getAutoType - C++0x deduced auto type. + QualType getAutoType(QualType DeducedType) const; + + /// getAutoDeductType - C++0x deduction pattern for 'auto' type. + QualType getAutoDeductType() const; + + /// getAutoRRefDeductType - C++0x deduction pattern for 'auto &&' type. + QualType getAutoRRefDeductType() const; + + /// getTagDeclType - Return the unique reference to the type for the + /// specified TagDecl (struct/union/class/enum) decl. + QualType getTagDeclType(const TagDecl *Decl) const; + + /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined + /// in . The sizeof operator requires this (C99 6.5.3.4p4). + CanQualType getSizeType() const; + + /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5), + /// defined in . + CanQualType getIntMaxType() const; + + /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5), + /// defined in . + CanQualType getUIntMaxType() const; + + /// getWCharType - In C++, this returns the unique wchar_t type. In C99, this + /// returns a type compatible with the type defined in as defined + /// by the target. + QualType getWCharType() const { return WCharTy; } + + /// getSignedWCharType - Return the type of "signed wchar_t". + /// Used when in C++, as a GCC extension. + QualType getSignedWCharType() const; + + /// getUnsignedWCharType - Return the type of "unsigned wchar_t". + /// Used when in C++, as a GCC extension. + QualType getUnsignedWCharType() const; + + /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) + /// defined in . Pointer - pointer requires this (C99 6.5.6p9). + QualType getPointerDiffType() const; + + // getCFConstantStringType - Return the C structure type used to represent + // constant CFStrings. + QualType getCFConstantStringType() const; + + /// Get the structure type used to representation CFStrings, or NULL + /// if it hasn't yet been built. + QualType getRawCFConstantStringType() const { + if (CFConstantStringTypeDecl) + return getTagDeclType(CFConstantStringTypeDecl); + return QualType(); + } + void setCFConstantStringType(QualType T); + + // This setter/getter represents the ObjC type for an NSConstantString. + void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl); + QualType getObjCConstantStringInterface() const { + return ObjCConstantStringType; + } + + QualType getObjCNSStringType() const { + return ObjCNSStringType; + } + + void setObjCNSStringType(QualType T) { + ObjCNSStringType = T; + } + + /// \brief Retrieve the type that 'id' has been defined to, which may be + /// different from the built-in 'id' if 'id' has been typedef'd. + QualType getObjCIdRedefinitionType() const { + if (ObjCIdRedefinitionType.isNull()) + return getObjCIdType(); + return ObjCIdRedefinitionType; + } + + /// \brief Set the user-written type that redefines 'id'. + void setObjCIdRedefinitionType(QualType RedefType) { + ObjCIdRedefinitionType = RedefType; + } + + /// \brief Retrieve the type that 'Class' has been defined to, which may be + /// different from the built-in 'Class' if 'Class' has been typedef'd. + QualType getObjCClassRedefinitionType() const { + if (ObjCClassRedefinitionType.isNull()) + return getObjCClassType(); + return ObjCClassRedefinitionType; + } + + /// \brief Set the user-written type that redefines 'SEL'. + void setObjCClassRedefinitionType(QualType RedefType) { + ObjCClassRedefinitionType = RedefType; + } + + /// \brief Retrieve the type that 'SEL' has been defined to, which may be + /// different from the built-in 'SEL' if 'SEL' has been typedef'd. + QualType getObjCSelRedefinitionType() const { + if (ObjCSelRedefinitionType.isNull()) + return getObjCSelType(); + return ObjCSelRedefinitionType; + } + + + /// \brief Set the user-written type that redefines 'SEL'. + void setObjCSelRedefinitionType(QualType RedefType) { + ObjCSelRedefinitionType = RedefType; + } + + /// \brief Retrieve the Objective-C "instancetype" type, if already known; + /// otherwise, returns a NULL type; + QualType getObjCInstanceType() { + return getTypeDeclType(getObjCInstanceTypeDecl()); + } + + /// \brief Retrieve the typedef declaration corresponding to the Objective-C + /// "instancetype" type. + TypedefDecl *getObjCInstanceTypeDecl(); + + /// \brief Set the type for the C FILE type. + void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; } + + /// \brief Retrieve the C FILE type. + QualType getFILEType() const { + if (FILEDecl) + return getTypeDeclType(FILEDecl); + return QualType(); + } + + /// \brief Set the type for the C jmp_buf type. + void setjmp_bufDecl(TypeDecl *jmp_bufDecl) { + this->jmp_bufDecl = jmp_bufDecl; + } + + /// \brief Retrieve the C jmp_buf type. + QualType getjmp_bufType() const { + if (jmp_bufDecl) + return getTypeDeclType(jmp_bufDecl); + return QualType(); + } + + /// \brief Set the type for the C sigjmp_buf type. + void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) { + this->sigjmp_bufDecl = sigjmp_bufDecl; + } + + /// \brief Retrieve the C sigjmp_buf type. + QualType getsigjmp_bufType() const { + if (sigjmp_bufDecl) + return getTypeDeclType(sigjmp_bufDecl); + return QualType(); + } + + /// \brief Set the type for the C ucontext_t type. + void setucontext_tDecl(TypeDecl *ucontext_tDecl) { + this->ucontext_tDecl = ucontext_tDecl; + } + + /// \brief Retrieve the C ucontext_t type. + QualType getucontext_tType() const { + if (ucontext_tDecl) + return getTypeDeclType(ucontext_tDecl); + return QualType(); + } + + /// \brief The result type of logical operations, '<', '>', '!=', etc. + QualType getLogicalOperationType() const { + return getLangOpts().CPlusPlus ? BoolTy : IntTy; + } + + /// getObjCEncodingForType - Emit the ObjC type encoding for the + /// given type into \arg S. If \arg NameFields is specified then + /// record field names are also encoded. + void getObjCEncodingForType(QualType t, std::string &S, + const FieldDecl *Field=0) const; + + void getLegacyIntegralTypeEncoding(QualType &t) const; + + // Put the string version of type qualifiers into S. + void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, + std::string &S) const; + + /// getObjCEncodingForFunctionDecl - Returns the encoded type for this + /// function. This is in the same format as Objective-C method encodings. + /// + /// \returns true if an error occurred (e.g., because one of the parameter + /// types is incomplete), false otherwise. + bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S); + + /// getObjCEncodingForMethodDecl - Return the encoded type for this method + /// declaration. + /// + /// \returns true if an error occurred (e.g., because one of the parameter + /// types is incomplete), false otherwise. + bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S, + bool Extended = false) + const; + + /// getObjCEncodingForBlock - Return the encoded type for this block + /// declaration. + std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const; + + /// getObjCEncodingForPropertyDecl - Return the encoded type for + /// this method declaration. If non-NULL, Container must be either + /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should + /// only be NULL when getting encodings for protocol properties. + void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, + const Decl *Container, + std::string &S) const; + + bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, + ObjCProtocolDecl *rProto) const; + + /// getObjCEncodingTypeSize returns size of type for objective-c encoding + /// purpose in characters. + CharUnits getObjCEncodingTypeSize(QualType t) const; + + /// \brief Retrieve the typedef corresponding to the predefined 'id' type + /// in Objective-C. + TypedefDecl *getObjCIdDecl() const; + + /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by + /// Sema. id is always a (typedef for a) pointer type, a pointer to a struct. + QualType getObjCIdType() const { + return getTypeDeclType(getObjCIdDecl()); + } + + /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type + /// in Objective-C. + TypedefDecl *getObjCSelDecl() const; + + /// \brief Retrieve the type that corresponds to the predefined Objective-C + /// 'SEL' type. + QualType getObjCSelType() const { + return getTypeDeclType(getObjCSelDecl()); + } + + /// \brief Retrieve the typedef declaration corresponding to the predefined + /// Objective-C 'Class' type. + TypedefDecl *getObjCClassDecl() const; + + /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by + /// Sema. 'Class' is always a (typedef for a) pointer type, a pointer to a + /// struct. + QualType getObjCClassType() const { + return getTypeDeclType(getObjCClassDecl()); + } + + /// \brief Retrieve the Objective-C class declaration corresponding to + /// the predefined 'Protocol' class. + ObjCInterfaceDecl *getObjCProtocolDecl() const; + + /// \brief Retrieve the type of the Objective-C "Protocol" class. + QualType getObjCProtoType() const { + return getObjCInterfaceType(getObjCProtocolDecl()); + } + + void setBuiltinVaListType(QualType T); + QualType getBuiltinVaListType() const { return BuiltinVaListType; } + + /// getCVRQualifiedType - Returns a type with additional const, + /// volatile, or restrict qualifiers. + QualType getCVRQualifiedType(QualType T, unsigned CVR) const { + return getQualifiedType(T, Qualifiers::fromCVRMask(CVR)); + } + + /// getQualifiedType - Un-split a SplitQualType. + QualType getQualifiedType(SplitQualType split) const { + return getQualifiedType(split.Ty, split.Quals); + } + + /// getQualifiedType - Returns a type with additional qualifiers. + QualType getQualifiedType(QualType T, Qualifiers Qs) const { + if (!Qs.hasNonFastQualifiers()) + return T.withFastQualifiers(Qs.getFastQualifiers()); + QualifierCollector Qc(Qs); + const Type *Ptr = Qc.strip(T); + return getExtQualType(Ptr, Qc); + } + + /// getQualifiedType - Returns a type with additional qualifiers. + QualType getQualifiedType(const Type *T, Qualifiers Qs) const { + if (!Qs.hasNonFastQualifiers()) + return QualType(T, Qs.getFastQualifiers()); + return getExtQualType(T, Qs); + } + + /// getLifetimeQualifiedType - Returns a type with the given + /// lifetime qualifier. + QualType getLifetimeQualifiedType(QualType type, + Qualifiers::ObjCLifetime lifetime) { + assert(type.getObjCLifetime() == Qualifiers::OCL_None); + assert(lifetime != Qualifiers::OCL_None); + + Qualifiers qs; + qs.addObjCLifetime(lifetime); + return getQualifiedType(type, qs); + } + + DeclarationNameInfo getNameForTemplate(TemplateName Name, + SourceLocation NameLoc) const; + + TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, + UnresolvedSetIterator End) const; + + TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, + bool TemplateKeyword, + TemplateDecl *Template) const; + + TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, + const IdentifierInfo *Name) const; + TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, + OverloadedOperatorKind Operator) const; + TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, + TemplateName replacement) const; + TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, + const TemplateArgument &ArgPack) const; + + enum GetBuiltinTypeError { + GE_None, //< No error + GE_Missing_stdio, //< Missing a type from + GE_Missing_setjmp, //< Missing a type from + GE_Missing_ucontext //< Missing a type from + }; + + /// GetBuiltinType - Return the type for the specified builtin. If + /// IntegerConstantArgs is non-null, it is filled in with a bitmask of + /// arguments to the builtin that are required to be integer constant + /// expressions. + QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, + unsigned *IntegerConstantArgs = 0) const; + +private: + CanQualType getFromTargetType(unsigned Type) const; + std::pair getTypeInfoImpl(const Type *T) const; + + //===--------------------------------------------------------------------===// + // Type Predicates. + //===--------------------------------------------------------------------===// + +public: + /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's + /// garbage collection attribute. + /// + Qualifiers::GC getObjCGCAttrKind(QualType Ty) const; + + /// areCompatibleVectorTypes - Return true if the given vector types + /// are of the same unqualified type or if they are equivalent to the same + /// GCC vector type, ignoring whether they are target-specific (AltiVec or + /// Neon) types. + bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec); + + /// isObjCNSObjectType - Return true if this is an NSObject object with + /// its NSObject attribute set. + static bool isObjCNSObjectType(QualType Ty) { + return Ty->isObjCNSObjectType(); + } + + //===--------------------------------------------------------------------===// + // Type Sizing and Analysis + //===--------------------------------------------------------------------===// + + /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified + /// scalar floating point type. + const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const; + + /// getTypeInfo - Get the size and alignment of the specified complete type in + /// bits. + std::pair getTypeInfo(const Type *T) const; + std::pair getTypeInfo(QualType T) const { + return getTypeInfo(T.getTypePtr()); + } + + /// getTypeSize - Return the size of the specified type, in bits. This method + /// does not work on incomplete types. + uint64_t getTypeSize(QualType T) const { + return getTypeInfo(T).first; + } + uint64_t getTypeSize(const Type *T) const { + return getTypeInfo(T).first; + } + + /// getCharWidth - Return the size of the character type, in bits + uint64_t getCharWidth() const { + return getTypeSize(CharTy); + } + + /// toCharUnitsFromBits - Convert a size in bits to a size in characters. + CharUnits toCharUnitsFromBits(int64_t BitSize) const; + + /// toBits - Convert a size in characters to a size in bits. + int64_t toBits(CharUnits CharSize) const; + + /// getTypeSizeInChars - Return the size of the specified type, in characters. + /// This method does not work on incomplete types. + CharUnits getTypeSizeInChars(QualType T) const; + CharUnits getTypeSizeInChars(const Type *T) const; + + /// getTypeAlign - Return the ABI-specified alignment of a type, in bits. + /// This method does not work on incomplete types. + unsigned getTypeAlign(QualType T) const { + return getTypeInfo(T).second; + } + unsigned getTypeAlign(const Type *T) const { + return getTypeInfo(T).second; + } + + /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in + /// characters. This method does not work on incomplete types. + CharUnits getTypeAlignInChars(QualType T) const; + CharUnits getTypeAlignInChars(const Type *T) const; + + std::pair getTypeInfoInChars(const Type *T) const; + std::pair getTypeInfoInChars(QualType T) const; + + /// getPreferredTypeAlign - Return the "preferred" alignment of the specified + /// type for the current target in bits. This can be different than the ABI + /// alignment in cases where it is beneficial for performance to overalign + /// a data type. + unsigned getPreferredTypeAlign(const Type *T) const; + + /// getDeclAlign - Return a conservative estimate of the alignment of + /// the specified decl. Note that bitfields do not have a valid alignment, so + /// this method will assert on them. + /// If @p RefAsPointee, references are treated like their underlying type + /// (for alignof), else they're treated like pointers (for CodeGen). + CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const; + + /// getASTRecordLayout - Get or compute information about the layout of the + /// specified record (struct/union/class), which indicates its size and field + /// position information. + const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const; + + /// getASTObjCInterfaceLayout - Get or compute information about the + /// layout of the specified Objective-C interface. + const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) + const; + + void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS, + bool Simple = false) const; + + /// getASTObjCImplementationLayout - Get or compute information about + /// the layout of the specified Objective-C implementation. This may + /// differ from the interface if synthesized ivars are present. + const ASTRecordLayout & + getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const; + + /// getKeyFunction - Get the key function for the given record decl, or NULL + /// if there isn't one. The key function is, according to the Itanium C++ ABI + /// section 5.2.3: + /// + /// ...the first non-pure virtual function that is not inline at the point + /// of class definition. + const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD); + + /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits. + uint64_t getFieldOffset(const ValueDecl *FD) const; + + bool isNearlyEmpty(const CXXRecordDecl *RD) const; + + MangleContext *createMangleContext(); + + void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, + SmallVectorImpl &Ivars) const; + + unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const; + void CollectInheritedProtocols(const Decl *CDecl, + llvm::SmallPtrSet &Protocols); + + //===--------------------------------------------------------------------===// + // Type Operators + //===--------------------------------------------------------------------===// + + /// getCanonicalType - Return the canonical (structural) type corresponding to + /// the specified potentially non-canonical type. The non-canonical version + /// of a type may have many "decorated" versions of types. Decorators can + /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed + /// to be free of any of these, allowing two canonical types to be compared + /// for exact equality with a simple pointer comparison. + CanQualType getCanonicalType(QualType T) const { + return CanQualType::CreateUnsafe(T.getCanonicalType()); + } + + const Type *getCanonicalType(const Type *T) const { + return T->getCanonicalTypeInternal().getTypePtr(); + } + + /// getCanonicalParamType - Return the canonical parameter type + /// corresponding to the specific potentially non-canonical one. + /// Qualifiers are stripped off, functions are turned into function + /// pointers, and arrays decay one level into pointers. + CanQualType getCanonicalParamType(QualType T) const; + + /// \brief Determine whether the given types are equivalent. + bool hasSameType(QualType T1, QualType T2) const { + return getCanonicalType(T1) == getCanonicalType(T2); + } + + /// \brief Returns this type as a completely-unqualified array type, + /// capturing the qualifiers in Quals. This will remove the minimal amount of + /// sugaring from the types, similar to the behavior of + /// QualType::getUnqualifiedType(). + /// + /// \param T is the qualified type, which may be an ArrayType + /// + /// \param Quals will receive the full set of qualifiers that were + /// applied to the array. + /// + /// \returns if this is an array type, the completely unqualified array type + /// that corresponds to it. Otherwise, returns T.getUnqualifiedType(). + QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals); + + /// \brief Determine whether the given types are equivalent after + /// cvr-qualifiers have been removed. + bool hasSameUnqualifiedType(QualType T1, QualType T2) const { + return getCanonicalType(T1).getTypePtr() == + getCanonicalType(T2).getTypePtr(); + } + + bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2); + + /// \brief Retrieves the "canonical" nested name specifier for a + /// given nested name specifier. + /// + /// The canonical nested name specifier is a nested name specifier + /// that uniquely identifies a type or namespace within the type + /// system. For example, given: + /// + /// \code + /// namespace N { + /// struct S { + /// template struct X { typename T* type; }; + /// }; + /// } + /// + /// template struct Y { + /// typename N::S::X::type member; + /// }; + /// \endcode + /// + /// Here, the nested-name-specifier for N::S::X:: will be + /// S::X, since 'S' and 'X' are uniquely defined + /// by declarations in the type system and the canonical type for + /// the template type parameter 'T' is template-param-0-0. + NestedNameSpecifier * + getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const; + + /// \brief Retrieves the default calling convention to use for + /// C++ instance methods. + CallingConv getDefaultMethodCallConv(); + + /// \brief Retrieves the canonical representation of the given + /// calling convention. + CallingConv getCanonicalCallConv(CallingConv CC) const { + if (!LangOpts.MRTD && CC == CC_C) + return CC_Default; + return CC; + } + + /// \brief Determines whether two calling conventions name the same + /// calling convention. + bool isSameCallConv(CallingConv lcc, CallingConv rcc) { + return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc)); + } + + /// \brief Retrieves the "canonical" template name that refers to a + /// given template. + /// + /// The canonical template name is the simplest expression that can + /// be used to refer to a given template. For most templates, this + /// expression is just the template declaration itself. For example, + /// the template std::vector can be referred to via a variety of + /// names---std::vector, ::std::vector, vector (if vector is in + /// scope), etc.---but all of these names map down to the same + /// TemplateDecl, which is used to form the canonical template name. + /// + /// Dependent template names are more interesting. Here, the + /// template name could be something like T::template apply or + /// std::allocator::template rebind, where the nested name + /// specifier itself is dependent. In this case, the canonical + /// template name uses the shortest form of the dependent + /// nested-name-specifier, which itself contains all canonical + /// types, values, and templates. + TemplateName getCanonicalTemplateName(TemplateName Name) const; + + /// \brief Determine whether the given template names refer to the same + /// template. + bool hasSameTemplateName(TemplateName X, TemplateName Y); + + /// \brief Retrieve the "canonical" template argument. + /// + /// The canonical template argument is the simplest template argument + /// (which may be a type, value, expression, or declaration) that + /// expresses the value of the argument. + TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) + const; + + /// Type Query functions. If the type is an instance of the specified class, + /// return the Type pointer for the underlying maximally pretty type. This + /// is a member of ASTContext because this may need to do some amount of + /// canonicalization, e.g. to move type qualifiers into the element type. + const ArrayType *getAsArrayType(QualType T) const; + const ConstantArrayType *getAsConstantArrayType(QualType T) const { + return dyn_cast_or_null(getAsArrayType(T)); + } + const VariableArrayType *getAsVariableArrayType(QualType T) const { + return dyn_cast_or_null(getAsArrayType(T)); + } + const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const { + return dyn_cast_or_null(getAsArrayType(T)); + } + const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T) + const { + return dyn_cast_or_null(getAsArrayType(T)); + } + + /// getBaseElementType - Returns the innermost element type of an array type. + /// For example, will return "int" for int[m][n] + QualType getBaseElementType(const ArrayType *VAT) const; + + /// getBaseElementType - Returns the innermost element type of a type + /// (which needn't actually be an array type). + QualType getBaseElementType(QualType QT) const; + + /// getConstantArrayElementCount - Returns number of constant array elements. + uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const; + + /// \brief Perform adjustment on the parameter type of a function. + /// + /// This routine adjusts the given parameter type @p T to the actual + /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], + /// C++ [dcl.fct]p3). The adjusted parameter type is returned. + QualType getAdjustedParameterType(QualType T); + + /// \brief Retrieve the parameter type as adjusted for use in the signature + /// of a function, decaying array and function types and removing top-level + /// cv-qualifiers. + QualType getSignatureParameterType(QualType T); + + /// getArrayDecayedType - Return the properly qualified result of decaying the + /// specified array type to a pointer. This operation is non-trivial when + /// handling typedefs etc. The canonical type of "T" must be an array type, + /// this returns a pointer to a properly qualified element of the array. + /// + /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. + QualType getArrayDecayedType(QualType T) const; + + /// getPromotedIntegerType - Returns the type that Promotable will + /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable + /// integer type. + QualType getPromotedIntegerType(QualType PromotableType) const; + + /// \brief Recurses in pointer/array types until it finds an objc retainable + /// type and returns its ownership. + Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const; + + /// \brief Whether this is a promotable bitfield reference according + /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). + /// + /// \returns the type this bit-field will promote to, or NULL if no + /// promotion occurs. + QualType isPromotableBitField(Expr *E) const; + + /// getIntegerTypeOrder - Returns the highest ranked integer type: + /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If + /// LHS < RHS, return -1. + int getIntegerTypeOrder(QualType LHS, QualType RHS) const; + + /// getFloatingTypeOrder - Compare the rank of the two specified floating + /// point types, ignoring the domain of the type (i.e. 'double' == + /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If + /// LHS < RHS, return -1. + int getFloatingTypeOrder(QualType LHS, QualType RHS) const; + + /// getFloatingTypeOfSizeWithinDomain - Returns a real floating + /// point or a complex type (based on typeDomain/typeSize). + /// 'typeDomain' is a real floating point or complex type. + /// 'typeSize' is a real floating point or complex type. + QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize, + QualType typeDomain) const; + + unsigned getTargetAddressSpace(QualType T) const { + return getTargetAddressSpace(T.getQualifiers()); + } + + unsigned getTargetAddressSpace(Qualifiers Q) const { + return getTargetAddressSpace(Q.getAddressSpace()); + } + + unsigned getTargetAddressSpace(unsigned AS) const { + if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count) + return AS; + else + return (*AddrSpaceMap)[AS - LangAS::Offset]; + } + +private: + // Helper for integer ordering + unsigned getIntegerRank(const Type *T) const; + +public: + + //===--------------------------------------------------------------------===// + // Type Compatibility Predicates + //===--------------------------------------------------------------------===// + + /// Compatibility predicates used to check assignment expressions. + bool typesAreCompatible(QualType T1, QualType T2, + bool CompareUnqualified = false); // C99 6.2.7p1 + + bool propertyTypesAreCompatible(QualType, QualType); + bool typesAreBlockPointerCompatible(QualType, QualType); + + bool isObjCIdType(QualType T) const { + return T == getObjCIdType(); + } + bool isObjCClassType(QualType T) const { + return T == getObjCClassType(); + } + bool isObjCSelType(QualType T) const { + return T == getObjCSelType(); + } + bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS); + bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS, + bool ForCompare); + + bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS); + + // Check the safety of assignment from LHS to RHS + bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, + const ObjCObjectPointerType *RHSOPT); + bool canAssignObjCInterfaces(const ObjCObjectType *LHS, + const ObjCObjectType *RHS); + bool canAssignObjCInterfacesInBlockPointer( + const ObjCObjectPointerType *LHSOPT, + const ObjCObjectPointerType *RHSOPT, + bool BlockReturnType); + bool areComparableObjCPointerTypes(QualType LHS, QualType RHS); + QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, + const ObjCObjectPointerType *RHSOPT); + bool canBindObjCObjectType(QualType To, QualType From); + + // Functions for calculating composite types + QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, + bool Unqualified = false, bool BlockReturnType = false); + QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, + bool Unqualified = false); + QualType mergeFunctionArgumentTypes(QualType, QualType, + bool OfBlockPointer=false, + bool Unqualified = false); + QualType mergeTransparentUnionType(QualType, QualType, + bool OfBlockPointer=false, + bool Unqualified = false); + + QualType mergeObjCGCQualifiers(QualType, QualType); + + bool FunctionTypesMatchOnNSConsumedAttrs( + const FunctionProtoType *FromFunctionType, + const FunctionProtoType *ToFunctionType); + + void ResetObjCLayout(const ObjCContainerDecl *CD) { + ObjCLayouts[CD] = 0; + } + + //===--------------------------------------------------------------------===// + // Integer Predicates + //===--------------------------------------------------------------------===// + + // The width of an integer, as defined in C99 6.2.6.2. This is the number + // of bits in an integer type excluding any padding bits. + unsigned getIntWidth(QualType T) const; + + // Per C99 6.2.5p6, for every signed integer type, there is a corresponding + // unsigned integer type. This method takes a signed type, and returns the + // corresponding unsigned integer type. + QualType getCorrespondingUnsignedType(QualType T); + + //===--------------------------------------------------------------------===// + // Type Iterators. + //===--------------------------------------------------------------------===// + + typedef std::vector::iterator type_iterator; + typedef std::vector::const_iterator const_type_iterator; + + type_iterator types_begin() { return Types.begin(); } + type_iterator types_end() { return Types.end(); } + const_type_iterator types_begin() const { return Types.begin(); } + const_type_iterator types_end() const { return Types.end(); } + + //===--------------------------------------------------------------------===// + // Integer Values + //===--------------------------------------------------------------------===// + + /// MakeIntValue - Make an APSInt of the appropriate width and + /// signedness for the given \arg Value and integer \arg Type. + llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const { + llvm::APSInt Res(getIntWidth(Type), + !Type->isSignedIntegerOrEnumerationType()); + Res = Value; + return Res; + } + + bool isSentinelNullExpr(const Expr *E); + + /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. + ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D); + /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. + ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D); + + /// \brief returns true if there is at lease one @implementation in TU. + bool AnyObjCImplementation() { + return !ObjCImpls.empty(); + } + + /// \brief Set the implementation of ObjCInterfaceDecl. + void setObjCImplementation(ObjCInterfaceDecl *IFaceD, + ObjCImplementationDecl *ImplD); + /// \brief Set the implementation of ObjCCategoryDecl. + void setObjCImplementation(ObjCCategoryDecl *CatD, + ObjCCategoryImplDecl *ImplD); + + /// \brief Get the duplicate declaration of a ObjCMethod in the same + /// interface, or null if non exists. + const ObjCMethodDecl *getObjCMethodRedeclaration( + const ObjCMethodDecl *MD) const { + llvm::DenseMap::const_iterator + I = ObjCMethodRedecls.find(MD); + if (I == ObjCMethodRedecls.end()) + return 0; + return I->second; + } + + void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, + const ObjCMethodDecl *Redecl) { + ObjCMethodRedecls[MD] = Redecl; + } + + /// \brief Returns the objc interface that \arg ND belongs to if it is a + /// objc method/property/ivar etc. that is part of an interface, + /// otherwise returns null. + ObjCInterfaceDecl *getObjContainingInterface(NamedDecl *ND) const; + + /// \brief Set the copy inialization expression of a block var decl. + void setBlockVarCopyInits(VarDecl*VD, Expr* Init); + /// \brief Get the copy initialization expression of VarDecl,or NULL if + /// none exists. + Expr *getBlockVarCopyInits(const VarDecl*VD); + + /// \brief Allocate an uninitialized TypeSourceInfo. + /// + /// The caller should initialize the memory held by TypeSourceInfo using + /// the TypeLoc wrappers. + /// + /// \param T the type that will be the basis for type source info. This type + /// should refer to how the declarator was written in source code, not to + /// what type semantic analysis resolved the declarator to. + /// + /// \param Size the size of the type info to create, or 0 if the size + /// should be calculated based on the type. + TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const; + + /// \brief Allocate a TypeSourceInfo where all locations have been + /// initialized to a given location, which defaults to the empty + /// location. + TypeSourceInfo * + getTrivialTypeSourceInfo(QualType T, + SourceLocation Loc = SourceLocation()) const; + + TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; } + + /// \brief Add a deallocation callback that will be invoked when the + /// ASTContext is destroyed. + /// + /// \brief Callback A callback function that will be invoked on destruction. + /// + /// \brief Data Pointer data that will be provided to the callback function + /// when it is called. + void AddDeallocation(void (*Callback)(void*), void *Data); + + GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD); + GVALinkage GetGVALinkageForVariable(const VarDecl *VD); + + /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH + /// lazily, only when used; this is only relevant for function or file scoped + /// var definitions. + /// + /// \returns true if the function/var must be CodeGen'ed/deserialized even if + /// it is not used. + bool DeclMustBeEmitted(const Decl *D); + + /// \brief Retrieve the lambda mangling number for a lambda expression. + unsigned getLambdaManglingNumber(CXXMethodDecl *CallOperator); + + /// \brief Used by ParmVarDecl to store on the side the + /// index of the parameter when it exceeds the size of the normal bitfield. + void setParameterIndex(const ParmVarDecl *D, unsigned index); + + /// \brief Used by ParmVarDecl to retrieve on the side the + /// index of the parameter when it exceeds the size of the normal bitfield. + unsigned getParameterIndex(const ParmVarDecl *D) const; + + //===--------------------------------------------------------------------===// + // Statistics + //===--------------------------------------------------------------------===// + + /// \brief The number of implicitly-declared default constructors. + static unsigned NumImplicitDefaultConstructors; + + /// \brief The number of implicitly-declared default constructors for + /// which declarations were built. + static unsigned NumImplicitDefaultConstructorsDeclared; + + /// \brief The number of implicitly-declared copy constructors. + static unsigned NumImplicitCopyConstructors; + + /// \brief The number of implicitly-declared copy constructors for + /// which declarations were built. + static unsigned NumImplicitCopyConstructorsDeclared; + + /// \brief The number of implicitly-declared move constructors. + static unsigned NumImplicitMoveConstructors; + + /// \brief The number of implicitly-declared move constructors for + /// which declarations were built. + static unsigned NumImplicitMoveConstructorsDeclared; + + /// \brief The number of implicitly-declared copy assignment operators. + static unsigned NumImplicitCopyAssignmentOperators; + + /// \brief The number of implicitly-declared copy assignment operators for + /// which declarations were built. + static unsigned NumImplicitCopyAssignmentOperatorsDeclared; + + /// \brief The number of implicitly-declared move assignment operators. + static unsigned NumImplicitMoveAssignmentOperators; + + /// \brief The number of implicitly-declared move assignment operators for + /// which declarations were built. + static unsigned NumImplicitMoveAssignmentOperatorsDeclared; + + /// \brief The number of implicitly-declared destructors. + static unsigned NumImplicitDestructors; + + /// \brief The number of implicitly-declared destructors for which + /// declarations were built. + static unsigned NumImplicitDestructorsDeclared; + +private: + ASTContext(const ASTContext&); // DO NOT IMPLEMENT + void operator=(const ASTContext&); // DO NOT IMPLEMENT + +public: + /// \brief Initialize built-in types. + /// + /// This routine may only be invoked once for a given ASTContext object. + /// It is normally invoked by the ASTContext constructor. However, the + /// constructor can be asked to delay initialization, which places the burden + /// of calling this function on the user of that object. + /// + /// \param Target The target + void InitBuiltinTypes(const TargetInfo &Target); + +private: + void InitBuiltinType(CanQualType &R, BuiltinType::Kind K); + + // Return the ObjC type encoding for a given type. + void getObjCEncodingForTypeImpl(QualType t, std::string &S, + bool ExpandPointedToStructures, + bool ExpandStructures, + const FieldDecl *Field, + bool OutermostType = false, + bool EncodingProperty = false, + bool StructField = false, + bool EncodeBlockParameters = false, + bool EncodeClassNames = false) const; + + // Adds the encoding of the structure's members. + void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S, + const FieldDecl *Field, + bool includeVBases = true) const; + + // Adds the encoding of a method parameter or return type. + void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, + QualType T, std::string& S, + bool Extended) const; + + const ASTRecordLayout & + getObjCLayout(const ObjCInterfaceDecl *D, + const ObjCImplementationDecl *Impl) const; + +private: + /// \brief A set of deallocations that should be performed when the + /// ASTContext is destroyed. + SmallVector, 16> Deallocations; + + // FIXME: This currently contains the set of StoredDeclMaps used + // by DeclContext objects. This probably should not be in ASTContext, + // but we include it here so that ASTContext can quickly deallocate them. + llvm::PointerIntPair LastSDM; + + /// \brief A counter used to uniquely identify "blocks". + mutable unsigned int UniqueBlockByRefTypeID; + + friend class DeclContext; + friend class DeclarationNameTable; + void ReleaseDeclContextMaps(); +}; + +/// @brief Utility function for constructing a nullary selector. +static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) { + IdentifierInfo* II = &Ctx.Idents.get(name); + return Ctx.Selectors.getSelector(0, &II); +} + +/// @brief Utility function for constructing an unary selector. +static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) { + IdentifierInfo* II = &Ctx.Idents.get(name); + return Ctx.Selectors.getSelector(1, &II); +} + +} // end namespace clang + +// operator new and delete aren't allowed inside namespaces. + +/// @brief Placement new for using the ASTContext's allocator. +/// +/// This placement form of operator new uses the ASTContext's allocator for +/// obtaining memory. +/// +/// IMPORTANT: These are also declared in clang/AST/Attr.h! Any changes here +/// need to also be made there. +/// +/// We intentionally avoid using a nothrow specification here so that the calls +/// to this operator will not perform a null check on the result -- the +/// underlying allocator never returns null pointers. +/// +/// Usage looks like this (assuming there's an ASTContext 'Context' in scope): +/// @code +/// // Default alignment (8) +/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments); +/// // Specific alignment +/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments); +/// @endcode +/// Please note that you cannot use delete on the pointer; it must be +/// deallocated using an explicit destructor call followed by +/// @c Context.Deallocate(Ptr). +/// +/// @param Bytes The number of bytes to allocate. Calculated by the compiler. +/// @param C The ASTContext that provides the allocator. +/// @param Alignment The alignment of the allocated memory (if the underlying +/// allocator supports it). +/// @return The allocated memory. Could be NULL. +inline void *operator new(size_t Bytes, const clang::ASTContext &C, + size_t Alignment) { + return C.Allocate(Bytes, Alignment); +} +/// @brief Placement delete companion to the new above. +/// +/// This operator is just a companion to the new above. There is no way of +/// invoking it directly; see the new operator for more details. This operator +/// is called implicitly by the compiler if a placement new expression using +/// the ASTContext throws in the object constructor. +inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) { + C.Deallocate(Ptr); +} + +/// This placement form of operator new[] uses the ASTContext's allocator for +/// obtaining memory. +/// +/// We intentionally avoid using a nothrow specification here so that the calls +/// to this operator will not perform a null check on the result -- the +/// underlying allocator never returns null pointers. +/// +/// Usage looks like this (assuming there's an ASTContext 'Context' in scope): +/// @code +/// // Default alignment (8) +/// char *data = new (Context) char[10]; +/// // Specific alignment +/// char *data = new (Context, 4) char[10]; +/// @endcode +/// Please note that you cannot use delete on the pointer; it must be +/// deallocated using an explicit destructor call followed by +/// @c Context.Deallocate(Ptr). +/// +/// @param Bytes The number of bytes to allocate. Calculated by the compiler. +/// @param C The ASTContext that provides the allocator. +/// @param Alignment The alignment of the allocated memory (if the underlying +/// allocator supports it). +/// @return The allocated memory. Could be NULL. +inline void *operator new[](size_t Bytes, const clang::ASTContext& C, + size_t Alignment = 8) { + return C.Allocate(Bytes, Alignment); +} + +/// @brief Placement delete[] companion to the new[] above. +/// +/// This operator is just a companion to the new[] above. There is no way of +/// invoking it directly; see the new[] operator for more details. This operator +/// is called implicitly by the compiler if a placement new[] expression using +/// the ASTContext throws in the object constructor. +inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) { + C.Deallocate(Ptr); +} + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/ASTDiagnostic.h b/cpp/llvm/tools/clang/include/clang/AST/ASTDiagnostic.h new file mode 100644 index 00000000..64e955ea --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/ASTDiagnostic.h @@ -0,0 +1,50 @@ +//===--- ASTDiagnostic.h - Diagnostics for the AST library ------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_DIAGNOSTICAST_H +#define LLVM_CLANG_DIAGNOSTICAST_H + +#include "clang/Basic/Diagnostic.h" + +namespace clang { + namespace diag { + enum { +#define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\ + SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM, +#define ASTSTART +#include "clang/Basic/DiagnosticASTKinds.inc" +#undef DIAG + NUM_BUILTIN_AST_DIAGNOSTICS + }; + } // end namespace diag + + /// \brief DiagnosticsEngine argument formatting function for diagnostics that + /// involve AST nodes. + /// + /// This function formats diagnostic arguments for various AST nodes, + /// including types, declaration names, nested name specifiers, and + /// declaration contexts, into strings that can be printed as part of + /// diagnostics. It is meant to be used as the argument to + /// \c DiagnosticsEngine::SetArgToStringFn(), where the cookie is an \c + /// ASTContext pointer. + void FormatASTNodeDiagnosticArgument( + DiagnosticsEngine::ArgumentKind Kind, + intptr_t Val, + const char *Modifier, + unsigned ModLen, + const char *Argument, + unsigned ArgLen, + const DiagnosticsEngine::ArgumentValue *PrevArgs, + unsigned NumPrevArgs, + SmallVectorImpl &Output, + void *Cookie, + ArrayRef QualTypeVals); +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/ASTImporter.h b/cpp/llvm/tools/clang/include/clang/AST/ASTImporter.h new file mode 100644 index 00000000..7157efe5 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/ASTImporter.h @@ -0,0 +1,278 @@ +//===--- ASTImporter.h - Importing ASTs from other Contexts -----*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the ASTImporter class which imports AST nodes from one +// context into another context. +// +//===----------------------------------------------------------------------===// +#ifndef LLVM_CLANG_AST_ASTIMPORTER_H +#define LLVM_CLANG_AST_ASTIMPORTER_H + +#include "clang/AST/DeclarationName.h" +#include "clang/AST/Type.h" +#include "clang/Basic/SourceLocation.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/SmallVector.h" + +namespace clang { + class ASTContext; + class Decl; + class DeclContext; + class DiagnosticsEngine; + class Expr; + class FileManager; + class IdentifierInfo; + class NestedNameSpecifier; + class Stmt; + class TypeSourceInfo; + + /// \brief Imports selected nodes from one AST context into another context, + /// merging AST nodes where appropriate. + class ASTImporter { + public: + typedef llvm::DenseSet > NonEquivalentDeclSet; + + private: + /// \brief The contexts we're importing to and from. + ASTContext &ToContext, &FromContext; + + /// \brief The file managers we're importing to and from. + FileManager &ToFileManager, &FromFileManager; + + /// \brief Whether to perform a minimal import. + bool Minimal; + + /// \brief Mapping from the already-imported types in the "from" context + /// to the corresponding types in the "to" context. + llvm::DenseMap ImportedTypes; + + /// \brief Mapping from the already-imported declarations in the "from" + /// context to the corresponding declarations in the "to" context. + llvm::DenseMap ImportedDecls; + + /// \brief Mapping from the already-imported statements in the "from" + /// context to the corresponding statements in the "to" context. + llvm::DenseMap ImportedStmts; + + /// \brief Mapping from the already-imported FileIDs in the "from" source + /// manager to the corresponding FileIDs in the "to" source manager. + llvm::DenseMap ImportedFileIDs; + + /// \brief Imported, anonymous tag declarations that are missing their + /// corresponding typedefs. + SmallVector AnonTagsWithPendingTypedefs; + + /// \brief Declaration (from, to) pairs that are known not to be equivalent + /// (which we have already complained about). + NonEquivalentDeclSet NonEquivalentDecls; + + public: + /// \brief Create a new AST importer. + /// + /// \param ToContext The context we'll be importing into. + /// + /// \param ToFileManager The file manager we'll be importing into. + /// + /// \param FromContext The context we'll be importing from. + /// + /// \param FromFileManager The file manager we'll be importing into. + /// + /// \param MinimalImport If true, the importer will attempt to import + /// as little as it can, e.g., by importing declarations as forward + /// declarations that can be completed at a later point. + ASTImporter(ASTContext &ToContext, FileManager &ToFileManager, + ASTContext &FromContext, FileManager &FromFileManager, + bool MinimalImport); + + virtual ~ASTImporter(); + + /// \brief Whether the importer will perform a minimal import, creating + /// to-be-completed forward declarations when possible. + bool isMinimalImport() const { return Minimal; } + + /// \brief Import the given type from the "from" context into the "to" + /// context. + /// + /// \returns the equivalent type in the "to" context, or a NULL type if + /// an error occurred. + QualType Import(QualType FromT); + + /// \brief Import the given type source information from the + /// "from" context into the "to" context. + /// + /// \returns the equivalent type source information in the "to" + /// context, or NULL if an error occurred. + TypeSourceInfo *Import(TypeSourceInfo *FromTSI); + + /// \brief Import the given declaration from the "from" context into the + /// "to" context. + /// + /// \returns the equivalent declaration in the "to" context, or a NULL type + /// if an error occurred. + Decl *Import(Decl *FromD); + + /// \brief Import the given declaration context from the "from" + /// AST context into the "to" AST context. + /// + /// \returns the equivalent declaration context in the "to" + /// context, or a NULL type if an error occurred. + DeclContext *ImportContext(DeclContext *FromDC); + + /// \brief Import the given expression from the "from" context into the + /// "to" context. + /// + /// \returns the equivalent expression in the "to" context, or NULL if + /// an error occurred. + Expr *Import(Expr *FromE); + + /// \brief Import the given statement from the "from" context into the + /// "to" context. + /// + /// \returns the equivalent statement in the "to" context, or NULL if + /// an error occurred. + Stmt *Import(Stmt *FromS); + + /// \brief Import the given nested-name-specifier from the "from" + /// context into the "to" context. + /// + /// \returns the equivalent nested-name-specifier in the "to" + /// context, or NULL if an error occurred. + NestedNameSpecifier *Import(NestedNameSpecifier *FromNNS); + + /// \brief Import the given nested-name-specifier from the "from" + /// context into the "to" context. + /// + /// \returns the equivalent nested-name-specifier in the "to" + /// context. + NestedNameSpecifierLoc Import(NestedNameSpecifierLoc FromNNS); + + /// \brief Import the goven template name from the "from" context into the + /// "to" context. + TemplateName Import(TemplateName From); + + /// \brief Import the given source location from the "from" context into + /// the "to" context. + /// + /// \returns the equivalent source location in the "to" context, or an + /// invalid source location if an error occurred. + SourceLocation Import(SourceLocation FromLoc); + + /// \brief Import the given source range from the "from" context into + /// the "to" context. + /// + /// \returns the equivalent source range in the "to" context, or an + /// invalid source location if an error occurred. + SourceRange Import(SourceRange FromRange); + + /// \brief Import the given declaration name from the "from" + /// context into the "to" context. + /// + /// \returns the equivalent declaration name in the "to" context, + /// or an empty declaration name if an error occurred. + DeclarationName Import(DeclarationName FromName); + + /// \brief Import the given identifier from the "from" context + /// into the "to" context. + /// + /// \returns the equivalent identifier in the "to" context. + IdentifierInfo *Import(const IdentifierInfo *FromId); + + /// \brief Import the given Objective-C selector from the "from" + /// context into the "to" context. + /// + /// \returns the equivalent selector in the "to" context. + Selector Import(Selector FromSel); + + /// \brief Import the given file ID from the "from" context into the + /// "to" context. + /// + /// \returns the equivalent file ID in the source manager of the "to" + /// context. + FileID Import(FileID); + + /// \brief Import the definition of the given declaration, including all of + /// the declarations it contains. + /// + /// This routine is intended to be used + void ImportDefinition(Decl *From); + + /// \brief Cope with a name conflict when importing a declaration into the + /// given context. + /// + /// This routine is invoked whenever there is a name conflict while + /// importing a declaration. The returned name will become the name of the + /// imported declaration. By default, the returned name is the same as the + /// original name, leaving the conflict unresolve such that name lookup + /// for this name is likely to find an ambiguity later. + /// + /// Subclasses may override this routine to resolve the conflict, e.g., by + /// renaming the declaration being imported. + /// + /// \param Name the name of the declaration being imported, which conflicts + /// with other declarations. + /// + /// \param DC the declaration context (in the "to" AST context) in which + /// the name is being imported. + /// + /// \param IDNS the identifier namespace in which the name will be found. + /// + /// \param Decls the set of declarations with the same name as the + /// declaration being imported. + /// + /// \param NumDecls the number of conflicting declarations in \p Decls. + /// + /// \returns the name that the newly-imported declaration should have. + virtual DeclarationName HandleNameConflict(DeclarationName Name, + DeclContext *DC, + unsigned IDNS, + NamedDecl **Decls, + unsigned NumDecls); + + /// \brief Retrieve the context that AST nodes are being imported into. + ASTContext &getToContext() const { return ToContext; } + + /// \brief Retrieve the context that AST nodes are being imported from. + ASTContext &getFromContext() const { return FromContext; } + + /// \brief Retrieve the file manager that AST nodes are being imported into. + FileManager &getToFileManager() const { return ToFileManager; } + + /// \brief Retrieve the file manager that AST nodes are being imported from. + FileManager &getFromFileManager() const { return FromFileManager; } + + /// \brief Report a diagnostic in the "to" context. + DiagnosticBuilder ToDiag(SourceLocation Loc, unsigned DiagID); + + /// \brief Report a diagnostic in the "from" context. + DiagnosticBuilder FromDiag(SourceLocation Loc, unsigned DiagID); + + /// \brief Return the set of declarations that we know are not equivalent. + NonEquivalentDeclSet &getNonEquivalentDecls() { return NonEquivalentDecls; } + + /// \brief Called for ObjCInterfaceDecl, ObjCProtocolDecl, and TagDecl. + /// Mark the Decl as complete, filling it in as much as possible. + /// + /// \param D A declaration in the "to" context. + virtual void CompleteDecl(Decl* D); + + /// \brief Note that we have imported the "from" declaration by mapping it + /// to the (potentially-newly-created) "to" declaration. + /// + /// Subclasses can override this function to observe all of the \c From -> + /// \c To declaration mappings as they are imported. + virtual Decl *Imported(Decl *From, Decl *To); + + /// \brief Determine whether the given types are structurally + /// equivalent. + bool IsStructurallyEquivalent(QualType From, QualType To); + }; +} + +#endif // LLVM_CLANG_AST_ASTIMPORTER_H diff --git a/cpp/llvm/tools/clang/include/clang/AST/ASTMutationListener.h b/cpp/llvm/tools/clang/include/clang/AST/ASTMutationListener.h new file mode 100644 index 00000000..cb038a0a --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/ASTMutationListener.h @@ -0,0 +1,84 @@ +//===--- ASTMutationListener.h - AST Mutation Interface --------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the ASTMutationListener interface. +// +//===----------------------------------------------------------------------===// +#ifndef LLVM_CLANG_AST_ASTMUTATIONLISTENER_H +#define LLVM_CLANG_AST_ASTMUTATIONLISTENER_H + +namespace clang { + class Decl; + class DeclContext; + class TagDecl; + class CXXRecordDecl; + class ClassTemplateDecl; + class ClassTemplateSpecializationDecl; + class FunctionDecl; + class FunctionTemplateDecl; + class ObjCCategoryDecl; + class ObjCInterfaceDecl; + class ObjCContainerDecl; + class ObjCPropertyDecl; + +/// \brief An abstract interface that should be implemented by listeners +/// that want to be notified when an AST entity gets modified after its +/// initial creation. +class ASTMutationListener { +public: + virtual ~ASTMutationListener(); + + /// \brief A new TagDecl definition was completed. + virtual void CompletedTagDefinition(const TagDecl *D) { } + + /// \brief A new declaration with name has been added to a DeclContext. + virtual void AddedVisibleDecl(const DeclContext *DC, const Decl *D) {} + + /// \brief An implicit member was added after the definition was completed. + virtual void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {} + + /// \brief A template specialization (or partial one) was added to the + /// template declaration. + virtual void AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, + const ClassTemplateSpecializationDecl *D) {} + + /// \brief A template specialization (or partial one) was added to the + /// template declaration. + virtual void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, + const FunctionDecl *D) {} + + /// \brief An implicit member got a definition. + virtual void CompletedImplicitDefinition(const FunctionDecl *D) {} + + /// \brief A static data member was implicitly instantiated. + virtual void StaticDataMemberInstantiated(const VarDecl *D) {} + + /// \brief A new objc category class was added for an interface. + virtual void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, + const ObjCInterfaceDecl *IFD) {} + + /// \brief A objc class extension redeclared or introduced a property. + /// + /// \param Prop the property in the class extension + /// + /// \param OrigProp the property from the original interface that was declared + /// or null if the property was introduced. + /// + /// \param ClassExt the class extension. + virtual void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop, + const ObjCPropertyDecl *OrigProp, + const ObjCCategoryDecl *ClassExt) {} + + // NOTE: If new methods are added they should also be added to + // MultiplexASTMutationListener. +}; + +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/ASTVector.h b/cpp/llvm/tools/clang/include/clang/AST/ASTVector.h new file mode 100644 index 00000000..217dfade --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/ASTVector.h @@ -0,0 +1,397 @@ +//===- ASTVector.h - Vector that uses ASTContext for allocation --*- C++ -*-=// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file provides ASTVector, a vector ADT whose contents are +// allocated using the allocator associated with an ASTContext.. +// +//===----------------------------------------------------------------------===// + +// FIXME: Most of this is copy-and-paste from BumpVector.h and SmallVector.h. +// We can refactor this core logic into something common. + +#ifndef LLVM_CLANG_AST_VECTOR +#define LLVM_CLANG_AST_VECTOR + +#include "llvm/Support/type_traits.h" +#include "llvm/Support/Allocator.h" +#include "llvm/ADT/PointerIntPair.h" +#include +#include +#include + +#ifdef _MSC_VER +namespace std { +#if _MSC_VER <= 1310 + // Work around flawed VC++ implementation of std::uninitialized_copy. Define + // additional overloads so that elements with pointer types are recognized as + // scalars and not objects, causing bizarre type conversion errors. + template + inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) { + _Scalar_ptr_iterator_tag _Cat; + return _Cat; + } + + template + inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) { + _Scalar_ptr_iterator_tag _Cat; + return _Cat; + } +#else + // FIXME: It is not clear if the problem is fixed in VS 2005. What is clear + // is that the above hack won't work if it wasn't fixed. +#endif +} +#endif + +namespace clang { + +template +class ASTVector { + T *Begin, *End, *Capacity; + + void setEnd(T *P) { this->End = P; } + +public: + // Default ctor - Initialize to empty. + explicit ASTVector(ASTContext &C, unsigned N = 0) + : Begin(NULL), End(NULL), Capacity(NULL) { + reserve(C, N); + } + + ~ASTVector() { + if (llvm::is_class::value) { + // Destroy the constructed elements in the vector. + destroy_range(Begin, End); + } + } + + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef T value_type; + typedef T* iterator; + typedef const T* const_iterator; + + typedef std::reverse_iterator const_reverse_iterator; + typedef std::reverse_iterator reverse_iterator; + + typedef T& reference; + typedef const T& const_reference; + typedef T* pointer; + typedef const T* const_pointer; + + // forward iterator creation methods. + iterator begin() { return Begin; } + const_iterator begin() const { return Begin; } + iterator end() { return End; } + const_iterator end() const { return End; } + + // reverse iterator creation methods. + reverse_iterator rbegin() { return reverse_iterator(end()); } + const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); } + reverse_iterator rend() { return reverse_iterator(begin()); } + const_reverse_iterator rend() const { return const_reverse_iterator(begin());} + + bool empty() const { return Begin == End; } + size_type size() const { return End-Begin; } + + reference operator[](unsigned idx) { + assert(Begin + idx < End); + return Begin[idx]; + } + const_reference operator[](unsigned idx) const { + assert(Begin + idx < End); + return Begin[idx]; + } + + reference front() { + return begin()[0]; + } + const_reference front() const { + return begin()[0]; + } + + reference back() { + return end()[-1]; + } + const_reference back() const { + return end()[-1]; + } + + void pop_back() { + --End; + End->~T(); + } + + T pop_back_val() { + T Result = back(); + pop_back(); + return Result; + } + + void clear() { + if (llvm::is_class::value) { + destroy_range(Begin, End); + } + End = Begin; + } + + /// data - Return a pointer to the vector's buffer, even if empty(). + pointer data() { + return pointer(Begin); + } + + /// data - Return a pointer to the vector's buffer, even if empty(). + const_pointer data() const { + return const_pointer(Begin); + } + + void push_back(const_reference Elt, ASTContext &C) { + if (End < Capacity) { + Retry: + new (End) T(Elt); + ++End; + return; + } + grow(C); + goto Retry; + } + + void reserve(ASTContext &C, unsigned N) { + if (unsigned(Capacity-Begin) < N) + grow(C, N); + } + + /// capacity - Return the total number of elements in the currently allocated + /// buffer. + size_t capacity() const { return Capacity - Begin; } + + /// append - Add the specified range to the end of the SmallVector. + /// + template + void append(ASTContext &C, in_iter in_start, in_iter in_end) { + size_type NumInputs = std::distance(in_start, in_end); + + if (NumInputs == 0) + return; + + // Grow allocated space if needed. + if (NumInputs > size_type(this->capacity_ptr()-this->end())) + this->grow(C, this->size()+NumInputs); + + // Copy the new elements over. + // TODO: NEED To compile time dispatch on whether in_iter is a random access + // iterator to use the fast uninitialized_copy. + std::uninitialized_copy(in_start, in_end, this->end()); + this->setEnd(this->end() + NumInputs); + } + + /// append - Add the specified range to the end of the SmallVector. + /// + void append(ASTContext &C, size_type NumInputs, const T &Elt) { + // Grow allocated space if needed. + if (NumInputs > size_type(this->capacity_ptr()-this->end())) + this->grow(C, this->size()+NumInputs); + + // Copy the new elements over. + std::uninitialized_fill_n(this->end(), NumInputs, Elt); + this->setEnd(this->end() + NumInputs); + } + + /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory + /// starting with "Dest", constructing elements into it as needed. + template + static void uninitialized_copy(It1 I, It1 E, It2 Dest) { + std::uninitialized_copy(I, E, Dest); + } + + iterator insert(ASTContext &C, iterator I, const T &Elt) { + if (I == this->end()) { // Important special case for empty vector. + push_back(Elt); + return this->end()-1; + } + + if (this->EndX < this->CapacityX) { + Retry: + new (this->end()) T(this->back()); + this->setEnd(this->end()+1); + // Push everything else over. + std::copy_backward(I, this->end()-1, this->end()); + *I = Elt; + return I; + } + size_t EltNo = I-this->begin(); + this->grow(C); + I = this->begin()+EltNo; + goto Retry; + } + + iterator insert(ASTContext &C, iterator I, size_type NumToInsert, + const T &Elt) { + if (I == this->end()) { // Important special case for empty vector. + append(C, NumToInsert, Elt); + return this->end()-1; + } + + // Convert iterator to elt# to avoid invalidating iterator when we reserve() + size_t InsertElt = I - this->begin(); + + // Ensure there is enough space. + reserve(C, static_cast(this->size() + NumToInsert)); + + // Uninvalidate the iterator. + I = this->begin()+InsertElt; + + // If there are more elements between the insertion point and the end of the + // range than there are being inserted, we can use a simple approach to + // insertion. Since we already reserved space, we know that this won't + // reallocate the vector. + if (size_t(this->end()-I) >= NumToInsert) { + T *OldEnd = this->end(); + append(C, this->end()-NumToInsert, this->end()); + + // Copy the existing elements that get replaced. + std::copy_backward(I, OldEnd-NumToInsert, OldEnd); + + std::fill_n(I, NumToInsert, Elt); + return I; + } + + // Otherwise, we're inserting more elements than exist already, and we're + // not inserting at the end. + + // Copy over the elements that we're about to overwrite. + T *OldEnd = this->end(); + this->setEnd(this->end() + NumToInsert); + size_t NumOverwritten = OldEnd-I; + this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten); + + // Replace the overwritten part. + std::fill_n(I, NumOverwritten, Elt); + + // Insert the non-overwritten middle part. + std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt); + return I; + } + + template + iterator insert(ASTContext &C, iterator I, ItTy From, ItTy To) { + if (I == this->end()) { // Important special case for empty vector. + append(C, From, To); + return this->end()-1; + } + + size_t NumToInsert = std::distance(From, To); + // Convert iterator to elt# to avoid invalidating iterator when we reserve() + size_t InsertElt = I - this->begin(); + + // Ensure there is enough space. + reserve(C, static_cast(this->size() + NumToInsert)); + + // Uninvalidate the iterator. + I = this->begin()+InsertElt; + + // If there are more elements between the insertion point and the end of the + // range than there are being inserted, we can use a simple approach to + // insertion. Since we already reserved space, we know that this won't + // reallocate the vector. + if (size_t(this->end()-I) >= NumToInsert) { + T *OldEnd = this->end(); + append(C, this->end()-NumToInsert, this->end()); + + // Copy the existing elements that get replaced. + std::copy_backward(I, OldEnd-NumToInsert, OldEnd); + + std::copy(From, To, I); + return I; + } + + // Otherwise, we're inserting more elements than exist already, and we're + // not inserting at the end. + + // Copy over the elements that we're about to overwrite. + T *OldEnd = this->end(); + this->setEnd(this->end() + NumToInsert); + size_t NumOverwritten = OldEnd-I; + this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten); + + // Replace the overwritten part. + for (; NumOverwritten > 0; --NumOverwritten) { + *I = *From; + ++I; ++From; + } + + // Insert the non-overwritten middle part. + this->uninitialized_copy(From, To, OldEnd); + return I; + } + + void resize(ASTContext &C, unsigned N, const T &NV) { + if (N < this->size()) { + this->destroy_range(this->begin()+N, this->end()); + this->setEnd(this->begin()+N); + } else if (N > this->size()) { + if (this->capacity() < N) + this->grow(C, N); + construct_range(this->end(), this->begin()+N, NV); + this->setEnd(this->begin()+N); + } + } + +private: + /// grow - double the size of the allocated memory, guaranteeing space for at + /// least one more element or MinSize if specified. + void grow(ASTContext &C, size_type MinSize = 1); + + void construct_range(T *S, T *E, const T &Elt) { + for (; S != E; ++S) + new (S) T(Elt); + } + + void destroy_range(T *S, T *E) { + while (S != E) { + --E; + E->~T(); + } + } + +protected: + iterator capacity_ptr() { return (iterator)this->Capacity; } +}; + +// Define this out-of-line to dissuade the C++ compiler from inlining it. +template +void ASTVector::grow(ASTContext &C, size_t MinSize) { + size_t CurCapacity = Capacity-Begin; + size_t CurSize = size(); + size_t NewCapacity = 2*CurCapacity; + if (NewCapacity < MinSize) + NewCapacity = MinSize; + + // Allocate the memory from the ASTContext. + T *NewElts = new (C) T[NewCapacity]; + + // Copy the elements over. + if (llvm::is_class::value) { + std::uninitialized_copy(Begin, End, NewElts); + // Destroy the original elements. + destroy_range(Begin, End); + } + else { + // Use memcpy for PODs (std::uninitialized_copy optimizes to memmove). + memcpy(NewElts, Begin, CurSize * sizeof(T)); + } + + C.Deallocate(Begin); + Begin = NewElts; + End = NewElts+CurSize; + Capacity = Begin+NewCapacity; +} + +} // end: clang namespace +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/Attr.h b/cpp/llvm/tools/clang/include/clang/AST/Attr.h new file mode 100644 index 00000000..ef1aa256 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/Attr.h @@ -0,0 +1,254 @@ +//===--- Attr.h - Classes for representing expressions ----------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the Attr interface and subclasses. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_ATTR_H +#define LLVM_CLANG_AST_ATTR_H + +#include "clang/Basic/LLVM.h" +#include "clang/Basic/AttrKinds.h" +#include "clang/AST/Type.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Basic/VersionTuple.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/StringSwitch.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/raw_ostream.h" +#include +#include +#include + +namespace clang { + class ASTContext; + class IdentifierInfo; + class ObjCInterfaceDecl; + class Expr; + class QualType; + class FunctionDecl; + class TypeSourceInfo; +} + +// Defined in ASTContext.h +void *operator new(size_t Bytes, const clang::ASTContext &C, + size_t Alignment = 16); +// FIXME: Being forced to not have a default argument here due to redeclaration +// rules on default arguments sucks +void *operator new[](size_t Bytes, const clang::ASTContext &C, + size_t Alignment); + +// It is good practice to pair new/delete operators. Also, MSVC gives many +// warnings if a matching delete overload is not declared, even though the +// throw() spec guarantees it will not be implicitly called. +void operator delete(void *Ptr, const clang::ASTContext &C, size_t); +void operator delete[](void *Ptr, const clang::ASTContext &C, size_t); + +namespace clang { + +/// Attr - This represents one attribute. +class Attr { +private: + SourceRange Range; + unsigned AttrKind : 16; + +protected: + bool Inherited : 1; + + virtual ~Attr(); + + void* operator new(size_t bytes) throw() { + llvm_unreachable("Attrs cannot be allocated with regular 'new'."); + } + void operator delete(void* data) throw() { + llvm_unreachable("Attrs cannot be released with regular 'delete'."); + } + +public: + // Forward so that the regular new and delete do not hide global ones. + void* operator new(size_t Bytes, ASTContext &C, + size_t Alignment = 16) throw() { + return ::operator new(Bytes, C, Alignment); + } + void operator delete(void *Ptr, ASTContext &C, + size_t Alignment) throw() { + return ::operator delete(Ptr, C, Alignment); + } + +protected: + Attr(attr::Kind AK, SourceRange R) + : Range(R), AttrKind(AK), Inherited(false) {} + +public: + + attr::Kind getKind() const { + return static_cast(AttrKind); + } + + SourceLocation getLocation() const { return Range.getBegin(); } + SourceRange getRange() const { return Range; } + void setRange(SourceRange R) { Range = R; } + + bool isInherited() const { return Inherited; } + + // Clone this attribute. + virtual Attr* clone(ASTContext &C) const = 0; + + virtual bool isLateParsed() const { return false; } + + // Pretty print this attribute. + virtual void printPretty(llvm::raw_ostream &OS, ASTContext &C) const = 0; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Attr *) { return true; } +}; + +class InheritableAttr : public Attr { + virtual void anchor(); +protected: + InheritableAttr(attr::Kind AK, SourceRange R) + : Attr(AK, R) {} + +public: + void setInherited(bool I) { Inherited = I; } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Attr *A) { + return A->getKind() <= attr::LAST_INHERITABLE; + } + static bool classof(const InheritableAttr *) { return true; } +}; + +class InheritableParamAttr : public InheritableAttr { + virtual void anchor(); +protected: + InheritableParamAttr(attr::Kind AK, SourceRange R) + : InheritableAttr(AK, R) {} + +public: + // Implement isa/cast/dyncast/etc. + static bool classof(const Attr *A) { + return A->getKind() <= attr::LAST_INHERITABLE_PARAM; + } + static bool classof(const InheritableParamAttr *) { return true; } +}; + +#include "clang/AST/Attrs.inc" + +/// AttrVec - A vector of Attr, which is how they are stored on the AST. +typedef SmallVector AttrVec; +typedef SmallVector ConstAttrVec; + +/// DestroyAttrs - Destroy the contents of an AttrVec. +inline void DestroyAttrs (AttrVec& V, ASTContext &C) { +} + +/// specific_attr_iterator - Iterates over a subrange of an AttrVec, only +/// providing attributes that are of a specifc type. +template +class specific_attr_iterator { + /// Current - The current, underlying iterator. + /// In order to ensure we don't dereference an invalid iterator unless + /// specifically requested, we don't necessarily advance this all the + /// way. Instead, we advance it when an operation is requested; if the + /// operation is acting on what should be a past-the-end iterator, + /// then we offer no guarantees, but this way we do not dererence a + /// past-the-end iterator when we move to a past-the-end position. + mutable AttrVec::const_iterator Current; + + void AdvanceToNext() const { + while (!isa(*Current)) + ++Current; + } + + void AdvanceToNext(AttrVec::const_iterator I) const { + while (Current != I && !isa(*Current)) + ++Current; + } + +public: + typedef SpecificAttr* value_type; + typedef SpecificAttr* reference; + typedef SpecificAttr* pointer; + typedef std::forward_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + + specific_attr_iterator() : Current() { } + explicit specific_attr_iterator(AttrVec::const_iterator i) : Current(i) { } + + reference operator*() const { + AdvanceToNext(); + return cast(*Current); + } + pointer operator->() const { + AdvanceToNext(); + return cast(*Current); + } + + specific_attr_iterator& operator++() { + ++Current; + return *this; + } + specific_attr_iterator operator++(int) { + specific_attr_iterator Tmp(*this); + ++(*this); + return Tmp; + } + + friend bool operator==(specific_attr_iterator Left, + specific_attr_iterator Right) { + if (Left.Current < Right.Current) + Left.AdvanceToNext(Right.Current); + else + Right.AdvanceToNext(Left.Current); + return Left.Current == Right.Current; + } + friend bool operator!=(specific_attr_iterator Left, + specific_attr_iterator Right) { + return !(Left == Right); + } +}; + +template +inline specific_attr_iterator specific_attr_begin(const AttrVec& vec) { + return specific_attr_iterator(vec.begin()); +} +template +inline specific_attr_iterator specific_attr_end(const AttrVec& vec) { + return specific_attr_iterator(vec.end()); +} + +template +inline bool hasSpecificAttr(const AttrVec& vec) { + return specific_attr_begin(vec) != specific_attr_end(vec); +} +template +inline T *getSpecificAttr(const AttrVec& vec) { + specific_attr_iterator i = specific_attr_begin(vec); + if (i != specific_attr_end(vec)) + return *i; + else + return 0; +} + +/// getMaxAlignment - Returns the highest alignment value found among +/// AlignedAttrs in an AttrVec, or 0 if there are none. +inline unsigned getMaxAttrAlignment(const AttrVec& V, ASTContext &Ctx) { + unsigned Align = 0; + specific_attr_iterator i(V.begin()), e(V.end()); + for(; i != e; ++i) + Align = std::max(Align, i->getAlignment(Ctx)); + return Align; +} + +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/BaseSubobject.h b/cpp/llvm/tools/clang/include/clang/AST/BaseSubobject.h new file mode 100644 index 00000000..6a036bb6 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/BaseSubobject.h @@ -0,0 +1,87 @@ +//===--- BaseSubobject.h - BaseSubobject class ----------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file provides a definition of the BaseSubobject class. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_BASESUBOBJECT_H +#define LLVM_CLANG_AST_BASESUBOBJECT_H + +#include "clang/AST/CharUnits.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/Support/DataTypes.h" +#include "llvm/Support/type_traits.h" + +namespace clang { + class CXXRecordDecl; + +// BaseSubobject - Uniquely identifies a direct or indirect base class. +// Stores both the base class decl and the offset from the most derived class to +// the base class. Used for vtable and VTT generation. +class BaseSubobject { + /// Base - The base class declaration. + const CXXRecordDecl *Base; + + /// BaseOffset - The offset from the most derived class to the base class. + CharUnits BaseOffset; + +public: + BaseSubobject() { } + BaseSubobject(const CXXRecordDecl *Base, CharUnits BaseOffset) + : Base(Base), BaseOffset(BaseOffset) { } + + /// getBase - Returns the base class declaration. + const CXXRecordDecl *getBase() const { return Base; } + + /// getBaseOffset - Returns the base class offset. + CharUnits getBaseOffset() const { return BaseOffset; } + + friend bool operator==(const BaseSubobject &LHS, const BaseSubobject &RHS) { + return LHS.Base == RHS.Base && LHS.BaseOffset == RHS.BaseOffset; + } +}; + +} // end namespace clang + +namespace llvm { + +template<> struct DenseMapInfo { + static clang::BaseSubobject getEmptyKey() { + return clang::BaseSubobject( + DenseMapInfo::getEmptyKey(), + clang::CharUnits::fromQuantity(DenseMapInfo::getEmptyKey())); + } + + static clang::BaseSubobject getTombstoneKey() { + return clang::BaseSubobject( + DenseMapInfo::getTombstoneKey(), + clang::CharUnits::fromQuantity(DenseMapInfo::getTombstoneKey())); + } + + static unsigned getHashValue(const clang::BaseSubobject &Base) { + return + DenseMapInfo::getHashValue(Base.getBase()) ^ + DenseMapInfo::getHashValue(Base.getBaseOffset().getQuantity()); + } + + static bool isEqual(const clang::BaseSubobject &LHS, + const clang::BaseSubobject &RHS) { + return LHS == RHS; + } +}; + +// It's OK to treat BaseSubobject as a POD type. +template <> struct isPodLike { + static const bool value = true; +}; + +} + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/BuiltinTypes.def b/cpp/llvm/tools/clang/include/clang/AST/BuiltinTypes.def new file mode 100644 index 00000000..34e6fc5c --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/BuiltinTypes.def @@ -0,0 +1,224 @@ +//===-- BuiltinTypeNodes.def - Metadata about BuiltinTypes ------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the database about various builtin singleton types. +// +// BuiltinType::Id is the enumerator defining the type. +// +// Context.SingletonId is the global singleton of this type. Some global +// singletons are shared by multiple types. +// +// BUILTIN_TYPE(Id, SingletonId) - A builtin type that has not been +// covered by any other #define. Defining this macro covers all +// the builtins. +// +// SIGNED_TYPE(Id, SingletonId) - A signed integral type. +// +// UNSIGNED_TYPE(Id, SingletonId) - An unsigned integral type. +// +// FLOATING_TYPE(Id, SingletonId) - A floating-point type. +// +// PLACEHOLDER_TYPE(Id, SingletonId) - A placeholder type. Placeholder +// types are used to perform context-sensitive checking of specific +// forms of expression. +// +// SHARED_SINGLETON_TYPE(Expansion) - The given expansion corresponds +// to a builtin which uses a shared singleton type. +// +//===----------------------------------------------------------------------===// + +#ifndef SIGNED_TYPE +#define SIGNED_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId) +#endif + +#ifndef UNSIGNED_TYPE +#define UNSIGNED_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId) +#endif + +#ifndef FLOATING_TYPE +#define FLOATING_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId) +#endif + +#ifndef PLACEHOLDER_TYPE +#define PLACEHOLDER_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId) +#endif + +#ifndef SHARED_SINGLETON_TYPE +#define SHARED_SINGLETON_TYPE(Expansion) Expansion +#endif + +//===- Builtin Types ------------------------------------------------------===// + +// void +BUILTIN_TYPE(Void, VoidTy) + +//===- Unsigned Types -----------------------------------------------------===// + +// 'bool' in C++, '_Bool' in C99 +UNSIGNED_TYPE(Bool, BoolTy) + +// 'char' for targets where it's unsigned +SHARED_SINGLETON_TYPE(UNSIGNED_TYPE(Char_U, CharTy)) + +// 'unsigned char', explicitly qualified +UNSIGNED_TYPE(UChar, UnsignedCharTy) + +// 'wchar_t' for targets where it's unsigned +SHARED_SINGLETON_TYPE(UNSIGNED_TYPE(WChar_U, WCharTy)) + +// 'char16_t' in C++ +UNSIGNED_TYPE(Char16, Char16Ty) + +// 'char32_t' in C++ +UNSIGNED_TYPE(Char32, Char32Ty) + +// 'unsigned short' +UNSIGNED_TYPE(UShort, UnsignedShortTy) + +// 'unsigned int' +UNSIGNED_TYPE(UInt, UnsignedIntTy) + +// 'unsigned long' +UNSIGNED_TYPE(ULong, UnsignedLongTy) + +// 'unsigned long long' +UNSIGNED_TYPE(ULongLong, UnsignedLongLongTy) + +// '__uint128_t' +UNSIGNED_TYPE(UInt128, UnsignedInt128Ty) + +//===- Signed Types -------------------------------------------------------===// + +// 'char' for targets where it's signed +SHARED_SINGLETON_TYPE(SIGNED_TYPE(Char_S, CharTy)) + +// 'signed char', explicitly qualified +SIGNED_TYPE(SChar, SignedCharTy) + +// 'wchar_t' for targets where it's signed +SHARED_SINGLETON_TYPE(SIGNED_TYPE(WChar_S, WCharTy)) + +// 'short' or 'signed short' +SIGNED_TYPE(Short, ShortTy) + +// 'int' or 'signed int' +SIGNED_TYPE(Int, IntTy) + +// 'long' or 'signed long' +SIGNED_TYPE(Long, LongTy) + +// 'long long' or 'signed long long' +SIGNED_TYPE(LongLong, LongLongTy) + +// '__int128_t' +SIGNED_TYPE(Int128, Int128Ty) + +//===- Floating point types -----------------------------------------------===// + +// 'half' in OpenCL, '__fp16' in ARM NEON. +FLOATING_TYPE(Half, HalfTy) + +// 'float' +FLOATING_TYPE(Float, FloatTy) + +// 'double' +FLOATING_TYPE(Double, DoubleTy) + +// 'long double' +FLOATING_TYPE(LongDouble, LongDoubleTy) + +//===- Language-specific types --------------------------------------------===// + +// This is the type of C++0x 'nullptr'. +BUILTIN_TYPE(NullPtr, NullPtrTy) + +// The primitive Objective C 'id' type. The user-visible 'id' +// type is a typedef of an ObjCObjectPointerType to an +// ObjCObjectType with this as its base. In fact, this only ever +// shows up in an AST as the base type of an ObjCObjectType. +BUILTIN_TYPE(ObjCId, ObjCBuiltinIdTy) + +// The primitive Objective C 'Class' type. The user-visible +// 'Class' type is a typedef of an ObjCObjectPointerType to an +// ObjCObjectType with this as its base. In fact, this only ever +// shows up in an AST as the base type of an ObjCObjectType. +BUILTIN_TYPE(ObjCClass, ObjCBuiltinClassTy) + +// The primitive Objective C 'SEL' type. The user-visible 'SEL' +// type is a typedef of a PointerType to this. +BUILTIN_TYPE(ObjCSel, ObjCBuiltinSelTy) + +// This represents the type of an expression whose type is +// totally unknown, e.g. 'T::foo'. It is permitted for this to +// appear in situations where the structure of the type is +// theoretically deducible. +BUILTIN_TYPE(Dependent, DependentTy) + +// The type of an unresolved overload set. A placeholder type. +// Expressions with this type have one of the following basic +// forms, with parentheses generally permitted: +// foo # possibly qualified, not if an implicit access +// foo # possibly qualified, not if an implicit access +// &foo # possibly qualified, not if an implicit access +// x->foo # only if might be a static member function +// &x->foo # only if might be a static member function +// &Class::foo # when a pointer-to-member; sub-expr also has this type +// OverloadExpr::find can be used to analyze the expression. +// +// Overload should be the first placeholder type, or else change +// BuiltinType::isNonOverloadPlaceholderType() +PLACEHOLDER_TYPE(Overload, OverloadTy) + +// The type of a bound C++ non-static member function. +// A placeholder type. Expressions with this type have one of the +// following basic forms: +// foo # if an implicit access +// x->foo # if only contains non-static members +PLACEHOLDER_TYPE(BoundMember, BoundMemberTy) + +// The type of an expression which refers to a pseudo-object, +// such as those introduced by Objective C's @property or +// VS.NET's __property declarations. A placeholder type. The +// pseudo-object is actually accessed by emitting a call to +// some sort of function or method; typically there is a pair +// of a setter and a getter, with the setter used if the +// pseudo-object reference is used syntactically as the +// left-hand-side of an assignment operator. +// +// A pseudo-object reference naming an Objective-C @property is +// always a dot access with a base of object-pointer type, +// e.g. 'x.foo'. +// +// In VS.NET, a __property declaration creates an implicit +// member with an associated name, which can then be named +// in any of the normal ways an ordinary member could be. +PLACEHOLDER_TYPE(PseudoObject, PseudoObjectTy) + +// __builtin_any_type. A placeholder type. Useful for clients +// like debuggers that don't know what type to give something. +// Only a small number of operations are valid on expressions of +// unknown type, most notably explicit casts. +PLACEHOLDER_TYPE(UnknownAny, UnknownAnyTy) + +// The type of a cast which, in ARC, would normally require a +// __bridge, but which might be okay depending on the immediate +// context. +PLACEHOLDER_TYPE(ARCUnbridgedCast, ARCUnbridgedCastTy) + +#ifdef LAST_BUILTIN_TYPE +LAST_BUILTIN_TYPE(ARCUnbridgedCast) +#undef LAST_BUILTIN_TYPE +#endif + +#undef SHARED_SINGLETON_TYPE +#undef PLACEHOLDER_TYPE +#undef FLOATING_TYPE +#undef SIGNED_TYPE +#undef UNSIGNED_TYPE +#undef BUILTIN_TYPE diff --git a/cpp/llvm/tools/clang/include/clang/AST/CMakeLists.txt b/cpp/llvm/tools/clang/include/clang/AST/CMakeLists.txt new file mode 100644 index 00000000..c10cda84 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/CMakeLists.txt @@ -0,0 +1,17 @@ +clang_tablegen(Attrs.inc -gen-clang-attr-classes + -I ${CMAKE_CURRENT_SOURCE_DIR}/../../ + SOURCE ../Basic/Attr.td + TARGET ClangAttrClasses) + +clang_tablegen(AttrImpl.inc -gen-clang-attr-impl + -I ${CMAKE_CURRENT_SOURCE_DIR}/../../ + SOURCE ../Basic/Attr.td + TARGET ClangAttrImpl) + +clang_tablegen(StmtNodes.inc -gen-clang-stmt-nodes + SOURCE ../Basic/StmtNodes.td + TARGET ClangStmtNodes) + +clang_tablegen(DeclNodes.inc -gen-clang-decl-nodes + SOURCE ../Basic/DeclNodes.td + TARGET ClangDeclNodes) diff --git a/cpp/llvm/tools/clang/include/clang/AST/CXXInheritance.h b/cpp/llvm/tools/clang/include/clang/AST/CXXInheritance.h new file mode 100644 index 00000000..44c554b6 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/CXXInheritance.h @@ -0,0 +1,370 @@ +//===------ CXXInheritance.h - C++ Inheritance ------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file provides routines that help analyzing C++ inheritance hierarchies. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_CXXINHERITANCE_H +#define LLVM_CLANG_AST_CXXINHERITANCE_H + +#include "clang/AST/DeclarationName.h" +#include "clang/AST/DeclBase.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/Type.h" +#include "clang/AST/TypeOrdering.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/SmallSet.h" +#include "llvm/ADT/SmallVector.h" +#include +#include +#include + +namespace clang { + +class CXXBaseSpecifier; +class CXXMethodDecl; +class CXXRecordDecl; +class NamedDecl; + +/// \brief Represents an element in a path from a derived class to a +/// base class. +/// +/// Each step in the path references the link from a +/// derived class to one of its direct base classes, along with a +/// base "number" that identifies which base subobject of the +/// original derived class we are referencing. +struct CXXBasePathElement { + /// \brief The base specifier that states the link from a derived + /// class to a base class, which will be followed by this base + /// path element. + const CXXBaseSpecifier *Base; + + /// \brief The record decl of the class that the base is a base of. + const CXXRecordDecl *Class; + + /// \brief Identifies which base class subobject (of type + /// \c Base->getType()) this base path element refers to. + /// + /// This value is only valid if \c !Base->isVirtual(), because there + /// is no base numbering for the zero or one virtual bases of a + /// given type. + int SubobjectNumber; +}; + +/// \brief Represents a path from a specific derived class +/// (which is not represented as part of the path) to a particular +/// (direct or indirect) base class subobject. +/// +/// Individual elements in the path are described by the \c CXXBasePathElement +/// structure, which captures both the link from a derived class to one of its +/// direct bases and identification describing which base class +/// subobject is being used. +class CXXBasePath : public SmallVector { +public: + CXXBasePath() : Access(AS_public) {} + + /// \brief The access along this inheritance path. This is only + /// calculated when recording paths. AS_none is a special value + /// used to indicate a path which permits no legal access. + AccessSpecifier Access; + + /// \brief The set of declarations found inside this base class + /// subobject. + DeclContext::lookup_result Decls; + + void clear() { + SmallVectorImpl::clear(); + Access = AS_public; + } +}; + +/// BasePaths - Represents the set of paths from a derived class to +/// one of its (direct or indirect) bases. For example, given the +/// following class hierarchy: +/// +/// @code +/// class A { }; +/// class B : public A { }; +/// class C : public A { }; +/// class D : public B, public C{ }; +/// @endcode +/// +/// There are two potential BasePaths to represent paths from D to a +/// base subobject of type A. One path is (D,0) -> (B,0) -> (A,0) +/// and another is (D,0)->(C,0)->(A,1). These two paths actually +/// refer to two different base class subobjects of the same type, +/// so the BasePaths object refers to an ambiguous path. On the +/// other hand, consider the following class hierarchy: +/// +/// @code +/// class A { }; +/// class B : public virtual A { }; +/// class C : public virtual A { }; +/// class D : public B, public C{ }; +/// @endcode +/// +/// Here, there are two potential BasePaths again, (D, 0) -> (B, 0) +/// -> (A,v) and (D, 0) -> (C, 0) -> (A, v), but since both of them +/// refer to the same base class subobject of type A (the virtual +/// one), there is no ambiguity. +class CXXBasePaths { + /// \brief The type from which this search originated. + CXXRecordDecl *Origin; + + /// Paths - The actual set of paths that can be taken from the + /// derived class to the same base class. + std::list Paths; + + /// ClassSubobjects - Records the class subobjects for each class + /// type that we've seen. The first element in the pair says + /// whether we found a path to a virtual base for that class type, + /// while the element contains the number of non-virtual base + /// class subobjects for that class type. The key of the map is + /// the cv-unqualified canonical type of the base class subobject. + std::map, QualTypeOrdering> + ClassSubobjects; + + /// FindAmbiguities - Whether Sema::IsDerivedFrom should try find + /// ambiguous paths while it is looking for a path from a derived + /// type to a base type. + bool FindAmbiguities; + + /// RecordPaths - Whether Sema::IsDerivedFrom should record paths + /// while it is determining whether there are paths from a derived + /// type to a base type. + bool RecordPaths; + + /// DetectVirtual - Whether Sema::IsDerivedFrom should abort the search + /// if it finds a path that goes across a virtual base. The virtual class + /// is also recorded. + bool DetectVirtual; + + /// ScratchPath - A BasePath that is used by Sema::lookupInBases + /// to help build the set of paths. + CXXBasePath ScratchPath; + + /// DetectedVirtual - The base class that is virtual. + const RecordType *DetectedVirtual; + + /// \brief Array of the declarations that have been found. This + /// array is constructed only if needed, e.g., to iterate over the + /// results within LookupResult. + NamedDecl **DeclsFound; + unsigned NumDeclsFound; + + friend class CXXRecordDecl; + + void ComputeDeclsFound(); + + bool lookupInBases(ASTContext &Context, + const CXXRecordDecl *Record, + CXXRecordDecl::BaseMatchesCallback *BaseMatches, + void *UserData); +public: + typedef std::list::iterator paths_iterator; + typedef std::list::const_iterator const_paths_iterator; + typedef NamedDecl **decl_iterator; + + /// BasePaths - Construct a new BasePaths structure to record the + /// paths for a derived-to-base search. + explicit CXXBasePaths(bool FindAmbiguities = true, + bool RecordPaths = true, + bool DetectVirtual = true) + : FindAmbiguities(FindAmbiguities), RecordPaths(RecordPaths), + DetectVirtual(DetectVirtual), DetectedVirtual(0), DeclsFound(0), + NumDeclsFound(0) { } + + ~CXXBasePaths() { delete [] DeclsFound; } + + paths_iterator begin() { return Paths.begin(); } + paths_iterator end() { return Paths.end(); } + const_paths_iterator begin() const { return Paths.begin(); } + const_paths_iterator end() const { return Paths.end(); } + + CXXBasePath& front() { return Paths.front(); } + const CXXBasePath& front() const { return Paths.front(); } + + decl_iterator found_decls_begin(); + decl_iterator found_decls_end(); + + /// \brief Determine whether the path from the most-derived type to the + /// given base type is ambiguous (i.e., it refers to multiple subobjects of + /// the same base type). + bool isAmbiguous(CanQualType BaseType); + + /// \brief Whether we are finding multiple paths to detect ambiguities. + bool isFindingAmbiguities() const { return FindAmbiguities; } + + /// \brief Whether we are recording paths. + bool isRecordingPaths() const { return RecordPaths; } + + /// \brief Specify whether we should be recording paths or not. + void setRecordingPaths(bool RP) { RecordPaths = RP; } + + /// \brief Whether we are detecting virtual bases. + bool isDetectingVirtual() const { return DetectVirtual; } + + /// \brief The virtual base discovered on the path (if we are merely + /// detecting virtuals). + const RecordType* getDetectedVirtual() const { + return DetectedVirtual; + } + + /// \brief Retrieve the type from which this base-paths search + /// began + CXXRecordDecl *getOrigin() const { return Origin; } + void setOrigin(CXXRecordDecl *Rec) { Origin = Rec; } + + /// \brief Clear the base-paths results. + void clear(); + + /// \brief Swap this data structure's contents with another CXXBasePaths + /// object. + void swap(CXXBasePaths &Other); +}; + +/// \brief Uniquely identifies a virtual method within a class +/// hierarchy by the method itself and a class subobject number. +struct UniqueVirtualMethod { + UniqueVirtualMethod() : Method(0), Subobject(0), InVirtualSubobject(0) { } + + UniqueVirtualMethod(CXXMethodDecl *Method, unsigned Subobject, + const CXXRecordDecl *InVirtualSubobject) + : Method(Method), Subobject(Subobject), + InVirtualSubobject(InVirtualSubobject) { } + + /// \brief The overriding virtual method. + CXXMethodDecl *Method; + + /// \brief The subobject in which the overriding virtual method + /// resides. + unsigned Subobject; + + /// \brief The virtual base class subobject of which this overridden + /// virtual method is a part. Note that this records the closest + /// derived virtual base class subobject. + const CXXRecordDecl *InVirtualSubobject; + + friend bool operator==(const UniqueVirtualMethod &X, + const UniqueVirtualMethod &Y) { + return X.Method == Y.Method && X.Subobject == Y.Subobject && + X.InVirtualSubobject == Y.InVirtualSubobject; + } + + friend bool operator!=(const UniqueVirtualMethod &X, + const UniqueVirtualMethod &Y) { + return !(X == Y); + } +}; + +/// \brief The set of methods that override a given virtual method in +/// each subobject where it occurs. +/// +/// The first part of the pair is the subobject in which the +/// overridden virtual function occurs, while the second part of the +/// pair is the virtual method that overrides it (including the +/// subobject in which that virtual function occurs). +class OverridingMethods { + llvm::DenseMap > + Overrides; + +public: + // Iterate over the set of subobjects that have overriding methods. + typedef llvm::DenseMap > + ::iterator iterator; + typedef llvm::DenseMap > + ::const_iterator const_iterator; + iterator begin() { return Overrides.begin(); } + const_iterator begin() const { return Overrides.begin(); } + iterator end() { return Overrides.end(); } + const_iterator end() const { return Overrides.end(); } + unsigned size() const { return Overrides.size(); } + + // Iterate over the set of overriding virtual methods in a given + // subobject. + typedef SmallVector::iterator + overriding_iterator; + typedef SmallVector::const_iterator + overriding_const_iterator; + + // Add a new overriding method for a particular subobject. + void add(unsigned OverriddenSubobject, UniqueVirtualMethod Overriding); + + // Add all of the overriding methods from "other" into overrides for + // this method. Used when merging the overrides from multiple base + // class subobjects. + void add(const OverridingMethods &Other); + + // Replace all overriding virtual methods in all subobjects with the + // given virtual method. + void replaceAll(UniqueVirtualMethod Overriding); +}; + +/// \brief A mapping from each virtual member function to its set of +/// final overriders. +/// +/// Within a class hierarchy for a given derived class, each virtual +/// member function in that hierarchy has one or more "final +/// overriders" (C++ [class.virtual]p2). A final overrider for a +/// virtual function "f" is the virtual function that will actually be +/// invoked when dispatching a call to "f" through the +/// vtable. Well-formed classes have a single final overrider for each +/// virtual function; in abstract classes, the final overrider for at +/// least one virtual function is a pure virtual function. Due to +/// multiple, virtual inheritance, it is possible for a class to have +/// more than one final overrider. Athough this is an error (per C++ +/// [class.virtual]p2), it is not considered an error here: the final +/// overrider map can represent multiple final overriders for a +/// method, and it is up to the client to determine whether they are +/// problem. For example, the following class \c D has two final +/// overriders for the virtual function \c A::f(), one in \c C and one +/// in \c D: +/// +/// \code +/// struct A { virtual void f(); }; +/// struct B : virtual A { virtual void f(); }; +/// struct C : virtual A { virtual void f(); }; +/// struct D : B, C { }; +/// \endcode +/// +/// This data structure contaings a mapping from every virtual +/// function *that does not override an existing virtual function* and +/// in every subobject where that virtual function occurs to the set +/// of virtual functions that override it. Thus, the same virtual +/// function \c A::f can actually occur in multiple subobjects of type +/// \c A due to multiple inheritance, and may be overriden by +/// different virtual functions in each, as in the following example: +/// +/// \code +/// struct A { virtual void f(); }; +/// struct B : A { virtual void f(); }; +/// struct C : A { virtual void f(); }; +/// struct D : B, C { }; +/// \endcode +/// +/// Unlike in the previous example, where the virtual functions \c +/// B::f and \c C::f both overrode \c A::f in the same subobject of +/// type \c A, in this example the two virtual functions both override +/// \c A::f but in *different* subobjects of type A. This is +/// represented by numbering the subobjects in which the overridden +/// and the overriding virtual member functions are located. Subobject +/// 0 represents the virtua base class subobject of that type, while +/// subobject numbers greater than 0 refer to non-virtual base class +/// subobjects of that type. +class CXXFinalOverriderMap + : public llvm::DenseMap { }; + +/// \brief A set of all the primary bases for a class. +class CXXIndirectPrimaryBaseSet + : public llvm::SmallSet { }; + +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/CanonicalType.h b/cpp/llvm/tools/clang/include/clang/AST/CanonicalType.h new file mode 100644 index 00000000..6cce8886 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/CanonicalType.h @@ -0,0 +1,778 @@ +//===-- CanonicalType.h - C Language Family Type Representation -*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the CanQual class template, which provides access to +// canonical types. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_CANONICAL_TYPE_H +#define LLVM_CLANG_AST_CANONICAL_TYPE_H + +#include "clang/AST/Type.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/type_traits.h" +#include + +namespace clang { + +template class CanProxy; +template struct CanProxyAdaptor; + +//----------------------------------------------------------------------------// +// Canonical, qualified type template +//----------------------------------------------------------------------------// + +/// \brief Represents a canonical, potentially-qualified type. +/// +/// The CanQual template is a lightweight smart pointer that provides access +/// to the canonical representation of a type, where all typedefs and other +/// syntactic sugar has been eliminated. A CanQualType may also have various +/// qualifiers (const, volatile, restrict) attached to it. +/// +/// The template type parameter @p T is one of the Type classes (PointerType, +/// BuiltinType, etc.). The type stored within @c CanQual will be of that +/// type (or some subclass of that type). The typedef @c CanQualType is just +/// a shorthand for @c CanQual. +/// +/// An instance of @c CanQual can be implicitly converted to a +/// @c CanQual when T is derived from U, which essentially provides an +/// implicit upcast. For example, @c CanQual can be +/// converted to @c CanQual. Note that any @c CanQual type can +/// be implicitly converted to a QualType, but the reverse operation requires +/// a call to ASTContext::getCanonicalType(). +/// +/// +template +class CanQual { + /// \brief The actual, canonical type. + QualType Stored; + +public: + /// \brief Constructs a NULL canonical type. + CanQual() : Stored() { } + + /// \brief Converting constructor that permits implicit upcasting of + /// canonical type pointers. + template + CanQual(const CanQual& Other, + typename llvm::enable_if, int>::type = 0); + + /// \brief Retrieve the underlying type pointer, which refers to a + /// canonical type. + /// + /// The underlying pointer must not be NULL. + const T *getTypePtr() const { return cast(Stored.getTypePtr()); } + + /// \brief Retrieve the underlying type pointer, which refers to a + /// canonical type, or NULL. + /// + const T *getTypePtrOrNull() const { + return cast_or_null(Stored.getTypePtrOrNull()); + } + + /// \brief Implicit conversion to a qualified type. + operator QualType() const { return Stored; } + + /// \brief Implicit conversion to bool. + operator bool() const { return !isNull(); } + + bool isNull() const { + return Stored.isNull(); + } + + SplitQualType split() const { return Stored.split(); } + + /// \brief Retrieve a canonical type pointer with a different static type, + /// upcasting or downcasting as needed. + /// + /// The getAs() function is typically used to try to downcast to a + /// more specific (canonical) type in the type system. For example: + /// + /// @code + /// void f(CanQual T) { + /// if (CanQual Ptr = T->getAs()) { + /// // look at Ptr's pointee type + /// } + /// } + /// @endcode + /// + /// \returns A proxy pointer to the same type, but with the specified + /// static type (@p U). If the dynamic type is not the specified static type + /// or a derived class thereof, a NULL canonical type. + template CanProxy getAs() const; + + template CanProxy castAs() const; + + /// \brief Overloaded arrow operator that produces a canonical type + /// proxy. + CanProxy operator->() const; + + /// \brief Retrieve all qualifiers. + Qualifiers getQualifiers() const { return Stored.getLocalQualifiers(); } + + /// \brief Retrieve the const/volatile/restrict qualifiers. + unsigned getCVRQualifiers() const { return Stored.getLocalCVRQualifiers(); } + + /// \brief Determines whether this type has any qualifiers + bool hasQualifiers() const { return Stored.hasLocalQualifiers(); } + + bool isConstQualified() const { + return Stored.isLocalConstQualified(); + } + bool isVolatileQualified() const { + return Stored.isLocalVolatileQualified(); + } + bool isRestrictQualified() const { + return Stored.isLocalRestrictQualified(); + } + + /// \brief Determines if this canonical type is furthermore + /// canonical as a parameter. The parameter-canonicalization + /// process decays arrays to pointers and drops top-level qualifiers. + bool isCanonicalAsParam() const { + return Stored.isCanonicalAsParam(); + } + + /// \brief Retrieve the unqualified form of this type. + CanQual getUnqualifiedType() const; + + /// \brief Retrieves a version of this type with const applied. + /// Note that this does not always yield a canonical type. + QualType withConst() const { + return Stored.withConst(); + } + + /// \brief Determines whether this canonical type is more qualified than + /// the @p Other canonical type. + bool isMoreQualifiedThan(CanQual Other) const { + return Stored.isMoreQualifiedThan(Other.Stored); + } + + /// \brief Determines whether this canonical type is at least as qualified as + /// the @p Other canonical type. + bool isAtLeastAsQualifiedAs(CanQual Other) const { + return Stored.isAtLeastAsQualifiedAs(Other.Stored); + } + + /// \brief If the canonical type is a reference type, returns the type that + /// it refers to; otherwise, returns the type itself. + CanQual getNonReferenceType() const; + + /// \brief Retrieve the internal representation of this canonical type. + void *getAsOpaquePtr() const { return Stored.getAsOpaquePtr(); } + + /// \brief Construct a canonical type from its internal representation. + static CanQual getFromOpaquePtr(void *Ptr); + + /// \brief Builds a canonical type from a QualType. + /// + /// This routine is inherently unsafe, because it requires the user to + /// ensure that the given type is a canonical type with the correct + // (dynamic) type. + static CanQual CreateUnsafe(QualType Other); + + void dump() const { Stored.dump(); } + + void Profile(llvm::FoldingSetNodeID &ID) const { + ID.AddPointer(getAsOpaquePtr()); + } +}; + +template +inline bool operator==(CanQual x, CanQual y) { + return x.getAsOpaquePtr() == y.getAsOpaquePtr(); +} + +template +inline bool operator!=(CanQual x, CanQual y) { + return x.getAsOpaquePtr() != y.getAsOpaquePtr(); +} + +/// \brief Represents a canonical, potentially-qualified type. +typedef CanQual CanQualType; + +inline CanQualType Type::getCanonicalTypeUnqualified() const { + return CanQualType::CreateUnsafe(getCanonicalTypeInternal()); +} + +inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, + CanQualType T) { + DB << static_cast(T); + return DB; +} + +//----------------------------------------------------------------------------// +// Internal proxy classes used by canonical types +//----------------------------------------------------------------------------// + +#define LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(Accessor) \ +CanQualType Accessor() const { \ +return CanQualType::CreateUnsafe(this->getTypePtr()->Accessor()); \ +} + +#define LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Type, Accessor) \ +Type Accessor() const { return this->getTypePtr()->Accessor(); } + +/// \brief Base class of all canonical proxy types, which is responsible for +/// storing the underlying canonical type and providing basic conversions. +template +class CanProxyBase { +protected: + CanQual Stored; + +public: + /// \brief Retrieve the pointer to the underlying Type + const T *getTypePtr() const { return Stored.getTypePtr(); } + + /// \brief Implicit conversion to the underlying pointer. + /// + /// Also provides the ability to use canonical type proxies in a Boolean + // context,e.g., + /// @code + /// if (CanQual Ptr = T->getAs()) { ... } + /// @endcode + operator const T*() const { return this->Stored.getTypePtrOrNull(); } + + /// \brief Try to convert the given canonical type to a specific structural + /// type. + template CanProxy getAs() const { + return this->Stored.template getAs(); + } + + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Type::TypeClass, getTypeClass) + + // Type predicates + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjectType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIncompleteType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIncompleteOrObjectType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isVariablyModifiedType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIntegerType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isEnumeralType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBooleanType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isCharType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isWideCharType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIntegralType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIntegralOrEnumerationType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isRealFloatingType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isComplexType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isAnyComplexType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isFloatingType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isRealType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isArithmeticType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isVoidType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isDerivedType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isScalarType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isAggregateType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isAnyPointerType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isVoidPointerType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isFunctionPointerType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isMemberFunctionPointerType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isClassType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isStructureType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isStructureOrClassType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isUnionType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isComplexIntegerType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isNullPtrType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isDependentType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isOverloadableType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isArrayType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasPointerRepresentation) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasObjCPointerRepresentation) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasIntegerRepresentation) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasSignedIntegerRepresentation) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasUnsignedIntegerRepresentation) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasFloatingRepresentation) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isPromotableIntegerType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isSignedIntegerType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isUnsignedIntegerType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isSignedIntegerOrEnumerationType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isUnsignedIntegerOrEnumerationType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isConstantSizeType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isSpecifierType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(CXXRecordDecl*, getAsCXXRecordDecl) + + /// \brief Retrieve the proxy-adaptor type. + /// + /// This arrow operator is used when CanProxyAdaptor has been specialized + /// for the given type T. In that case, we reference members of the + /// CanProxyAdaptor specialization. Otherwise, this operator will be hidden + /// by the arrow operator in the primary CanProxyAdaptor template. + const CanProxyAdaptor *operator->() const { + return static_cast *>(this); + } +}; + +/// \brief Replacable canonical proxy adaptor class that provides the link +/// between a canonical type and the accessors of the type. +/// +/// The CanProxyAdaptor is a replaceable class template that is instantiated +/// as part of each canonical proxy type. The primary template merely provides +/// redirection to the underlying type (T), e.g., @c PointerType. One can +/// provide specializations of this class template for each underlying type +/// that provide accessors returning canonical types (@c CanQualType) rather +/// than the more typical @c QualType, to propagate the notion of "canonical" +/// through the system. +template +struct CanProxyAdaptor : CanProxyBase { }; + +/// \brief Canonical proxy type returned when retrieving the members of a +/// canonical type or as the result of the @c CanQual::getAs member +/// function. +/// +/// The CanProxy type mainly exists as a proxy through which operator-> will +/// look to either map down to a raw T* (e.g., PointerType*) or to a proxy +/// type that provides canonical-type access to the fields of the type. +template +class CanProxy : public CanProxyAdaptor { +public: + /// \brief Build a NULL proxy. + CanProxy() { } + + /// \brief Build a proxy to the given canonical type. + CanProxy(CanQual Stored) { this->Stored = Stored; } + + /// \brief Implicit conversion to the stored canonical type. + operator CanQual() const { return this->Stored; } +}; + +} // end namespace clang + +namespace llvm { + +/// Implement simplify_type for CanQual, so that we can dyn_cast from +/// CanQual to a specific Type class. We're prefer isa/dyn_cast/cast/etc. +/// to return smart pointer (proxies?). +template +struct simplify_type > { + typedef const T *SimpleType; + static SimpleType getSimplifiedValue(const ::clang::CanQual &Val) { + return Val.getTypePtr(); + } +}; +template +struct simplify_type< ::clang::CanQual > +: public simplify_type > {}; + +// Teach SmallPtrSet that CanQual is "basically a pointer". +template +class PointerLikeTypeTraits > { +public: + static inline void *getAsVoidPointer(clang::CanQual P) { + return P.getAsOpaquePtr(); + } + static inline clang::CanQual getFromVoidPointer(void *P) { + return clang::CanQual::getFromOpaquePtr(P); + } + // qualifier information is encoded in the low bits. + enum { NumLowBitsAvailable = 0 }; +}; + +} // end namespace llvm + +namespace clang { + +//----------------------------------------------------------------------------// +// Canonical proxy adaptors for canonical type nodes. +//----------------------------------------------------------------------------// + +/// \brief Iterator adaptor that turns an iterator over canonical QualTypes +/// into an iterator over CanQualTypes. +template +class CanTypeIterator { + InputIterator Iter; + +public: + typedef CanQualType value_type; + typedef value_type reference; + typedef CanProxy pointer; + typedef typename std::iterator_traits::difference_type + difference_type; + typedef typename std::iterator_traits::iterator_category + iterator_category; + + CanTypeIterator() : Iter() { } + explicit CanTypeIterator(InputIterator Iter) : Iter(Iter) { } + + // Input iterator + reference operator*() const { + return CanQualType::CreateUnsafe(*Iter); + } + + pointer operator->() const; + + CanTypeIterator &operator++() { + ++Iter; + return *this; + } + + CanTypeIterator operator++(int) { + CanTypeIterator Tmp(*this); + ++Iter; + return Tmp; + } + + friend bool operator==(const CanTypeIterator& X, const CanTypeIterator &Y) { + return X.Iter == Y.Iter; + } + friend bool operator!=(const CanTypeIterator& X, const CanTypeIterator &Y) { + return X.Iter != Y.Iter; + } + + // Bidirectional iterator + CanTypeIterator &operator--() { + --Iter; + return *this; + } + + CanTypeIterator operator--(int) { + CanTypeIterator Tmp(*this); + --Iter; + return Tmp; + } + + // Random access iterator + reference operator[](difference_type n) const { + return CanQualType::CreateUnsafe(Iter[n]); + } + + CanTypeIterator &operator+=(difference_type n) { + Iter += n; + return *this; + } + + CanTypeIterator &operator-=(difference_type n) { + Iter -= n; + return *this; + } + + friend CanTypeIterator operator+(CanTypeIterator X, difference_type n) { + X += n; + return X; + } + + friend CanTypeIterator operator+(difference_type n, CanTypeIterator X) { + X += n; + return X; + } + + friend CanTypeIterator operator-(CanTypeIterator X, difference_type n) { + X -= n; + return X; + } + + friend difference_type operator-(const CanTypeIterator &X, + const CanTypeIterator &Y) { + return X - Y; + } +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const Type *, getClass) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + getSizeModifier) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Qualifiers, getIndexTypeQualifiers) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + getSizeModifier) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Qualifiers, getIndexTypeQualifiers) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const llvm::APInt &, getSize) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + getSizeModifier) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Qualifiers, getIndexTypeQualifiers) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayType::ArraySizeModifier, + getSizeModifier) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Qualifiers, getIndexTypeQualifiers) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Expr *, getSizeExpr) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceRange, getBracketsRange) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getLBracketLoc) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getRBracketLoc) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Expr *, getSizeExpr) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceRange, getBracketsRange) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getLBracketLoc) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getRBracketLoc) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const Expr *, getSizeExpr) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getAttributeLoc) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumElements) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumElements) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getResultType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(FunctionType::ExtInfo, getExtInfo) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getResultType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(FunctionType::ExtInfo, getExtInfo) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getResultType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(FunctionType::ExtInfo, getExtInfo) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumArgs) + CanQualType getArgType(unsigned i) const { + return CanQualType::CreateUnsafe(this->getTypePtr()->getArgType(i)); + } + + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isVariadic) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getTypeQuals) + + typedef CanTypeIterator + arg_type_iterator; + + arg_type_iterator arg_type_begin() const { + return arg_type_iterator(this->getTypePtr()->arg_type_begin()); + } + + arg_type_iterator arg_type_end() const { + return arg_type_iterator(this->getTypePtr()->arg_type_end()); + } + + // Note: canonical function types never have exception specifications +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getUnderlyingType) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Expr *, getUnderlyingExpr) + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getUnderlyingType) +}; + +template <> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getBaseType) + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getUnderlyingType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(UnaryTransformType::UTTKind, getUTTKind) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(TagDecl *, getDecl) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBeingDefined) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(RecordDecl *, getDecl) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBeingDefined) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasConstFields) +}; + +template<> +struct CanProxyAdaptor : public CanProxyBase { + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(EnumDecl *, getDecl) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBeingDefined) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getDepth) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getIndex) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isParameterPack) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(TemplateTypeParmDecl *, getDecl) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(IdentifierInfo *, getIdentifier) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getBaseType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const ObjCInterfaceDecl *, + getInterface) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCUnqualifiedId) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCUnqualifiedClass) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedId) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedClass) + + typedef ObjCObjectPointerType::qual_iterator qual_iterator; + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_begin) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_end) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, qual_empty) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumProtocols) +}; + +template<> +struct CanProxyAdaptor + : public CanProxyBase { + LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const ObjCInterfaceType *, + getInterfaceType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCIdType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCClassType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedIdType) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedClassType) + + typedef ObjCObjectPointerType::qual_iterator qual_iterator; + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_begin) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_end) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, qual_empty) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumProtocols) +}; + +//----------------------------------------------------------------------------// +// Method and function definitions +//----------------------------------------------------------------------------// +template +inline CanQual CanQual::getUnqualifiedType() const { + return CanQual::CreateUnsafe(Stored.getLocalUnqualifiedType()); +} + +template +inline CanQual CanQual::getNonReferenceType() const { + if (CanQual RefType = getAs()) + return RefType->getPointeeType(); + else + return *this; +} + +template +CanQual CanQual::getFromOpaquePtr(void *Ptr) { + CanQual Result; + Result.Stored = QualType::getFromOpaquePtr(Ptr); + assert((!Result || Result.Stored.getAsOpaquePtr() == (void*)-1 || + Result.Stored.isCanonical()) && "Type is not canonical!"); + return Result; +} + +template +CanQual CanQual::CreateUnsafe(QualType Other) { + assert((Other.isNull() || Other.isCanonical()) && "Type is not canonical!"); + assert((Other.isNull() || isa(Other.getTypePtr())) && + "Dynamic type does not meet the static type's requires"); + CanQual Result; + Result.Stored = Other; + return Result; +} + +template +template +CanProxy CanQual::getAs() const { + if (Stored.isNull()) + return CanProxy(); + + if (isa(Stored.getTypePtr())) + return CanQual::CreateUnsafe(Stored); + + return CanProxy(); +} + +template +template +CanProxy CanQual::castAs() const { + assert(!Stored.isNull() && isa(Stored.getTypePtr())); + return CanQual::CreateUnsafe(Stored); +} + +template +CanProxy CanQual::operator->() const { + return CanProxy(*this); +} + +template +typename CanTypeIterator::pointer +CanTypeIterator::operator->() const { + return CanProxy(*this); +} + +} + + +#endif // LLVM_CLANG_AST_CANONICAL_TYPE_H diff --git a/cpp/llvm/tools/clang/include/clang/AST/CharUnits.h b/cpp/llvm/tools/clang/include/clang/AST/CharUnits.h new file mode 100644 index 00000000..5be35826 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/CharUnits.h @@ -0,0 +1,217 @@ +//===--- CharUnits.h - Character units for sizes and offsets ----*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the CharUnits class +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_CHARUNITS_H +#define LLVM_CLANG_AST_CHARUNITS_H + +#include "llvm/ADT/DenseMapInfo.h" +#include "llvm/Support/DataTypes.h" +#include "llvm/Support/MathExtras.h" + +namespace clang { + + /// CharUnits - This is an opaque type for sizes expressed in character units. + /// Instances of this type represent a quantity as a multiple of the size + /// of the standard C type, char, on the target architecture. As an opaque + /// type, CharUnits protects you from accidentally combining operations on + /// quantities in bit units and character units. + /// + /// It should be noted that characters and bytes are distinct concepts. Bytes + /// refer to addressable units of data storage on the target machine, and + /// characters are members of a set of elements used for the organization, + /// control, or representation of data. According to C99, bytes are allowed + /// to exceed characters in size, although currently, clang only supports + /// architectures where the two are the same size. + /// + /// For portability, never assume that a target character is 8 bits wide. Use + /// CharUnit values wherever you calculate sizes, offsets, or alignments + /// in character units. + class CharUnits { + public: + typedef int64_t QuantityType; + + private: + QuantityType Quantity; + + explicit CharUnits(QuantityType C) : Quantity(C) {} + + public: + + /// CharUnits - A default constructor. + CharUnits() : Quantity(0) {} + + /// Zero - Construct a CharUnits quantity of zero. + static CharUnits Zero() { + return CharUnits(0); + } + + /// One - Construct a CharUnits quantity of one. + static CharUnits One() { + return CharUnits(1); + } + + /// fromQuantity - Construct a CharUnits quantity from a raw integer type. + static CharUnits fromQuantity(QuantityType Quantity) { + return CharUnits(Quantity); + } + + // Compound assignment. + CharUnits& operator+= (const CharUnits &Other) { + Quantity += Other.Quantity; + return *this; + } + CharUnits& operator++ () { + ++Quantity; + return *this; + } + CharUnits operator++ (int) { + return CharUnits(Quantity++); + } + CharUnits& operator-= (const CharUnits &Other) { + Quantity -= Other.Quantity; + return *this; + } + CharUnits& operator-- () { + --Quantity; + return *this; + } + CharUnits operator-- (int) { + return CharUnits(Quantity--); + } + + // Comparison operators. + bool operator== (const CharUnits &Other) const { + return Quantity == Other.Quantity; + } + bool operator!= (const CharUnits &Other) const { + return Quantity != Other.Quantity; + } + + // Relational operators. + bool operator< (const CharUnits &Other) const { + return Quantity < Other.Quantity; + } + bool operator<= (const CharUnits &Other) const { + return Quantity <= Other.Quantity; + } + bool operator> (const CharUnits &Other) const { + return Quantity > Other.Quantity; + } + bool operator>= (const CharUnits &Other) const { + return Quantity >= Other.Quantity; + } + + // Other predicates. + + /// isZero - Test whether the quantity equals zero. + bool isZero() const { return Quantity == 0; } + + /// isOne - Test whether the quantity equals one. + bool isOne() const { return Quantity == 1; } + + /// isPositive - Test whether the quantity is greater than zero. + bool isPositive() const { return Quantity > 0; } + + /// isNegative - Test whether the quantity is less than zero. + bool isNegative() const { return Quantity < 0; } + + /// isPowerOfTwo - Test whether the quantity is a power of two. + /// Zero is not a power of two. + bool isPowerOfTwo() const { + return (Quantity & -Quantity) == Quantity; + } + + // Arithmetic operators. + CharUnits operator* (QuantityType N) const { + return CharUnits(Quantity * N); + } + CharUnits operator/ (QuantityType N) const { + return CharUnits(Quantity / N); + } + QuantityType operator/ (const CharUnits &Other) const { + return Quantity / Other.Quantity; + } + CharUnits operator% (QuantityType N) const { + return CharUnits(Quantity % N); + } + QuantityType operator% (const CharUnits &Other) const { + return Quantity % Other.Quantity; + } + CharUnits operator+ (const CharUnits &Other) const { + return CharUnits(Quantity + Other.Quantity); + } + CharUnits operator- (const CharUnits &Other) const { + return CharUnits(Quantity - Other.Quantity); + } + CharUnits operator- () const { + return CharUnits(-Quantity); + } + + + // Conversions. + + /// getQuantity - Get the raw integer representation of this quantity. + QuantityType getQuantity() const { return Quantity; } + + /// RoundUpToAlignment - Returns the next integer (mod 2**64) that is + /// greater than or equal to this quantity and is a multiple of \arg + /// Align. Align must be non-zero. + CharUnits RoundUpToAlignment(const CharUnits &Align) { + return CharUnits(llvm::RoundUpToAlignment(Quantity, + Align.Quantity)); + } + + + }; // class CharUnit +} // namespace clang + +inline clang::CharUnits operator* (clang::CharUnits::QuantityType Scale, + const clang::CharUnits &CU) { + return CU * Scale; +} + +namespace llvm { + +template<> struct DenseMapInfo { + static clang::CharUnits getEmptyKey() { + clang::CharUnits::QuantityType Quantity = + DenseMapInfo::getEmptyKey(); + + return clang::CharUnits::fromQuantity(Quantity); + } + + static clang::CharUnits getTombstoneKey() { + clang::CharUnits::QuantityType Quantity = + DenseMapInfo::getTombstoneKey(); + + return clang::CharUnits::fromQuantity(Quantity); + } + + static unsigned getHashValue(const clang::CharUnits &CU) { + clang::CharUnits::QuantityType Quantity = CU.getQuantity(); + return DenseMapInfo::getHashValue(Quantity); + } + + static bool isEqual(const clang::CharUnits &LHS, + const clang::CharUnits &RHS) { + return LHS == RHS; + } +}; + +template <> struct isPodLike { + static const bool value = true; +}; + +} // end namespace llvm + +#endif // LLVM_CLANG_AST_CHARUNITS_H diff --git a/cpp/llvm/tools/clang/include/clang/AST/Decl.h b/cpp/llvm/tools/clang/include/clang/AST/Decl.h new file mode 100644 index 00000000..0c47f2e4 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/Decl.h @@ -0,0 +1,3339 @@ +//===--- Decl.h - Classes for representing declarations ---------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the Decl subclasses. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_DECL_H +#define LLVM_CLANG_AST_DECL_H + +#include "clang/AST/APValue.h" +#include "clang/AST/DeclBase.h" +#include "clang/AST/Redeclarable.h" +#include "clang/AST/DeclarationName.h" +#include "clang/AST/ExternalASTSource.h" +#include "clang/Basic/Linkage.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Optional.h" +#include "llvm/Support/Compiler.h" + +namespace clang { +class CXXTemporary; +class Expr; +class FunctionTemplateDecl; +class Stmt; +class CompoundStmt; +class StringLiteral; +class NestedNameSpecifier; +class TemplateParameterList; +class TemplateArgumentList; +struct ASTTemplateArgumentListInfo; +class MemberSpecializationInfo; +class FunctionTemplateSpecializationInfo; +class DependentFunctionTemplateSpecializationInfo; +class TypeLoc; +class UnresolvedSetImpl; +class LabelStmt; +class Module; + +/// \brief A container of type source information. +/// +/// A client can read the relevant info using TypeLoc wrappers, e.g: +/// @code +/// TypeLoc TL = TypeSourceInfo->getTypeLoc(); +/// if (PointerLoc *PL = dyn_cast(&TL)) +/// PL->getStarLoc().print(OS, SrcMgr); +/// @endcode +/// +class TypeSourceInfo { + QualType Ty; + // Contains a memory block after the class, used for type source information, + // allocated by ASTContext. + friend class ASTContext; + TypeSourceInfo(QualType ty) : Ty(ty) { } +public: + /// \brief Return the type wrapped by this type source info. + QualType getType() const { return Ty; } + + /// \brief Return the TypeLoc wrapper for the type source info. + TypeLoc getTypeLoc() const; // implemented in TypeLoc.h +}; + +/// TranslationUnitDecl - The top declaration context. +class TranslationUnitDecl : public Decl, public DeclContext { + virtual void anchor(); + ASTContext &Ctx; + + /// The (most recently entered) anonymous namespace for this + /// translation unit, if one has been created. + NamespaceDecl *AnonymousNamespace; + + explicit TranslationUnitDecl(ASTContext &ctx) + : Decl(TranslationUnit, 0, SourceLocation()), + DeclContext(TranslationUnit), + Ctx(ctx), AnonymousNamespace(0) {} +public: + ASTContext &getASTContext() const { return Ctx; } + + NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; } + void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; } + + static TranslationUnitDecl *Create(ASTContext &C); + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const TranslationUnitDecl *D) { return true; } + static bool classofKind(Kind K) { return K == TranslationUnit; } + static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { + return static_cast(const_cast(D)); + } + static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) { + return static_cast(const_cast(DC)); + } +}; + +/// NamedDecl - This represents a decl with a name. Many decls have names such +/// as ObjCMethodDecl, but not @class, etc. +class NamedDecl : public Decl { + virtual void anchor(); + /// Name - The name of this declaration, which is typically a normal + /// identifier but may also be a special kind of name (C++ + /// constructor, Objective-C selector, etc.) + DeclarationName Name; + +private: + NamedDecl *getUnderlyingDeclImpl(); + +protected: + NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N) + : Decl(DK, DC, L), Name(N) { } + +public: + /// getIdentifier - Get the identifier that names this declaration, + /// if there is one. This will return NULL if this declaration has + /// no name (e.g., for an unnamed class) or if the name is a special + /// name (C++ constructor, Objective-C selector, etc.). + IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); } + + /// getName - Get the name of identifier for this declaration as a StringRef. + /// This requires that the declaration have a name and that it be a simple + /// identifier. + StringRef getName() const { + assert(Name.isIdentifier() && "Name is not a simple identifier"); + return getIdentifier() ? getIdentifier()->getName() : ""; + } + + /// getNameAsString - Get a human-readable name for the declaration, even if + /// it is one of the special kinds of names (C++ constructor, Objective-C + /// selector, etc). Creating this name requires expensive string + /// manipulation, so it should be called only when performance doesn't matter. + /// For simple declarations, getNameAsCString() should suffice. + // + // FIXME: This function should be renamed to indicate that it is not just an + // alternate form of getName(), and clients should move as appropriate. + // + // FIXME: Deprecated, move clients to getName(). + std::string getNameAsString() const { return Name.getAsString(); } + + void printName(raw_ostream &os) const { return Name.printName(os); } + + /// getDeclName - Get the actual, stored name of the declaration, + /// which may be a special name. + DeclarationName getDeclName() const { return Name; } + + /// \brief Set the name of this declaration. + void setDeclName(DeclarationName N) { Name = N; } + + /// getQualifiedNameAsString - Returns human-readable qualified name for + /// declaration, like A::B::i, for i being member of namespace A::B. + /// If declaration is not member of context which can be named (record, + /// namespace), it will return same result as getNameAsString(). + /// Creating this name is expensive, so it should be called only when + /// performance doesn't matter. + std::string getQualifiedNameAsString() const; + std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const; + + /// getNameForDiagnostic - Appends a human-readable name for this + /// declaration into the given string. + /// + /// This is the method invoked by Sema when displaying a NamedDecl + /// in a diagnostic. It does not necessarily produce the same + /// result as getNameAsString(); for example, class template + /// specializations are printed with their template arguments. + /// + /// TODO: use an API that doesn't require so many temporary strings + virtual void getNameForDiagnostic(std::string &S, + const PrintingPolicy &Policy, + bool Qualified) const { + if (Qualified) + S += getQualifiedNameAsString(Policy); + else + S += getNameAsString(); + } + + /// declarationReplaces - Determine whether this declaration, if + /// known to be well-formed within its context, will replace the + /// declaration OldD if introduced into scope. A declaration will + /// replace another declaration if, for example, it is a + /// redeclaration of the same variable or function, but not if it is + /// a declaration of a different kind (function vs. class) or an + /// overloaded function. + bool declarationReplaces(NamedDecl *OldD) const; + + /// \brief Determine whether this declaration has linkage. + bool hasLinkage() const; + + using Decl::isModulePrivate; + using Decl::setModulePrivate; + + /// \brief Determine whether this declaration is hidden from name lookup. + bool isHidden() const { return Hidden; } + + /// \brief Determine whether this declaration is a C++ class member. + bool isCXXClassMember() const { + const DeclContext *DC = getDeclContext(); + + // C++0x [class.mem]p1: + // The enumerators of an unscoped enumeration defined in + // the class are members of the class. + // FIXME: support C++0x scoped enumerations. + if (isa(DC)) + DC = DC->getParent(); + + return DC->isRecord(); + } + + /// \brief Determine whether the given declaration is an instance member of + /// a C++ class. + bool isCXXInstanceMember() const; + + class LinkageInfo { + Linkage linkage_; + Visibility visibility_; + bool explicit_; + + public: + LinkageInfo() : linkage_(ExternalLinkage), visibility_(DefaultVisibility), + explicit_(false) {} + LinkageInfo(Linkage L, Visibility V, bool E) + : linkage_(L), visibility_(V), explicit_(E) {} + + static LinkageInfo external() { + return LinkageInfo(); + } + static LinkageInfo internal() { + return LinkageInfo(InternalLinkage, DefaultVisibility, false); + } + static LinkageInfo uniqueExternal() { + return LinkageInfo(UniqueExternalLinkage, DefaultVisibility, false); + } + static LinkageInfo none() { + return LinkageInfo(NoLinkage, DefaultVisibility, false); + } + + Linkage linkage() const { return linkage_; } + Visibility visibility() const { return visibility_; } + bool visibilityExplicit() const { return explicit_; } + + void setLinkage(Linkage L) { linkage_ = L; } + void setVisibility(Visibility V, bool E) { visibility_ = V; explicit_ = E; } + + void mergeLinkage(Linkage L) { + setLinkage(minLinkage(linkage(), L)); + } + void mergeLinkage(LinkageInfo Other) { + mergeLinkage(Other.linkage()); + } + + // Merge the visibility V giving preference to explicit ones. + // This is used, for example, when merging the visibility of a class + // down to one of its members. If the member has no explicit visibility, + // the class visibility wins. + void mergeVisibility(Visibility V, bool E = false) { + // If one has explicit visibility and the other doesn't, keep the + // explicit one. + if (visibilityExplicit() && !E) + return; + if (!visibilityExplicit() && E) + setVisibility(V, E); + + // If both are explicit or both are implicit, keep the minimum. + setVisibility(minVisibility(visibility(), V), visibilityExplicit() || E); + } + // Merge the visibility V, keeping the most restrictive one. + // This is used for cases like merging the visibility of a template + // argument to an instantiation. If we already have a hidden class, + // no argument should give it default visibility. + void mergeVisibilityWithMin(Visibility V, bool E = false) { + // Never increase the visibility + if (visibility() < V) + return; + + // If this visibility is explicit, keep it. + if (visibilityExplicit() && !E) + return; + setVisibility(V, E); + } + void mergeVisibility(LinkageInfo Other) { + mergeVisibility(Other.visibility(), Other.visibilityExplicit()); + } + void mergeVisibilityWithMin(LinkageInfo Other) { + mergeVisibilityWithMin(Other.visibility(), Other.visibilityExplicit()); + } + + void merge(LinkageInfo Other) { + mergeLinkage(Other); + mergeVisibility(Other); + } + void mergeWithMin(LinkageInfo Other) { + mergeLinkage(Other); + mergeVisibilityWithMin(Other); + } + + friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) { + L.merge(R); + return L; + } + }; + + /// \brief Determine what kind of linkage this entity has. + Linkage getLinkage() const; + + /// \brief Determines the visibility of this entity. + Visibility getVisibility() const { + return getLinkageAndVisibility().visibility(); + } + + /// \brief Determines the linkage and visibility of this entity. + LinkageInfo getLinkageAndVisibility() const; + + /// \brief If visibility was explicitly specified for this + /// declaration, return that visibility. + llvm::Optional getExplicitVisibility() const; + + /// \brief Clear the linkage cache in response to a change + /// to the declaration. + void ClearLinkageCache(); + + /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for + /// the underlying named decl. + NamedDecl *getUnderlyingDecl() { + // Fast-path the common case. + if (this->getKind() != UsingShadow && + this->getKind() != ObjCCompatibleAlias) + return this; + + return getUnderlyingDeclImpl(); + } + const NamedDecl *getUnderlyingDecl() const { + return const_cast(this)->getUnderlyingDecl(); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const NamedDecl *D) { return true; } + static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; } +}; + +inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) { + ND.printName(OS); + return OS; +} + +/// LabelDecl - Represents the declaration of a label. Labels also have a +/// corresponding LabelStmt, which indicates the position that the label was +/// defined at. For normal labels, the location of the decl is the same as the +/// location of the statement. For GNU local labels (__label__), the decl +/// location is where the __label__ is. +class LabelDecl : public NamedDecl { + virtual void anchor(); + LabelStmt *TheStmt; + /// LocStart - For normal labels, this is the same as the main declaration + /// label, i.e., the location of the identifier; for GNU local labels, + /// this is the location of the __label__ keyword. + SourceLocation LocStart; + + LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II, + LabelStmt *S, SourceLocation StartL) + : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {} + +public: + static LabelDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation IdentL, IdentifierInfo *II); + static LabelDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation IdentL, IdentifierInfo *II, + SourceLocation GnuLabelL); + static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + LabelStmt *getStmt() const { return TheStmt; } + void setStmt(LabelStmt *T) { TheStmt = T; } + + bool isGnuLocal() const { return LocStart != getLocation(); } + void setLocStart(SourceLocation L) { LocStart = L; } + + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(LocStart, getLocation()); + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const LabelDecl *D) { return true; } + static bool classofKind(Kind K) { return K == Label; } +}; + +/// NamespaceDecl - Represent a C++ namespace. +class NamespaceDecl : public NamedDecl, public DeclContext, + public Redeclarable +{ + virtual void anchor(); + + /// LocStart - The starting location of the source range, pointing + /// to either the namespace or the inline keyword. + SourceLocation LocStart; + /// RBraceLoc - The ending location of the source range. + SourceLocation RBraceLoc; + + /// \brief A pointer to either the anonymous namespace that lives just inside + /// this namespace or to the first namespace in the chain (the latter case + /// only when this is not the first in the chain), along with a + /// boolean value indicating whether this is an inline namespace. + llvm::PointerIntPair AnonOrFirstNamespaceAndInline; + + NamespaceDecl(DeclContext *DC, bool Inline, SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + NamespaceDecl *PrevDecl); + + typedef Redeclarable redeclarable_base; + virtual NamespaceDecl *getNextRedeclaration() { + return RedeclLink.getNext(); + } + virtual NamespaceDecl *getPreviousDeclImpl() { + return getPreviousDecl(); + } + virtual NamespaceDecl *getMostRecentDeclImpl() { + return getMostRecentDecl(); + } + +public: + static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, + bool Inline, SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + NamespaceDecl *PrevDecl); + + static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + typedef redeclarable_base::redecl_iterator redecl_iterator; + using redeclarable_base::redecls_begin; + using redeclarable_base::redecls_end; + using redeclarable_base::getPreviousDecl; + using redeclarable_base::getMostRecentDecl; + + /// \brief Returns true if this is an anonymous namespace declaration. + /// + /// For example: + /// \code + /// namespace { + /// ... + /// }; + /// \endcode + /// q.v. C++ [namespace.unnamed] + bool isAnonymousNamespace() const { + return !getIdentifier(); + } + + /// \brief Returns true if this is an inline namespace declaration. + bool isInline() const { + return AnonOrFirstNamespaceAndInline.getInt(); + } + + /// \brief Set whether this is an inline namespace declaration. + void setInline(bool Inline) { + AnonOrFirstNamespaceAndInline.setInt(Inline); + } + + /// \brief Get the original (first) namespace declaration. + NamespaceDecl *getOriginalNamespace() { + if (isFirstDeclaration()) + return this; + + return AnonOrFirstNamespaceAndInline.getPointer(); + } + + /// \brief Get the original (first) namespace declaration. + const NamespaceDecl *getOriginalNamespace() const { + if (isFirstDeclaration()) + return this; + + return AnonOrFirstNamespaceAndInline.getPointer(); + } + + /// \brief Return true if this declaration is an original (first) declaration + /// of the namespace. This is false for non-original (subsequent) namespace + /// declarations and anonymous namespaces. + bool isOriginalNamespace() const { + return isFirstDeclaration(); + } + + /// \brief Retrieve the anonymous namespace nested inside this namespace, + /// if any. + NamespaceDecl *getAnonymousNamespace() const { + return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer(); + } + + void setAnonymousNamespace(NamespaceDecl *D) { + getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D); + } + + /// Retrieves the canonical declaration of this namespace. + NamespaceDecl *getCanonicalDecl() { + return getOriginalNamespace(); + } + const NamespaceDecl *getCanonicalDecl() const { + return getOriginalNamespace(); + } + + virtual SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(LocStart, RBraceLoc); + } + + SourceLocation getLocStart() const LLVM_READONLY { return LocStart; } + SourceLocation getRBraceLoc() const { return RBraceLoc; } + void setLocStart(SourceLocation L) { LocStart = L; } + void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const NamespaceDecl *D) { return true; } + static bool classofKind(Kind K) { return K == Namespace; } + static DeclContext *castToDeclContext(const NamespaceDecl *D) { + return static_cast(const_cast(D)); + } + static NamespaceDecl *castFromDeclContext(const DeclContext *DC) { + return static_cast(const_cast(DC)); + } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// ValueDecl - Represent the declaration of a variable (in which case it is +/// an lvalue) a function (in which case it is a function designator) or +/// an enum constant. +class ValueDecl : public NamedDecl { + virtual void anchor(); + QualType DeclType; + +protected: + ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, + DeclarationName N, QualType T) + : NamedDecl(DK, DC, L, N), DeclType(T) {} +public: + QualType getType() const { return DeclType; } + void setType(QualType newType) { DeclType = newType; } + + /// \brief Determine whether this symbol is weakly-imported, + /// or declared with the weak or weak-ref attr. + bool isWeak() const { + return hasAttr() || hasAttr() || isWeakImported(); + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ValueDecl *D) { return true; } + static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; } +}; + +/// QualifierInfo - A struct with extended info about a syntactic +/// name qualifier, to be used for the case of out-of-line declarations. +struct QualifierInfo { + NestedNameSpecifierLoc QualifierLoc; + + /// NumTemplParamLists - The number of "outer" template parameter lists. + /// The count includes all of the template parameter lists that were matched + /// against the template-ids occurring into the NNS and possibly (in the + /// case of an explicit specialization) a final "template <>". + unsigned NumTemplParamLists; + + /// TemplParamLists - A new-allocated array of size NumTemplParamLists, + /// containing pointers to the "outer" template parameter lists. + /// It includes all of the template parameter lists that were matched + /// against the template-ids occurring into the NNS and possibly (in the + /// case of an explicit specialization) a final "template <>". + TemplateParameterList** TemplParamLists; + + /// Default constructor. + QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {} + + /// setTemplateParameterListsInfo - Sets info about "outer" template + /// parameter lists. + void setTemplateParameterListsInfo(ASTContext &Context, + unsigned NumTPLists, + TemplateParameterList **TPLists); + +private: + // Copy constructor and copy assignment are disabled. + QualifierInfo(const QualifierInfo&); + QualifierInfo& operator=(const QualifierInfo&); +}; + +/// \brief Represents a ValueDecl that came out of a declarator. +/// Contains type source information through TypeSourceInfo. +class DeclaratorDecl : public ValueDecl { + // A struct representing both a TInfo and a syntactic qualifier, + // to be used for the (uncommon) case of out-of-line declarations. + struct ExtInfo : public QualifierInfo { + TypeSourceInfo *TInfo; + }; + + llvm::PointerUnion DeclInfo; + + /// InnerLocStart - The start of the source range for this declaration, + /// ignoring outer template declarations. + SourceLocation InnerLocStart; + + bool hasExtInfo() const { return DeclInfo.is(); } + ExtInfo *getExtInfo() { return DeclInfo.get(); } + const ExtInfo *getExtInfo() const { return DeclInfo.get(); } + +protected: + DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, + DeclarationName N, QualType T, TypeSourceInfo *TInfo, + SourceLocation StartL) + : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) { + } + +public: + TypeSourceInfo *getTypeSourceInfo() const { + return hasExtInfo() + ? getExtInfo()->TInfo + : DeclInfo.get(); + } + void setTypeSourceInfo(TypeSourceInfo *TI) { + if (hasExtInfo()) + getExtInfo()->TInfo = TI; + else + DeclInfo = TI; + } + + /// getInnerLocStart - Return SourceLocation representing start of source + /// range ignoring outer template declarations. + SourceLocation getInnerLocStart() const { return InnerLocStart; } + void setInnerLocStart(SourceLocation L) { InnerLocStart = L; } + + /// getOuterLocStart - Return SourceLocation representing start of source + /// range taking into account any outer template declarations. + SourceLocation getOuterLocStart() const; + + virtual SourceRange getSourceRange() const LLVM_READONLY; + SourceLocation getLocStart() const LLVM_READONLY { + return getOuterLocStart(); + } + + /// \brief Retrieve the nested-name-specifier that qualifies the name of this + /// declaration, if it was present in the source. + NestedNameSpecifier *getQualifier() const { + return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() + : 0; + } + + /// \brief Retrieve the nested-name-specifier (with source-location + /// information) that qualifies the name of this declaration, if it was + /// present in the source. + NestedNameSpecifierLoc getQualifierLoc() const { + return hasExtInfo() ? getExtInfo()->QualifierLoc + : NestedNameSpecifierLoc(); + } + + void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); + + unsigned getNumTemplateParameterLists() const { + return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; + } + TemplateParameterList *getTemplateParameterList(unsigned index) const { + assert(index < getNumTemplateParameterLists()); + return getExtInfo()->TemplParamLists[index]; + } + void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists, + TemplateParameterList **TPLists); + + SourceLocation getTypeSpecStartLoc() const; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const DeclaratorDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstDeclarator && K <= lastDeclarator; + } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// \brief Structure used to store a statement, the constant value to +/// which it was evaluated (if any), and whether or not the statement +/// is an integral constant expression (if known). +struct EvaluatedStmt { + EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false), + CheckingICE(false), IsICE(false) { } + + /// \brief Whether this statement was already evaluated. + bool WasEvaluated : 1; + + /// \brief Whether this statement is being evaluated. + bool IsEvaluating : 1; + + /// \brief Whether we already checked whether this statement was an + /// integral constant expression. + bool CheckedICE : 1; + + /// \brief Whether we are checking whether this statement is an + /// integral constant expression. + bool CheckingICE : 1; + + /// \brief Whether this statement is an integral constant expression, + /// or in C++11, whether the statement is a constant expression. Only + /// valid if CheckedICE is true. + bool IsICE : 1; + + Stmt *Value; + APValue Evaluated; +}; + +/// VarDecl - An instance of this class is created to represent a variable +/// declaration or definition. +class VarDecl : public DeclaratorDecl, public Redeclarable { +public: + typedef clang::StorageClass StorageClass; + + /// getStorageClassSpecifierString - Return the string used to + /// specify the storage class \arg SC. + /// + /// It is illegal to call this function with SC == None. + static const char *getStorageClassSpecifierString(StorageClass SC); + + /// \brief Initialization styles. + enum InitializationStyle { + CInit, ///< C-style initialization with assignment + CallInit, ///< Call-style initialization (C++98) + ListInit ///< Direct list-initialization (C++11) + }; + +protected: + /// \brief Placeholder type used in Init to denote an unparsed C++ default + /// argument. + struct UnparsedDefaultArgument; + + /// \brief Placeholder type used in Init to denote an uninstantiated C++ + /// default argument. + struct UninstantiatedDefaultArgument; + + typedef llvm::PointerUnion4 InitType; + + /// \brief The initializer for this variable or, for a ParmVarDecl, the + /// C++ default argument. + mutable InitType Init; + +private: + class VarDeclBitfields { + friend class VarDecl; + friend class ASTDeclReader; + + unsigned SClass : 3; + unsigned SClassAsWritten : 3; + unsigned ThreadSpecified : 1; + unsigned InitStyle : 2; + + /// \brief Whether this variable is the exception variable in a C++ catch + /// or an Objective-C @catch statement. + unsigned ExceptionVar : 1; + + /// \brief Whether this local variable could be allocated in the return + /// slot of its function, enabling the named return value optimization + /// (NRVO). + unsigned NRVOVariable : 1; + + /// \brief Whether this variable is the for-range-declaration in a C++0x + /// for-range statement. + unsigned CXXForRangeDecl : 1; + + /// \brief Whether this variable is an ARC pseudo-__strong + /// variable; see isARCPseudoStrong() for details. + unsigned ARCPseudoStrong : 1; + + /// \brief Whether this variable is (C++0x) constexpr. + unsigned IsConstexpr : 1; + }; + enum { NumVarDeclBits = 14 }; + + friend class ASTDeclReader; + friend class StmtIteratorBase; + +protected: + enum { NumParameterIndexBits = 8 }; + + class ParmVarDeclBitfields { + friend class ParmVarDecl; + friend class ASTDeclReader; + + unsigned : NumVarDeclBits; + + /// Whether this parameter inherits a default argument from a + /// prior declaration. + unsigned HasInheritedDefaultArg : 1; + + /// Whether this parameter undergoes K&R argument promotion. + unsigned IsKNRPromoted : 1; + + /// Whether this parameter is an ObjC method parameter or not. + unsigned IsObjCMethodParam : 1; + + /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier. + /// Otherwise, the number of function parameter scopes enclosing + /// the function parameter scope in which this parameter was + /// declared. + unsigned ScopeDepthOrObjCQuals : 7; + + /// The number of parameters preceding this parameter in the + /// function parameter scope in which it was declared. + unsigned ParameterIndex : NumParameterIndexBits; + }; + + union { + unsigned AllBits; + VarDeclBitfields VarDeclBits; + ParmVarDeclBitfields ParmVarDeclBits; + }; + + VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + QualType T, TypeSourceInfo *TInfo, StorageClass SC, + StorageClass SCAsWritten) + : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() { + assert(sizeof(VarDeclBitfields) <= sizeof(unsigned)); + assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned)); + AllBits = 0; + VarDeclBits.SClass = SC; + VarDeclBits.SClassAsWritten = SCAsWritten; + // Everything else is implicitly initialized to false. + } + + typedef Redeclarable redeclarable_base; + virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); } + virtual VarDecl *getPreviousDeclImpl() { + return getPreviousDecl(); + } + virtual VarDecl *getMostRecentDeclImpl() { + return getMostRecentDecl(); + } + +public: + typedef redeclarable_base::redecl_iterator redecl_iterator; + using redeclarable_base::redecls_begin; + using redeclarable_base::redecls_end; + using redeclarable_base::getPreviousDecl; + using redeclarable_base::getMostRecentDecl; + + static VarDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, + StorageClass S, StorageClass SCAsWritten); + + static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + virtual SourceRange getSourceRange() const LLVM_READONLY; + + StorageClass getStorageClass() const { + return (StorageClass) VarDeclBits.SClass; + } + StorageClass getStorageClassAsWritten() const { + return (StorageClass) VarDeclBits.SClassAsWritten; + } + void setStorageClass(StorageClass SC); + void setStorageClassAsWritten(StorageClass SC) { + assert(isLegalForVariable(SC)); + VarDeclBits.SClassAsWritten = SC; + } + + void setThreadSpecified(bool T) { VarDeclBits.ThreadSpecified = T; } + bool isThreadSpecified() const { + return VarDeclBits.ThreadSpecified; + } + + /// hasLocalStorage - Returns true if a variable with function scope + /// is a non-static local variable. + bool hasLocalStorage() const { + if (getStorageClass() == SC_None) + return !isFileVarDecl(); + + // Return true for: Auto, Register. + // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal. + + return getStorageClass() >= SC_Auto; + } + + /// isStaticLocal - Returns true if a variable with function scope is a + /// static local variable. + bool isStaticLocal() const { + return getStorageClass() == SC_Static && !isFileVarDecl(); + } + + /// hasExternStorage - Returns true if a variable has extern or + /// __private_extern__ storage. + bool hasExternalStorage() const { + return getStorageClass() == SC_Extern || + getStorageClass() == SC_PrivateExtern; + } + + /// hasGlobalStorage - Returns true for all variables that do not + /// have local storage. This includs all global variables as well + /// as static variables declared within a function. + bool hasGlobalStorage() const { return !hasLocalStorage(); } + + /// \brief Determines whether this variable is a variable with + /// external, C linkage. + bool isExternC() const; + + /// isLocalVarDecl - Returns true for local variable declarations + /// other than parameters. Note that this includes static variables + /// inside of functions. It also includes variables inside blocks. + /// + /// void foo() { int x; static int y; extern int z; } + /// + bool isLocalVarDecl() const { + if (getKind() != Decl::Var) + return false; + if (const DeclContext *DC = getDeclContext()) + return DC->getRedeclContext()->isFunctionOrMethod(); + return false; + } + + /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but + /// excludes variables declared in blocks. + bool isFunctionOrMethodVarDecl() const { + if (getKind() != Decl::Var) + return false; + const DeclContext *DC = getDeclContext()->getRedeclContext(); + return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; + } + + /// \brief Determines whether this is a static data member. + /// + /// This will only be true in C++, and applies to, e.g., the + /// variable 'x' in: + /// \code + /// struct S { + /// static int x; + /// }; + /// \endcode + bool isStaticDataMember() const { + // If it wasn't static, it would be a FieldDecl. + return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); + } + + virtual VarDecl *getCanonicalDecl(); + const VarDecl *getCanonicalDecl() const { + return const_cast(this)->getCanonicalDecl(); + } + + enum DefinitionKind { + DeclarationOnly, ///< This declaration is only a declaration. + TentativeDefinition, ///< This declaration is a tentative definition. + Definition ///< This declaration is definitely a definition. + }; + + /// \brief Check whether this declaration is a definition. If this could be + /// a tentative definition (in C), don't check whether there's an overriding + /// definition. + DefinitionKind isThisDeclarationADefinition(ASTContext &) const; + DefinitionKind isThisDeclarationADefinition() const { + return isThisDeclarationADefinition(getASTContext()); + } + + /// \brief Check whether this variable is defined in this + /// translation unit. + DefinitionKind hasDefinition(ASTContext &) const; + DefinitionKind hasDefinition() const { + return hasDefinition(getASTContext()); + } + + /// \brief Get the tentative definition that acts as the real definition in + /// a TU. Returns null if there is a proper definition available. + VarDecl *getActingDefinition(); + const VarDecl *getActingDefinition() const { + return const_cast(this)->getActingDefinition(); + } + + /// \brief Determine whether this is a tentative definition of a + /// variable in C. + bool isTentativeDefinitionNow() const; + + /// \brief Get the real (not just tentative) definition for this declaration. + VarDecl *getDefinition(ASTContext &); + const VarDecl *getDefinition(ASTContext &C) const { + return const_cast(this)->getDefinition(C); + } + VarDecl *getDefinition() { + return getDefinition(getASTContext()); + } + const VarDecl *getDefinition() const { + return const_cast(this)->getDefinition(); + } + + /// \brief Determine whether this is or was instantiated from an out-of-line + /// definition of a static data member. + virtual bool isOutOfLine() const; + + /// \brief If this is a static data member, find its out-of-line definition. + VarDecl *getOutOfLineDefinition(); + + /// isFileVarDecl - Returns true for file scoped variable declaration. + bool isFileVarDecl() const { + if (getKind() != Decl::Var) + return false; + + if (getDeclContext()->getRedeclContext()->isFileContext()) + return true; + + if (isStaticDataMember()) + return true; + + return false; + } + + /// getAnyInitializer - Get the initializer for this variable, no matter which + /// declaration it is attached to. + const Expr *getAnyInitializer() const { + const VarDecl *D; + return getAnyInitializer(D); + } + + /// getAnyInitializer - Get the initializer for this variable, no matter which + /// declaration it is attached to. Also get that declaration. + const Expr *getAnyInitializer(const VarDecl *&D) const; + + bool hasInit() const { + return !Init.isNull() && (Init.is() || Init.is()); + } + const Expr *getInit() const { + if (Init.isNull()) + return 0; + + const Stmt *S = Init.dyn_cast(); + if (!S) { + if (EvaluatedStmt *ES = Init.dyn_cast()) + S = ES->Value; + } + return (const Expr*) S; + } + Expr *getInit() { + if (Init.isNull()) + return 0; + + Stmt *S = Init.dyn_cast(); + if (!S) { + if (EvaluatedStmt *ES = Init.dyn_cast()) + S = ES->Value; + } + + return (Expr*) S; + } + + /// \brief Retrieve the address of the initializer expression. + Stmt **getInitAddress() { + if (EvaluatedStmt *ES = Init.dyn_cast()) + return &ES->Value; + + // This union hack tip-toes around strict-aliasing rules. + union { + InitType *InitPtr; + Stmt **StmtPtr; + }; + + InitPtr = &Init; + return StmtPtr; + } + + void setInit(Expr *I); + + /// \brief Determine whether this variable is a reference that + /// extends the lifetime of its temporary initializer. + /// + /// A reference extends the lifetime of its temporary initializer if + /// it's initializer is an rvalue that would normally go out of scope + /// at the end of the initializer (a full expression). In such cases, + /// the reference itself takes ownership of the temporary, which will + /// be destroyed when the reference goes out of scope. For example: + /// + /// \code + /// const int &r = 1.0; // creates a temporary of type 'int' + /// \endcode + bool extendsLifetimeOfTemporary() const; + + /// \brief Determine whether this variable's value can be used in a + /// constant expression, according to the relevant language standard. + /// This only checks properties of the declaration, and does not check + /// whether the initializer is in fact a constant expression. + bool isUsableInConstantExpressions(ASTContext &C) const; + + EvaluatedStmt *ensureEvaluatedStmt() const; + + /// \brief Attempt to evaluate the value of the initializer attached to this + /// declaration, and produce notes explaining why it cannot be evaluated or is + /// not a constant expression. Returns a pointer to the value if evaluation + /// succeeded, 0 otherwise. + APValue *evaluateValue() const; + APValue *evaluateValue( + llvm::SmallVectorImpl &Notes) const; + + /// \brief Return the already-evaluated value of this variable's + /// initializer, or NULL if the value is not yet known. Returns pointer + /// to untyped APValue if the value could not be evaluated. + APValue *getEvaluatedValue() const { + if (EvaluatedStmt *Eval = Init.dyn_cast()) + if (Eval->WasEvaluated) + return &Eval->Evaluated; + + return 0; + } + + /// \brief Determines whether it is already known whether the + /// initializer is an integral constant expression or not. + bool isInitKnownICE() const { + if (EvaluatedStmt *Eval = Init.dyn_cast()) + return Eval->CheckedICE; + + return false; + } + + /// \brief Determines whether the initializer is an integral constant + /// expression, or in C++11, whether the initializer is a constant + /// expression. + /// + /// \pre isInitKnownICE() + bool isInitICE() const { + assert(isInitKnownICE() && + "Check whether we already know that the initializer is an ICE"); + return Init.get()->IsICE; + } + + /// \brief Determine whether the value of the initializer attached to this + /// declaration is an integral constant expression. + bool checkInitIsICE() const; + + void setInitStyle(InitializationStyle Style) { + VarDeclBits.InitStyle = Style; + } + + /// \brief The style of initialization for this declaration. + /// + /// C-style initialization is "int x = 1;". Call-style initialization is + /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be + /// the expression inside the parens or a "ClassType(a,b,c)" class constructor + /// expression for class types. List-style initialization is C++11 syntax, + /// e.g. "int x{1};". Clients can distinguish between different forms of + /// initialization by checking this value. In particular, "int x = {1};" is + /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the + /// Init expression in all three cases is an InitListExpr. + InitializationStyle getInitStyle() const { + return static_cast(VarDeclBits.InitStyle); + } + + /// \brief Whether the initializer is a direct-initializer (list or call). + bool isDirectInit() const { + return getInitStyle() != CInit; + } + + /// \brief Determine whether this variable is the exception variable in a + /// C++ catch statememt or an Objective-C @catch statement. + bool isExceptionVariable() const { + return VarDeclBits.ExceptionVar; + } + void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; } + + /// \brief Determine whether this local variable can be used with the named + /// return value optimization (NRVO). + /// + /// The named return value optimization (NRVO) works by marking certain + /// non-volatile local variables of class type as NRVO objects. These + /// locals can be allocated within the return slot of their containing + /// function, in which case there is no need to copy the object to the + /// return slot when returning from the function. Within the function body, + /// each return that returns the NRVO object will have this variable as its + /// NRVO candidate. + bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; } + void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; } + + /// \brief Determine whether this variable is the for-range-declaration in + /// a C++0x for-range statement. + bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; } + void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; } + + /// \brief Determine whether this variable is an ARC pseudo-__strong + /// variable. A pseudo-__strong variable has a __strong-qualified + /// type but does not actually retain the object written into it. + /// Generally such variables are also 'const' for safety. + bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; } + void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; } + + /// Whether this variable is (C++0x) constexpr. + bool isConstexpr() const { return VarDeclBits.IsConstexpr; } + void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; } + + /// \brief If this variable is an instantiated static data member of a + /// class template specialization, returns the templated static data member + /// from which it was instantiated. + VarDecl *getInstantiatedFromStaticDataMember() const; + + /// \brief If this variable is a static data member, determine what kind of + /// template specialization or instantiation this is. + TemplateSpecializationKind getTemplateSpecializationKind() const; + + /// \brief If this variable is an instantiation of a static data member of a + /// class template specialization, retrieves the member specialization + /// information. + MemberSpecializationInfo *getMemberSpecializationInfo() const; + + /// \brief For a static data member that was instantiated from a static + /// data member of a class template, set the template specialiation kind. + void setTemplateSpecializationKind(TemplateSpecializationKind TSK, + SourceLocation PointOfInstantiation = SourceLocation()); + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const VarDecl *D) { return true; } + static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; } +}; + +class ImplicitParamDecl : public VarDecl { + virtual void anchor(); +public: + static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation IdLoc, IdentifierInfo *Id, + QualType T); + + static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc, + IdentifierInfo *Id, QualType Type) + : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type, + /*tinfo*/ 0, SC_None, SC_None) { + setImplicit(); + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const ImplicitParamDecl *D) { return true; } + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classofKind(Kind K) { return K == ImplicitParam; } +}; + +/// ParmVarDecl - Represents a parameter to a function. +class ParmVarDecl : public VarDecl { +public: + enum { MaxFunctionScopeDepth = 255 }; + enum { MaxFunctionScopeIndex = 255 }; + +protected: + ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + QualType T, TypeSourceInfo *TInfo, + StorageClass S, StorageClass SCAsWritten, Expr *DefArg) + : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S, SCAsWritten) { + assert(ParmVarDeclBits.HasInheritedDefaultArg == false); + assert(ParmVarDeclBits.IsKNRPromoted == false); + assert(ParmVarDeclBits.IsObjCMethodParam == false); + setDefaultArg(DefArg); + } + +public: + static ParmVarDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + QualType T, TypeSourceInfo *TInfo, + StorageClass S, StorageClass SCAsWritten, + Expr *DefArg); + + static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + virtual SourceRange getSourceRange() const LLVM_READONLY; + + void setObjCMethodScopeInfo(unsigned parameterIndex) { + ParmVarDeclBits.IsObjCMethodParam = true; + setParameterIndex(parameterIndex); + } + + void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) { + assert(!ParmVarDeclBits.IsObjCMethodParam); + + ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth; + assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth + && "truncation!"); + + setParameterIndex(parameterIndex); + } + + bool isObjCMethodParameter() const { + return ParmVarDeclBits.IsObjCMethodParam; + } + + unsigned getFunctionScopeDepth() const { + if (ParmVarDeclBits.IsObjCMethodParam) return 0; + return ParmVarDeclBits.ScopeDepthOrObjCQuals; + } + + /// Returns the index of this parameter in its prototype or method scope. + unsigned getFunctionScopeIndex() const { + return getParameterIndex(); + } + + ObjCDeclQualifier getObjCDeclQualifier() const { + if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None; + return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals); + } + void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { + assert(ParmVarDeclBits.IsObjCMethodParam); + ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal; + } + + /// True if the value passed to this parameter must undergo + /// K&R-style default argument promotion: + /// + /// C99 6.5.2.2. + /// If the expression that denotes the called function has a type + /// that does not include a prototype, the integer promotions are + /// performed on each argument, and arguments that have type float + /// are promoted to double. + bool isKNRPromoted() const { + return ParmVarDeclBits.IsKNRPromoted; + } + void setKNRPromoted(bool promoted) { + ParmVarDeclBits.IsKNRPromoted = promoted; + } + + Expr *getDefaultArg(); + const Expr *getDefaultArg() const { + return const_cast(this)->getDefaultArg(); + } + + void setDefaultArg(Expr *defarg) { + Init = reinterpret_cast(defarg); + } + + /// \brief Retrieve the source range that covers the entire default + /// argument. + SourceRange getDefaultArgRange() const; + void setUninstantiatedDefaultArg(Expr *arg) { + Init = reinterpret_cast(arg); + } + Expr *getUninstantiatedDefaultArg() { + return (Expr *)Init.get(); + } + const Expr *getUninstantiatedDefaultArg() const { + return (const Expr *)Init.get(); + } + + /// hasDefaultArg - Determines whether this parameter has a default argument, + /// either parsed or not. + bool hasDefaultArg() const { + return getInit() || hasUnparsedDefaultArg() || + hasUninstantiatedDefaultArg(); + } + + /// hasUnparsedDefaultArg - Determines whether this parameter has a + /// default argument that has not yet been parsed. This will occur + /// during the processing of a C++ class whose member functions have + /// default arguments, e.g., + /// @code + /// class X { + /// public: + /// void f(int x = 17); // x has an unparsed default argument now + /// }; // x has a regular default argument now + /// @endcode + bool hasUnparsedDefaultArg() const { + return Init.is(); + } + + bool hasUninstantiatedDefaultArg() const { + return Init.is(); + } + + /// setUnparsedDefaultArg - Specify that this parameter has an + /// unparsed default argument. The argument will be replaced with a + /// real default argument via setDefaultArg when the class + /// definition enclosing the function declaration that owns this + /// default argument is completed. + void setUnparsedDefaultArg() { + Init = (UnparsedDefaultArgument *)0; + } + + bool hasInheritedDefaultArg() const { + return ParmVarDeclBits.HasInheritedDefaultArg; + } + + void setHasInheritedDefaultArg(bool I = true) { + ParmVarDeclBits.HasInheritedDefaultArg = I; + } + + QualType getOriginalType() const { + if (getTypeSourceInfo()) + return getTypeSourceInfo()->getType(); + return getType(); + } + + /// \brief Determine whether this parameter is actually a function + /// parameter pack. + bool isParameterPack() const; + + /// setOwningFunction - Sets the function declaration that owns this + /// ParmVarDecl. Since ParmVarDecls are often created before the + /// FunctionDecls that own them, this routine is required to update + /// the DeclContext appropriately. + void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ParmVarDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ParmVar; } + +private: + enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 }; + + void setParameterIndex(unsigned parameterIndex) { + if (parameterIndex >= ParameterIndexSentinel) { + setParameterIndexLarge(parameterIndex); + return; + } + + ParmVarDeclBits.ParameterIndex = parameterIndex; + assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!"); + } + unsigned getParameterIndex() const { + unsigned d = ParmVarDeclBits.ParameterIndex; + return d == ParameterIndexSentinel ? getParameterIndexLarge() : d; + } + + void setParameterIndexLarge(unsigned parameterIndex); + unsigned getParameterIndexLarge() const; +}; + +/// FunctionDecl - An instance of this class is created to represent a +/// function declaration or definition. +/// +/// Since a given function can be declared several times in a program, +/// there may be several FunctionDecls that correspond to that +/// function. Only one of those FunctionDecls will be found when +/// traversing the list of declarations in the context of the +/// FunctionDecl (e.g., the translation unit); this FunctionDecl +/// contains all of the information known about the function. Other, +/// previous declarations of the function are available via the +/// getPreviousDecl() chain. +class FunctionDecl : public DeclaratorDecl, public DeclContext, + public Redeclarable { +public: + typedef clang::StorageClass StorageClass; + + /// \brief The kind of templated function a FunctionDecl can be. + enum TemplatedKind { + TK_NonTemplate, + TK_FunctionTemplate, + TK_MemberSpecialization, + TK_FunctionTemplateSpecialization, + TK_DependentFunctionTemplateSpecialization + }; + +private: + /// ParamInfo - new[]'d array of pointers to VarDecls for the formal + /// parameters of this function. This is null if a prototype or if there are + /// no formals. + ParmVarDecl **ParamInfo; + + /// DeclsInPrototypeScope - Array of pointers to NamedDecls for + /// decls defined in the function prototype that are not parameters. E.g. + /// 'enum Y' in 'void f(enum Y {AA} x) {}'. + llvm::ArrayRef DeclsInPrototypeScope; + + LazyDeclStmtPtr Body; + + // FIXME: This can be packed into the bitfields in Decl. + // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum + unsigned SClass : 2; + unsigned SClassAsWritten : 2; + bool IsInline : 1; + bool IsInlineSpecified : 1; + bool IsVirtualAsWritten : 1; + bool IsPure : 1; + bool HasInheritedPrototype : 1; + bool HasWrittenPrototype : 1; + bool IsDeleted : 1; + bool IsTrivial : 1; // sunk from CXXMethodDecl + bool IsDefaulted : 1; // sunk from CXXMethoDecl + bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl + bool HasImplicitReturnZero : 1; + bool IsLateTemplateParsed : 1; + bool IsConstexpr : 1; + + /// \brief End part of this FunctionDecl's source range. + /// + /// We could compute the full range in getSourceRange(). However, when we're + /// dealing with a function definition deserialized from a PCH/AST file, + /// we can only compute the full range once the function body has been + /// de-serialized, so it's far better to have the (sometimes-redundant) + /// EndRangeLoc. + SourceLocation EndRangeLoc; + + /// \brief The template or declaration that this declaration + /// describes or was instantiated from, respectively. + /// + /// For non-templates, this value will be NULL. For function + /// declarations that describe a function template, this will be a + /// pointer to a FunctionTemplateDecl. For member functions + /// of class template specializations, this will be a MemberSpecializationInfo + /// pointer containing information about the specialization. + /// For function template specializations, this will be a + /// FunctionTemplateSpecializationInfo, which contains information about + /// the template being specialized and the template arguments involved in + /// that specialization. + llvm::PointerUnion4 + TemplateOrSpecialization; + + /// DNLoc - Provides source/type location info for the + /// declaration name embedded in the DeclaratorDecl base class. + DeclarationNameLoc DNLoc; + + /// \brief Specify that this function declaration is actually a function + /// template specialization. + /// + /// \param C the ASTContext. + /// + /// \param Template the function template that this function template + /// specialization specializes. + /// + /// \param TemplateArgs the template arguments that produced this + /// function template specialization from the template. + /// + /// \param InsertPos If non-NULL, the position in the function template + /// specialization set where the function template specialization data will + /// be inserted. + /// + /// \param TSK the kind of template specialization this is. + /// + /// \param TemplateArgsAsWritten location info of template arguments. + /// + /// \param PointOfInstantiation point at which the function template + /// specialization was first instantiated. + void setFunctionTemplateSpecialization(ASTContext &C, + FunctionTemplateDecl *Template, + const TemplateArgumentList *TemplateArgs, + void *InsertPos, + TemplateSpecializationKind TSK, + const TemplateArgumentListInfo *TemplateArgsAsWritten, + SourceLocation PointOfInstantiation); + + /// \brief Specify that this record is an instantiation of the + /// member function FD. + void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, + TemplateSpecializationKind TSK); + + void setParams(ASTContext &C, llvm::ArrayRef NewParamInfo); + +protected: + FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified, + bool isConstexprSpecified) + : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, + StartLoc), + DeclContext(DK), + ParamInfo(0), Body(), + SClass(S), SClassAsWritten(SCAsWritten), + IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified), + IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false), + HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false), + IsDefaulted(false), IsExplicitlyDefaulted(false), + HasImplicitReturnZero(false), IsLateTemplateParsed(false), + IsConstexpr(isConstexprSpecified), EndRangeLoc(NameInfo.getEndLoc()), + TemplateOrSpecialization(), + DNLoc(NameInfo.getInfo()) {} + + typedef Redeclarable redeclarable_base; + virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); } + virtual FunctionDecl *getPreviousDeclImpl() { + return getPreviousDecl(); + } + virtual FunctionDecl *getMostRecentDeclImpl() { + return getMostRecentDecl(); + } + +public: + typedef redeclarable_base::redecl_iterator redecl_iterator; + using redeclarable_base::redecls_begin; + using redeclarable_base::redecls_end; + using redeclarable_base::getPreviousDecl; + using redeclarable_base::getMostRecentDecl; + + static FunctionDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, SourceLocation NLoc, + DeclarationName N, QualType T, + TypeSourceInfo *TInfo, + StorageClass SC = SC_None, + StorageClass SCAsWritten = SC_None, + bool isInlineSpecified = false, + bool hasWrittenPrototype = true, + bool isConstexprSpecified = false) { + DeclarationNameInfo NameInfo(N, NLoc); + return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, + SC, SCAsWritten, + isInlineSpecified, hasWrittenPrototype, + isConstexprSpecified); + } + + static FunctionDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + StorageClass SC = SC_None, + StorageClass SCAsWritten = SC_None, + bool isInlineSpecified = false, + bool hasWrittenPrototype = true, + bool isConstexprSpecified = false); + + static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + DeclarationNameInfo getNameInfo() const { + return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); + } + + virtual void getNameForDiagnostic(std::string &S, + const PrintingPolicy &Policy, + bool Qualified) const; + + void setRangeEnd(SourceLocation E) { EndRangeLoc = E; } + + virtual SourceRange getSourceRange() const LLVM_READONLY; + + /// \brief Returns true if the function has a body (definition). The + /// function body might be in any of the (re-)declarations of this + /// function. The variant that accepts a FunctionDecl pointer will + /// set that function declaration to the actual declaration + /// containing the body (if there is one). + bool hasBody(const FunctionDecl *&Definition) const; + + virtual bool hasBody() const { + const FunctionDecl* Definition; + return hasBody(Definition); + } + + /// hasTrivialBody - Returns whether the function has a trivial body that does + /// not require any specific codegen. + bool hasTrivialBody() const; + + /// isDefined - Returns true if the function is defined at all, including + /// a deleted definition. Except for the behavior when the function is + /// deleted, behaves like hasBody. + bool isDefined(const FunctionDecl *&Definition) const; + + virtual bool isDefined() const { + const FunctionDecl* Definition; + return isDefined(Definition); + } + + /// getBody - Retrieve the body (definition) of the function. The + /// function body might be in any of the (re-)declarations of this + /// function. The variant that accepts a FunctionDecl pointer will + /// set that function declaration to the actual declaration + /// containing the body (if there is one). + /// NOTE: For checking if there is a body, use hasBody() instead, to avoid + /// unnecessary AST de-serialization of the body. + Stmt *getBody(const FunctionDecl *&Definition) const; + + virtual Stmt *getBody() const { + const FunctionDecl* Definition; + return getBody(Definition); + } + + /// isThisDeclarationADefinition - Returns whether this specific + /// declaration of the function is also a definition. This does not + /// determine whether the function has been defined (e.g., in a + /// previous definition); for that information, use isDefined. Note + /// that this returns false for a defaulted function unless that function + /// has been implicitly defined (possibly as deleted). + bool isThisDeclarationADefinition() const { + return IsDeleted || Body || IsLateTemplateParsed; + } + + /// doesThisDeclarationHaveABody - Returns whether this specific + /// declaration of the function has a body - that is, if it is a non- + /// deleted definition. + bool doesThisDeclarationHaveABody() const { + return Body || IsLateTemplateParsed; + } + + void setBody(Stmt *B); + void setLazyBody(uint64_t Offset) { Body = Offset; } + + /// Whether this function is variadic. + bool isVariadic() const; + + /// Whether this function is marked as virtual explicitly. + bool isVirtualAsWritten() const { return IsVirtualAsWritten; } + void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; } + + /// Whether this virtual function is pure, i.e. makes the containing class + /// abstract. + bool isPure() const { return IsPure; } + void setPure(bool P = true); + + /// Whether this templated function will be late parsed. + bool isLateTemplateParsed() const { return IsLateTemplateParsed; } + void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; } + + /// Whether this function is "trivial" in some specialized C++ senses. + /// Can only be true for default constructors, copy constructors, + /// copy assignment operators, and destructors. Not meaningful until + /// the class has been fully built by Sema. + bool isTrivial() const { return IsTrivial; } + void setTrivial(bool IT) { IsTrivial = IT; } + + /// Whether this function is defaulted per C++0x. Only valid for + /// special member functions. + bool isDefaulted() const { return IsDefaulted; } + void setDefaulted(bool D = true) { IsDefaulted = D; } + + /// Whether this function is explicitly defaulted per C++0x. Only valid + /// for special member functions. + bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; } + void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; } + + /// Whether falling off this function implicitly returns null/zero. + /// If a more specific implicit return value is required, front-ends + /// should synthesize the appropriate return statements. + bool hasImplicitReturnZero() const { return HasImplicitReturnZero; } + void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; } + + /// \brief Whether this function has a prototype, either because one + /// was explicitly written or because it was "inherited" by merging + /// a declaration without a prototype with a declaration that has a + /// prototype. + bool hasPrototype() const { + return HasWrittenPrototype || HasInheritedPrototype; + } + + bool hasWrittenPrototype() const { return HasWrittenPrototype; } + + /// \brief Whether this function inherited its prototype from a + /// previous declaration. + bool hasInheritedPrototype() const { return HasInheritedPrototype; } + void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; } + + /// Whether this is a (C++0x) constexpr function or constexpr constructor. + bool isConstexpr() const { return IsConstexpr; } + void setConstexpr(bool IC) { IsConstexpr = IC; } + + /// \brief Whether this function has been deleted. + /// + /// A function that is "deleted" (via the C++0x "= delete" syntax) + /// acts like a normal function, except that it cannot actually be + /// called or have its address taken. Deleted functions are + /// typically used in C++ overload resolution to attract arguments + /// whose type or lvalue/rvalue-ness would permit the use of a + /// different overload that would behave incorrectly. For example, + /// one might use deleted functions to ban implicit conversion from + /// a floating-point number to an Integer type: + /// + /// @code + /// struct Integer { + /// Integer(long); // construct from a long + /// Integer(double) = delete; // no construction from float or double + /// Integer(long double) = delete; // no construction from long double + /// }; + /// @endcode + // If a function is deleted, its first declaration must be. + bool isDeleted() const { return getCanonicalDecl()->IsDeleted; } + bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; } + void setDeletedAsWritten(bool D = true) { IsDeleted = D; } + + /// \brief Determines whether this function is "main", which is the + /// entry point into an executable program. + bool isMain() const; + + /// \brief Determines whether this operator new or delete is one + /// of the reserved global placement operators: + /// void *operator new(size_t, void *); + /// void *operator new[](size_t, void *); + /// void operator delete(void *, void *); + /// void operator delete[](void *, void *); + /// These functions have special behavior under [new.delete.placement]: + /// These functions are reserved, a C++ program may not define + /// functions that displace the versions in the Standard C++ library. + /// The provisions of [basic.stc.dynamic] do not apply to these + /// reserved placement forms of operator new and operator delete. + /// + /// This function must be an allocation or deallocation function. + bool isReservedGlobalPlacementOperator() const; + + /// \brief Determines whether this function is a function with + /// external, C linkage. + bool isExternC() const; + + /// \brief Determines whether this is a global function. + bool isGlobal() const; + + void setPreviousDeclaration(FunctionDecl * PrevDecl); + + virtual const FunctionDecl *getCanonicalDecl() const; + virtual FunctionDecl *getCanonicalDecl(); + + unsigned getBuiltinID() const; + + // Iterator access to formal parameters. + unsigned param_size() const { return getNumParams(); } + typedef ParmVarDecl **param_iterator; + typedef ParmVarDecl * const *param_const_iterator; + + param_iterator param_begin() { return ParamInfo; } + param_iterator param_end() { return ParamInfo+param_size(); } + + param_const_iterator param_begin() const { return ParamInfo; } + param_const_iterator param_end() const { return ParamInfo+param_size(); } + + /// getNumParams - Return the number of parameters this function must have + /// based on its FunctionType. This is the length of the ParamInfo array + /// after it has been created. + unsigned getNumParams() const; + + const ParmVarDecl *getParamDecl(unsigned i) const { + assert(i < getNumParams() && "Illegal param #"); + return ParamInfo[i]; + } + ParmVarDecl *getParamDecl(unsigned i) { + assert(i < getNumParams() && "Illegal param #"); + return ParamInfo[i]; + } + void setParams(llvm::ArrayRef NewParamInfo) { + setParams(getASTContext(), NewParamInfo); + } + + const llvm::ArrayRef &getDeclsInPrototypeScope() const { + return DeclsInPrototypeScope; + } + void setDeclsInPrototypeScope(llvm::ArrayRef NewDecls); + + /// getMinRequiredArguments - Returns the minimum number of arguments + /// needed to call this function. This may be fewer than the number of + /// function parameters, if some of the parameters have default + /// arguments (in C++). + unsigned getMinRequiredArguments() const; + + QualType getResultType() const { + return getType()->getAs()->getResultType(); + } + + /// \brief Determine the type of an expression that calls this function. + QualType getCallResultType() const { + return getType()->getAs()->getCallResultType(getASTContext()); + } + + StorageClass getStorageClass() const { return StorageClass(SClass); } + void setStorageClass(StorageClass SC); + + StorageClass getStorageClassAsWritten() const { + return StorageClass(SClassAsWritten); + } + + /// \brief Determine whether the "inline" keyword was specified for this + /// function. + bool isInlineSpecified() const { return IsInlineSpecified; } + + /// Set whether the "inline" keyword was specified for this function. + void setInlineSpecified(bool I) { + IsInlineSpecified = I; + IsInline = I; + } + + /// Flag that this function is implicitly inline. + void setImplicitlyInline() { + IsInline = true; + } + + /// \brief Determine whether this function should be inlined, because it is + /// either marked "inline" or "constexpr" or is a member function of a class + /// that was defined in the class body. + bool isInlined() const; + + bool isInlineDefinitionExternallyVisible() const; + + bool doesDeclarationForceExternallyVisibleDefinition() const; + + /// isOverloadedOperator - Whether this function declaration + /// represents an C++ overloaded operator, e.g., "operator+". + bool isOverloadedOperator() const { + return getOverloadedOperator() != OO_None; + } + + OverloadedOperatorKind getOverloadedOperator() const; + + const IdentifierInfo *getLiteralIdentifier() const; + + /// \brief If this function is an instantiation of a member function + /// of a class template specialization, retrieves the function from + /// which it was instantiated. + /// + /// This routine will return non-NULL for (non-templated) member + /// functions of class templates and for instantiations of function + /// templates. For example, given: + /// + /// \code + /// template + /// struct X { + /// void f(T); + /// }; + /// \endcode + /// + /// The declaration for X::f is a (non-templated) FunctionDecl + /// whose parent is the class template specialization X. For + /// this declaration, getInstantiatedFromFunction() will return + /// the FunctionDecl X::A. When a complete definition of + /// X::A is required, it will be instantiated from the + /// declaration returned by getInstantiatedFromMemberFunction(). + FunctionDecl *getInstantiatedFromMemberFunction() const; + + /// \brief What kind of templated function this is. + TemplatedKind getTemplatedKind() const; + + /// \brief If this function is an instantiation of a member function of a + /// class template specialization, retrieves the member specialization + /// information. + MemberSpecializationInfo *getMemberSpecializationInfo() const; + + /// \brief Specify that this record is an instantiation of the + /// member function FD. + void setInstantiationOfMemberFunction(FunctionDecl *FD, + TemplateSpecializationKind TSK) { + setInstantiationOfMemberFunction(getASTContext(), FD, TSK); + } + + /// \brief Retrieves the function template that is described by this + /// function declaration. + /// + /// Every function template is represented as a FunctionTemplateDecl + /// and a FunctionDecl (or something derived from FunctionDecl). The + /// former contains template properties (such as the template + /// parameter lists) while the latter contains the actual + /// description of the template's + /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the + /// FunctionDecl that describes the function template, + /// getDescribedFunctionTemplate() retrieves the + /// FunctionTemplateDecl from a FunctionDecl. + FunctionTemplateDecl *getDescribedFunctionTemplate() const { + return TemplateOrSpecialization.dyn_cast(); + } + + void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) { + TemplateOrSpecialization = Template; + } + + /// \brief Determine whether this function is a function template + /// specialization. + bool isFunctionTemplateSpecialization() const { + return getPrimaryTemplate() != 0; + } + + /// \brief Retrieve the class scope template pattern that this function + /// template specialization is instantiated from. + FunctionDecl *getClassScopeSpecializationPattern() const; + + /// \brief If this function is actually a function template specialization, + /// retrieve information about this function template specialization. + /// Otherwise, returns NULL. + FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const { + return TemplateOrSpecialization. + dyn_cast(); + } + + /// \brief Determines whether this function is a function template + /// specialization or a member of a class template specialization that can + /// be implicitly instantiated. + bool isImplicitlyInstantiable() const; + + /// \brief Determines if the given function was instantiated from a + /// function template. + bool isTemplateInstantiation() const; + + /// \brief Retrieve the function declaration from which this function could + /// be instantiated, if it is an instantiation (rather than a non-template + /// or a specialization, for example). + FunctionDecl *getTemplateInstantiationPattern() const; + + /// \brief Retrieve the primary template that this function template + /// specialization either specializes or was instantiated from. + /// + /// If this function declaration is not a function template specialization, + /// returns NULL. + FunctionTemplateDecl *getPrimaryTemplate() const; + + /// \brief Retrieve the template arguments used to produce this function + /// template specialization from the primary template. + /// + /// If this function declaration is not a function template specialization, + /// returns NULL. + const TemplateArgumentList *getTemplateSpecializationArgs() const; + + /// \brief Retrieve the template argument list as written in the sources, + /// if any. + /// + /// If this function declaration is not a function template specialization + /// or if it had no explicit template argument list, returns NULL. + /// Note that it an explicit template argument list may be written empty, + /// e.g., template<> void foo<>(char* s); + const ASTTemplateArgumentListInfo* + getTemplateSpecializationArgsAsWritten() const; + + /// \brief Specify that this function declaration is actually a function + /// template specialization. + /// + /// \param Template the function template that this function template + /// specialization specializes. + /// + /// \param TemplateArgs the template arguments that produced this + /// function template specialization from the template. + /// + /// \param InsertPos If non-NULL, the position in the function template + /// specialization set where the function template specialization data will + /// be inserted. + /// + /// \param TSK the kind of template specialization this is. + /// + /// \param TemplateArgsAsWritten location info of template arguments. + /// + /// \param PointOfInstantiation point at which the function template + /// specialization was first instantiated. + void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, + const TemplateArgumentList *TemplateArgs, + void *InsertPos, + TemplateSpecializationKind TSK = TSK_ImplicitInstantiation, + const TemplateArgumentListInfo *TemplateArgsAsWritten = 0, + SourceLocation PointOfInstantiation = SourceLocation()) { + setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs, + InsertPos, TSK, TemplateArgsAsWritten, + PointOfInstantiation); + } + + /// \brief Specifies that this function declaration is actually a + /// dependent function template specialization. + void setDependentTemplateSpecialization(ASTContext &Context, + const UnresolvedSetImpl &Templates, + const TemplateArgumentListInfo &TemplateArgs); + + DependentFunctionTemplateSpecializationInfo * + getDependentSpecializationInfo() const { + return TemplateOrSpecialization. + dyn_cast(); + } + + /// \brief Determine what kind of template instantiation this function + /// represents. + TemplateSpecializationKind getTemplateSpecializationKind() const; + + /// \brief Determine what kind of template instantiation this function + /// represents. + void setTemplateSpecializationKind(TemplateSpecializationKind TSK, + SourceLocation PointOfInstantiation = SourceLocation()); + + /// \brief Retrieve the (first) point of instantiation of a function template + /// specialization or a member of a class template specialization. + /// + /// \returns the first point of instantiation, if this function was + /// instantiated from a template; otherwise, returns an invalid source + /// location. + SourceLocation getPointOfInstantiation() const; + + /// \brief Determine whether this is or was instantiated from an out-of-line + /// definition of a member function. + virtual bool isOutOfLine() const; + + /// \brief Identify a memory copying or setting function. + /// If the given function is a memory copy or setting function, returns + /// the corresponding Builtin ID. If the function is not a memory function, + /// returns 0. + unsigned getMemoryFunctionKind() const; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const FunctionDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstFunction && K <= lastFunction; + } + static DeclContext *castToDeclContext(const FunctionDecl *D) { + return static_cast(const_cast(D)); + } + static FunctionDecl *castFromDeclContext(const DeclContext *DC) { + return static_cast(const_cast(DC)); + } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + + +/// FieldDecl - An instance of this class is created by Sema::ActOnField to +/// represent a member of a struct/union/class. +class FieldDecl : public DeclaratorDecl { + // FIXME: This can be packed into the bitfields in Decl. + bool Mutable : 1; + mutable unsigned CachedFieldIndex : 31; + + /// \brief A pointer to either the in-class initializer for this field (if + /// the boolean value is false), or the bit width expression for this bit + /// field (if the boolean value is true). + /// + /// We can safely combine these two because in-class initializers are not + /// permitted for bit-fields. + /// + /// If the boolean is false and the initializer is null, then this field has + /// an in-class initializer which has not yet been parsed and attached. + llvm::PointerIntPair InitializerOrBitWidth; +protected: + FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, + bool HasInit) + : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), + Mutable(Mutable), CachedFieldIndex(0), + InitializerOrBitWidth(BW, !HasInit) { + assert(!(BW && HasInit) && "got initializer for bitfield"); + } + +public: + static FieldDecl *Create(const ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, QualType T, + TypeSourceInfo *TInfo, Expr *BW, bool Mutable, + bool HasInit); + + static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + /// getFieldIndex - Returns the index of this field within its record, + /// as appropriate for passing to ASTRecordLayout::getFieldOffset. + unsigned getFieldIndex() const; + + /// isMutable - Determines whether this field is mutable (C++ only). + bool isMutable() const { return Mutable; } + + /// \brief Set whether this field is mutable (C++ only). + void setMutable(bool M) { Mutable = M; } + + /// isBitfield - Determines whether this field is a bitfield. + bool isBitField() const { + return InitializerOrBitWidth.getInt() && InitializerOrBitWidth.getPointer(); + } + + /// @brief Determines whether this is an unnamed bitfield. + bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); } + + /// isAnonymousStructOrUnion - Determines whether this field is a + /// representative for an anonymous struct or union. Such fields are + /// unnamed and are implicitly generated by the implementation to + /// store the data for the anonymous union or struct. + bool isAnonymousStructOrUnion() const; + + Expr *getBitWidth() const { + return isBitField() ? InitializerOrBitWidth.getPointer() : 0; + } + unsigned getBitWidthValue(const ASTContext &Ctx) const; + void setBitWidth(Expr *BW) { + assert(!InitializerOrBitWidth.getPointer() && + "bit width or initializer already set"); + InitializerOrBitWidth.setPointer(BW); + InitializerOrBitWidth.setInt(1); + } + /// removeBitWidth - Remove the bitfield width from this member. + void removeBitWidth() { + assert(isBitField() && "no bit width to remove"); + InitializerOrBitWidth.setPointer(0); + } + + /// hasInClassInitializer - Determine whether this member has a C++0x in-class + /// initializer. + bool hasInClassInitializer() const { + return !InitializerOrBitWidth.getInt(); + } + /// getInClassInitializer - Get the C++0x in-class initializer for this + /// member, or null if one has not been set. If a valid declaration has an + /// in-class initializer, but this returns null, then we have not parsed and + /// attached it yet. + Expr *getInClassInitializer() const { + return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0; + } + /// setInClassInitializer - Set the C++0x in-class initializer for this + /// member. + void setInClassInitializer(Expr *Init); + /// removeInClassInitializer - Remove the C++0x in-class initializer from this + /// member. + void removeInClassInitializer() { + assert(!InitializerOrBitWidth.getInt() && "no initializer to remove"); + InitializerOrBitWidth.setPointer(0); + InitializerOrBitWidth.setInt(1); + } + + /// getParent - Returns the parent of this field declaration, which + /// is the struct in which this method is defined. + const RecordDecl *getParent() const { + return cast(getDeclContext()); + } + + RecordDecl *getParent() { + return cast(getDeclContext()); + } + + SourceRange getSourceRange() const LLVM_READONLY; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const FieldDecl *D) { return true; } + static bool classofKind(Kind K) { return K >= firstField && K <= lastField; } +}; + +/// EnumConstantDecl - An instance of this object exists for each enum constant +/// that is defined. For example, in "enum X {a,b}", each of a/b are +/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a +/// TagType for the X EnumDecl. +class EnumConstantDecl : public ValueDecl { + Stmt *Init; // an integer constant expression + llvm::APSInt Val; // The value. +protected: + EnumConstantDecl(DeclContext *DC, SourceLocation L, + IdentifierInfo *Id, QualType T, Expr *E, + const llvm::APSInt &V) + : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} + +public: + + static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, + SourceLocation L, IdentifierInfo *Id, + QualType T, Expr *E, + const llvm::APSInt &V); + static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + const Expr *getInitExpr() const { return (const Expr*) Init; } + Expr *getInitExpr() { return (Expr*) Init; } + const llvm::APSInt &getInitVal() const { return Val; } + + void setInitExpr(Expr *E) { Init = (Stmt*) E; } + void setInitVal(const llvm::APSInt &V) { Val = V; } + + SourceRange getSourceRange() const LLVM_READONLY; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const EnumConstantDecl *D) { return true; } + static bool classofKind(Kind K) { return K == EnumConstant; } + + friend class StmtIteratorBase; +}; + +/// IndirectFieldDecl - An instance of this class is created to represent a +/// field injected from an anonymous union/struct into the parent scope. +/// IndirectFieldDecl are always implicit. +class IndirectFieldDecl : public ValueDecl { + virtual void anchor(); + NamedDecl **Chaining; + unsigned ChainingSize; + + IndirectFieldDecl(DeclContext *DC, SourceLocation L, + DeclarationName N, QualType T, + NamedDecl **CH, unsigned CHS) + : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {} + +public: + static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, IdentifierInfo *Id, + QualType T, NamedDecl **CH, unsigned CHS); + + static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + typedef NamedDecl * const *chain_iterator; + chain_iterator chain_begin() const { return Chaining; } + chain_iterator chain_end() const { return Chaining+ChainingSize; } + + unsigned getChainingSize() const { return ChainingSize; } + + FieldDecl *getAnonField() const { + assert(ChainingSize >= 2); + return cast(Chaining[ChainingSize - 1]); + } + + VarDecl *getVarDecl() const { + assert(ChainingSize >= 2); + return dyn_cast(*chain_begin()); + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const IndirectFieldDecl *D) { return true; } + static bool classofKind(Kind K) { return K == IndirectField; } + friend class ASTDeclReader; +}; + +/// TypeDecl - Represents a declaration of a type. +/// +class TypeDecl : public NamedDecl { + virtual void anchor(); + /// TypeForDecl - This indicates the Type object that represents + /// this TypeDecl. It is a cache maintained by + /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and + /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl. + mutable const Type *TypeForDecl; + /// LocStart - The start of the source range for this declaration. + SourceLocation LocStart; + friend class ASTContext; + friend class DeclContext; + friend class TagDecl; + friend class TemplateTypeParmDecl; + friend class TagType; + friend class ASTReader; + +protected: + TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, + SourceLocation StartL = SourceLocation()) + : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {} + +public: + // Low-level accessor + const Type *getTypeForDecl() const { return TypeForDecl; } + void setTypeForDecl(const Type *TD) { TypeForDecl = TD; } + + SourceLocation getLocStart() const LLVM_READONLY { return LocStart; } + void setLocStart(SourceLocation L) { LocStart = L; } + virtual SourceRange getSourceRange() const LLVM_READONLY { + if (LocStart.isValid()) + return SourceRange(LocStart, getLocation()); + else + return SourceRange(getLocation()); + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const TypeDecl *D) { return true; } + static bool classofKind(Kind K) { return K >= firstType && K <= lastType; } +}; + + +/// Base class for declarations which introduce a typedef-name. +class TypedefNameDecl : public TypeDecl, public Redeclarable { + virtual void anchor(); + /// UnderlyingType - This is the type the typedef is set to. + TypeSourceInfo *TInfo; + +protected: + TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + TypeSourceInfo *TInfo) + : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {} + + typedef Redeclarable redeclarable_base; + virtual TypedefNameDecl *getNextRedeclaration() { + return RedeclLink.getNext(); + } + virtual TypedefNameDecl *getPreviousDeclImpl() { + return getPreviousDecl(); + } + virtual TypedefNameDecl *getMostRecentDeclImpl() { + return getMostRecentDecl(); + } + +public: + typedef redeclarable_base::redecl_iterator redecl_iterator; + using redeclarable_base::redecls_begin; + using redeclarable_base::redecls_end; + using redeclarable_base::getPreviousDecl; + using redeclarable_base::getMostRecentDecl; + + TypeSourceInfo *getTypeSourceInfo() const { + return TInfo; + } + + /// Retrieves the canonical declaration of this typedef-name. + TypedefNameDecl *getCanonicalDecl() { + return getFirstDeclaration(); + } + const TypedefNameDecl *getCanonicalDecl() const { + return getFirstDeclaration(); + } + + QualType getUnderlyingType() const { + return TInfo->getType(); + } + void setTypeSourceInfo(TypeSourceInfo *newType) { + TInfo = newType; + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const TypedefNameDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstTypedefName && K <= lastTypedefName; + } +}; + +/// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef' +/// type specifier. +class TypedefDecl : public TypedefNameDecl { + TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, TypeSourceInfo *TInfo) + : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {} + +public: + static TypedefDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, TypeSourceInfo *TInfo); + static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + SourceRange getSourceRange() const LLVM_READONLY; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const TypedefDecl *D) { return true; } + static bool classofKind(Kind K) { return K == Typedef; } +}; + +/// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x +/// alias-declaration. +class TypeAliasDecl : public TypedefNameDecl { + TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, TypeSourceInfo *TInfo) + : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {} + +public: + static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, TypeSourceInfo *TInfo); + static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + SourceRange getSourceRange() const LLVM_READONLY; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const TypeAliasDecl *D) { return true; } + static bool classofKind(Kind K) { return K == TypeAlias; } +}; + +/// TagDecl - Represents the declaration of a struct/union/class/enum. +class TagDecl + : public TypeDecl, public DeclContext, public Redeclarable { +public: + // This is really ugly. + typedef TagTypeKind TagKind; + +private: + // FIXME: This can be packed into the bitfields in Decl. + /// TagDeclKind - The TagKind enum. + unsigned TagDeclKind : 2; + + /// IsCompleteDefinition - True if this is a definition ("struct foo + /// {};"), false if it is a declaration ("struct foo;"). It is not + /// a definition until the definition has been fully processed. + bool IsCompleteDefinition : 1; + +protected: + /// IsBeingDefined - True if this is currently being defined. + bool IsBeingDefined : 1; + +private: + /// IsEmbeddedInDeclarator - True if this tag declaration is + /// "embedded" (i.e., defined or declared for the very first time) + /// in the syntax of a declarator. + bool IsEmbeddedInDeclarator : 1; + + /// \brief True if this tag is free standing, e.g. "struct foo;". + bool IsFreeStanding : 1; + +protected: + // These are used by (and only defined for) EnumDecl. + unsigned NumPositiveBits : 8; + unsigned NumNegativeBits : 8; + + /// IsScoped - True if this tag declaration is a scoped enumeration. Only + /// possible in C++11 mode. + bool IsScoped : 1; + /// IsScopedUsingClassTag - If this tag declaration is a scoped enum, + /// then this is true if the scoped enum was declared using the class + /// tag, false if it was declared with the struct tag. No meaning is + /// associated if this tag declaration is not a scoped enum. + bool IsScopedUsingClassTag : 1; + + /// IsFixed - True if this is an enumeration with fixed underlying type. Only + /// possible in C++11 or Microsoft extensions mode. + bool IsFixed : 1; + +private: + SourceLocation RBraceLoc; + + // A struct representing syntactic qualifier info, + // to be used for the (uncommon) case of out-of-line declarations. + typedef QualifierInfo ExtInfo; + + /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name + /// is qualified, it points to the qualifier info (nns and range); + /// otherwise, if the tag declaration is anonymous and it is part of + /// a typedef or alias, it points to the TypedefNameDecl (used for mangling); + /// otherwise, it is a null (TypedefNameDecl) pointer. + llvm::PointerUnion TypedefNameDeclOrQualifier; + + bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is(); } + ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get(); } + const ExtInfo *getExtInfo() const { + return TypedefNameDeclOrQualifier.get(); + } + +protected: + TagDecl(Kind DK, TagKind TK, DeclContext *DC, + SourceLocation L, IdentifierInfo *Id, + TagDecl *PrevDecl, SourceLocation StartL) + : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), + TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) { + assert((DK != Enum || TK == TTK_Enum) && + "EnumDecl not matched with TTK_Enum"); + TagDeclKind = TK; + IsCompleteDefinition = false; + IsBeingDefined = false; + IsEmbeddedInDeclarator = false; + IsFreeStanding = false; + setPreviousDeclaration(PrevDecl); + } + + typedef Redeclarable redeclarable_base; + virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); } + virtual TagDecl *getPreviousDeclImpl() { + return getPreviousDecl(); + } + virtual TagDecl *getMostRecentDeclImpl() { + return getMostRecentDecl(); + } + + /// @brief Completes the definition of this tag declaration. + /// + /// This is a helper function for derived classes. + void completeDefinition(); + +public: + typedef redeclarable_base::redecl_iterator redecl_iterator; + using redeclarable_base::redecls_begin; + using redeclarable_base::redecls_end; + using redeclarable_base::getPreviousDecl; + using redeclarable_base::getMostRecentDecl; + + SourceLocation getRBraceLoc() const { return RBraceLoc; } + void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } + + /// getInnerLocStart - Return SourceLocation representing start of source + /// range ignoring outer template declarations. + SourceLocation getInnerLocStart() const { return getLocStart(); } + + /// getOuterLocStart - Return SourceLocation representing start of source + /// range taking into account any outer template declarations. + SourceLocation getOuterLocStart() const; + virtual SourceRange getSourceRange() const LLVM_READONLY; + + virtual TagDecl* getCanonicalDecl(); + const TagDecl* getCanonicalDecl() const { + return const_cast(this)->getCanonicalDecl(); + } + + /// isThisDeclarationADefinition() - Return true if this declaration + /// is a completion definintion of the type. Provided for consistency. + bool isThisDeclarationADefinition() const { + return isCompleteDefinition(); + } + + /// isCompleteDefinition - Return true if this decl has its body + /// fully specified. + bool isCompleteDefinition() const { + return IsCompleteDefinition; + } + + /// isBeingDefined - Return true if this decl is currently being defined. + bool isBeingDefined() const { + return IsBeingDefined; + } + + bool isEmbeddedInDeclarator() const { + return IsEmbeddedInDeclarator; + } + void setEmbeddedInDeclarator(bool isInDeclarator) { + IsEmbeddedInDeclarator = isInDeclarator; + } + + bool isFreeStanding() const { return IsFreeStanding; } + void setFreeStanding(bool isFreeStanding = true) { + IsFreeStanding = isFreeStanding; + } + + /// \brief Whether this declaration declares a type that is + /// dependent, i.e., a type that somehow depends on template + /// parameters. + bool isDependentType() const { return isDependentContext(); } + + /// @brief Starts the definition of this tag declaration. + /// + /// This method should be invoked at the beginning of the definition + /// of this tag declaration. It will set the tag type into a state + /// where it is in the process of being defined. + void startDefinition(); + + /// getDefinition - Returns the TagDecl that actually defines this + /// struct/union/class/enum. When determining whether or not a + /// struct/union/class/enum has a definition, one should use this + /// method as opposed to 'isDefinition'. 'isDefinition' indicates + /// whether or not a specific TagDecl is defining declaration, not + /// whether or not the struct/union/class/enum type is defined. + /// This method returns NULL if there is no TagDecl that defines + /// the struct/union/class/enum. + TagDecl *getDefinition() const; + + void setCompleteDefinition(bool V) { IsCompleteDefinition = V; } + + const char *getKindName() const { + return TypeWithKeyword::getTagTypeKindName(getTagKind()); + } + + TagKind getTagKind() const { + return TagKind(TagDeclKind); + } + + void setTagKind(TagKind TK) { TagDeclKind = TK; } + + bool isStruct() const { return getTagKind() == TTK_Struct; } + bool isClass() const { return getTagKind() == TTK_Class; } + bool isUnion() const { return getTagKind() == TTK_Union; } + bool isEnum() const { return getTagKind() == TTK_Enum; } + + TypedefNameDecl *getTypedefNameForAnonDecl() const { + return hasExtInfo() ? 0 : + TypedefNameDeclOrQualifier.get(); + } + + void setTypedefNameForAnonDecl(TypedefNameDecl *TDD); + + /// \brief Retrieve the nested-name-specifier that qualifies the name of this + /// declaration, if it was present in the source. + NestedNameSpecifier *getQualifier() const { + return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() + : 0; + } + + /// \brief Retrieve the nested-name-specifier (with source-location + /// information) that qualifies the name of this declaration, if it was + /// present in the source. + NestedNameSpecifierLoc getQualifierLoc() const { + return hasExtInfo() ? getExtInfo()->QualifierLoc + : NestedNameSpecifierLoc(); + } + + void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); + + unsigned getNumTemplateParameterLists() const { + return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; + } + TemplateParameterList *getTemplateParameterList(unsigned i) const { + assert(i < getNumTemplateParameterLists()); + return getExtInfo()->TemplParamLists[i]; + } + void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists, + TemplateParameterList **TPLists); + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const TagDecl *D) { return true; } + static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; } + + static DeclContext *castToDeclContext(const TagDecl *D) { + return static_cast(const_cast(D)); + } + static TagDecl *castFromDeclContext(const DeclContext *DC) { + return static_cast(const_cast(DC)); + } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// EnumDecl - Represents an enum. In C++11, enums can be forward-declared +/// with a fixed underlying type, and in C we allow them to be forward-declared +/// with no underlying type as an extension. +class EnumDecl : public TagDecl { + virtual void anchor(); + /// IntegerType - This represent the integer type that the enum corresponds + /// to for code generation purposes. Note that the enumerator constants may + /// have a different type than this does. + /// + /// If the underlying integer type was explicitly stated in the source + /// code, this is a TypeSourceInfo* for that type. Otherwise this type + /// was automatically deduced somehow, and this is a Type*. + /// + /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in + /// some cases it won't. + /// + /// The underlying type of an enumeration never has any qualifiers, so + /// we can get away with just storing a raw Type*, and thus save an + /// extra pointer when TypeSourceInfo is needed. + + llvm::PointerUnion IntegerType; + + /// PromotionType - The integer type that values of this type should + /// promote to. In C, enumerators are generally of an integer type + /// directly, but gcc-style large enumerators (and all enumerators + /// in C++) are of the enum type instead. + QualType PromotionType; + + /// \brief If this enumeration is an instantiation of a member enumeration + /// of a class template specialization, this is the member specialization + /// information. + MemberSpecializationInfo *SpecializationInfo; + + EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, EnumDecl *PrevDecl, + bool Scoped, bool ScopedUsingClassTag, bool Fixed) + : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc), + SpecializationInfo(0) { + assert(Scoped || !ScopedUsingClassTag); + IntegerType = (const Type*)0; + NumNegativeBits = 0; + NumPositiveBits = 0; + IsScoped = Scoped; + IsScopedUsingClassTag = ScopedUsingClassTag; + IsFixed = Fixed; + } + + void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, + TemplateSpecializationKind TSK); +public: + EnumDecl *getCanonicalDecl() { + return cast(TagDecl::getCanonicalDecl()); + } + const EnumDecl *getCanonicalDecl() const { + return cast(TagDecl::getCanonicalDecl()); + } + + const EnumDecl *getPreviousDecl() const { + return cast_or_null(TagDecl::getPreviousDecl()); + } + EnumDecl *getPreviousDecl() { + return cast_or_null(TagDecl::getPreviousDecl()); + } + + const EnumDecl *getMostRecentDecl() const { + return cast(TagDecl::getMostRecentDecl()); + } + EnumDecl *getMostRecentDecl() { + return cast(TagDecl::getMostRecentDecl()); + } + + EnumDecl *getDefinition() const { + return cast_or_null(TagDecl::getDefinition()); + } + + static EnumDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, EnumDecl *PrevDecl, + bool IsScoped, bool IsScopedUsingClassTag, + bool IsFixed); + static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + /// completeDefinition - When created, the EnumDecl corresponds to a + /// forward-declared enum. This method is used to mark the + /// declaration as being defined; it's enumerators have already been + /// added (via DeclContext::addDecl). NewType is the new underlying + /// type of the enumeration type. + void completeDefinition(QualType NewType, + QualType PromotionType, + unsigned NumPositiveBits, + unsigned NumNegativeBits); + + // enumerator_iterator - Iterates through the enumerators of this + // enumeration. + typedef specific_decl_iterator enumerator_iterator; + + enumerator_iterator enumerator_begin() const { + const EnumDecl *E = getDefinition(); + if (!E) + E = this; + return enumerator_iterator(E->decls_begin()); + } + + enumerator_iterator enumerator_end() const { + const EnumDecl *E = getDefinition(); + if (!E) + E = this; + return enumerator_iterator(E->decls_end()); + } + + /// getPromotionType - Return the integer type that enumerators + /// should promote to. + QualType getPromotionType() const { return PromotionType; } + + /// \brief Set the promotion type. + void setPromotionType(QualType T) { PromotionType = T; } + + /// getIntegerType - Return the integer type this enum decl corresponds to. + /// This returns a null qualtype for an enum forward definition. + QualType getIntegerType() const { + if (!IntegerType) + return QualType(); + if (const Type* T = IntegerType.dyn_cast()) + return QualType(T, 0); + return IntegerType.get()->getType(); + } + + /// \brief Set the underlying integer type. + void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); } + + /// \brief Set the underlying integer type source info. + void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; } + + /// \brief Return the type source info for the underlying integer type, + /// if no type source info exists, return 0. + TypeSourceInfo* getIntegerTypeSourceInfo() const { + return IntegerType.dyn_cast(); + } + + /// \brief Returns the width in bits required to store all the + /// non-negative enumerators of this enum. + unsigned getNumPositiveBits() const { + return NumPositiveBits; + } + void setNumPositiveBits(unsigned Num) { + NumPositiveBits = Num; + assert(NumPositiveBits == Num && "can't store this bitcount"); + } + + /// \brief Returns the width in bits required to store all the + /// negative enumerators of this enum. These widths include + /// the rightmost leading 1; that is: + /// + /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS + /// ------------------------ ------- ----------------- + /// -1 1111111 1 + /// -10 1110110 5 + /// -101 1001011 8 + unsigned getNumNegativeBits() const { + return NumNegativeBits; + } + void setNumNegativeBits(unsigned Num) { + NumNegativeBits = Num; + } + + /// \brief Returns true if this is a C++0x scoped enumeration. + bool isScoped() const { + return IsScoped; + } + + /// \brief Returns true if this is a C++0x scoped enumeration. + bool isScopedUsingClassTag() const { + return IsScopedUsingClassTag; + } + + /// \brief Returns true if this is a C++0x enumeration with fixed underlying + /// type. + bool isFixed() const { + return IsFixed; + } + + /// \brief Returns true if this can be considered a complete type. + bool isComplete() const { + return isCompleteDefinition() || isFixed(); + } + + /// \brief Returns the enumeration (declared within the template) + /// from which this enumeration type was instantiated, or NULL if + /// this enumeration was not instantiated from any template. + EnumDecl *getInstantiatedFromMemberEnum() const; + + /// \brief If this enumeration is a member of a specialization of a + /// templated class, determine what kind of template specialization + /// or instantiation this is. + TemplateSpecializationKind getTemplateSpecializationKind() const; + + /// \brief For an enumeration member that was instantiated from a member + /// enumeration of a templated class, set the template specialiation kind. + void setTemplateSpecializationKind(TemplateSpecializationKind TSK, + SourceLocation PointOfInstantiation = SourceLocation()); + + /// \brief If this enumeration is an instantiation of a member enumeration of + /// a class template specialization, retrieves the member specialization + /// information. + MemberSpecializationInfo *getMemberSpecializationInfo() const { + return SpecializationInfo; + } + + /// \brief Specify that this enumeration is an instantiation of the + /// member enumeration ED. + void setInstantiationOfMemberEnum(EnumDecl *ED, + TemplateSpecializationKind TSK) { + setInstantiationOfMemberEnum(getASTContext(), ED, TSK); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const EnumDecl *D) { return true; } + static bool classofKind(Kind K) { return K == Enum; } + + friend class ASTDeclReader; +}; + + +/// RecordDecl - Represents a struct/union/class. For example: +/// struct X; // Forward declaration, no "body". +/// union Y { int A, B; }; // Has body with members A and B (FieldDecls). +/// This decl will be marked invalid if *any* members are invalid. +/// +class RecordDecl : public TagDecl { + // FIXME: This can be packed into the bitfields in Decl. + /// HasFlexibleArrayMember - This is true if this struct ends with a flexible + /// array member (e.g. int X[]) or if this union contains a struct that does. + /// If so, this cannot be contained in arrays or other structs as a member. + bool HasFlexibleArrayMember : 1; + + /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct + /// or union. + bool AnonymousStructOrUnion : 1; + + /// HasObjectMember - This is true if this struct has at least one member + /// containing an Objective-C object pointer type. + bool HasObjectMember : 1; + + /// \brief Whether the field declarations of this record have been loaded + /// from external storage. To avoid unnecessary deserialization of + /// methods/nested types we allow deserialization of just the fields + /// when needed. + mutable bool LoadedFieldsFromExternalStorage : 1; + friend class DeclContext; + +protected: + RecordDecl(Kind DK, TagKind TK, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, RecordDecl *PrevDecl); + +public: + static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, RecordDecl* PrevDecl = 0); + static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); + + const RecordDecl *getPreviousDecl() const { + return cast_or_null(TagDecl::getPreviousDecl()); + } + RecordDecl *getPreviousDecl() { + return cast_or_null(TagDecl::getPreviousDecl()); + } + + const RecordDecl *getMostRecentDecl() const { + return cast(TagDecl::getMostRecentDecl()); + } + RecordDecl *getMostRecentDecl() { + return cast(TagDecl::getMostRecentDecl()); + } + + bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; } + void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; } + + /// isAnonymousStructOrUnion - Whether this is an anonymous struct + /// or union. To be an anonymous struct or union, it must have been + /// declared without a name and there must be no objects of this + /// type declared, e.g., + /// @code + /// union { int i; float f; }; + /// @endcode + /// is an anonymous union but neither of the following are: + /// @code + /// union X { int i; float f; }; + /// union { int i; float f; } obj; + /// @endcode + bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; } + void setAnonymousStructOrUnion(bool Anon) { + AnonymousStructOrUnion = Anon; + } + + bool hasObjectMember() const { return HasObjectMember; } + void setHasObjectMember (bool val) { HasObjectMember = val; } + + /// \brief Determines whether this declaration represents the + /// injected class name. + /// + /// The injected class name in C++ is the name of the class that + /// appears inside the class itself. For example: + /// + /// \code + /// struct C { + /// // C is implicitly declared here as a synonym for the class name. + /// }; + /// + /// C::C c; // same as "C c;" + /// \endcode + bool isInjectedClassName() const; + + /// getDefinition - Returns the RecordDecl that actually defines + /// this struct/union/class. When determining whether or not a + /// struct/union/class is completely defined, one should use this + /// method as opposed to 'isCompleteDefinition'. + /// 'isCompleteDefinition' indicates whether or not a specific + /// RecordDecl is a completed definition, not whether or not the + /// record type is defined. This method returns NULL if there is + /// no RecordDecl that defines the struct/union/tag. + RecordDecl *getDefinition() const { + return cast_or_null(TagDecl::getDefinition()); + } + + // Iterator access to field members. The field iterator only visits + // the non-static data members of this class, ignoring any static + // data members, functions, constructors, destructors, etc. + typedef specific_decl_iterator field_iterator; + + field_iterator field_begin() const; + + field_iterator field_end() const { + return field_iterator(decl_iterator()); + } + + // field_empty - Whether there are any fields (non-static data + // members) in this record. + bool field_empty() const { + return field_begin() == field_end(); + } + + /// completeDefinition - Notes that the definition of this type is + /// now complete. + virtual void completeDefinition(); + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const RecordDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstRecord && K <= lastRecord; + } + +private: + /// \brief Deserialize just the fields. + void LoadFieldsFromExternalStorage() const; +}; + +class FileScopeAsmDecl : public Decl { + virtual void anchor(); + StringLiteral *AsmString; + SourceLocation RParenLoc; + FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring, + SourceLocation StartL, SourceLocation EndL) + : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {} +public: + static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC, + StringLiteral *Str, SourceLocation AsmLoc, + SourceLocation RParenLoc); + + static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + SourceLocation getAsmLoc() const { return getLocation(); } + SourceLocation getRParenLoc() const { return RParenLoc; } + void setRParenLoc(SourceLocation L) { RParenLoc = L; } + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(getAsmLoc(), getRParenLoc()); + } + + const StringLiteral *getAsmString() const { return AsmString; } + StringLiteral *getAsmString() { return AsmString; } + void setAsmString(StringLiteral *Asm) { AsmString = Asm; } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const FileScopeAsmDecl *D) { return true; } + static bool classofKind(Kind K) { return K == FileScopeAsm; } +}; + +/// BlockDecl - This represents a block literal declaration, which is like an +/// unnamed FunctionDecl. For example: +/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } +/// +class BlockDecl : public Decl, public DeclContext { +public: + /// A class which contains all the information about a particular + /// captured value. + class Capture { + enum { + flag_isByRef = 0x1, + flag_isNested = 0x2 + }; + + /// The variable being captured. + llvm::PointerIntPair VariableAndFlags; + + /// The copy expression, expressed in terms of a DeclRef (or + /// BlockDeclRef) to the captured variable. Only required if the + /// variable has a C++ class type. + Expr *CopyExpr; + + public: + Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy) + : VariableAndFlags(variable, + (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)), + CopyExpr(copy) {} + + /// The variable being captured. + VarDecl *getVariable() const { return VariableAndFlags.getPointer(); } + + /// Whether this is a "by ref" capture, i.e. a capture of a __block + /// variable. + bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; } + + /// Whether this is a nested capture, i.e. the variable captured + /// is not from outside the immediately enclosing function/block. + bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; } + + bool hasCopyExpr() const { return CopyExpr != 0; } + Expr *getCopyExpr() const { return CopyExpr; } + void setCopyExpr(Expr *e) { CopyExpr = e; } + }; + +private: + // FIXME: This can be packed into the bitfields in Decl. + bool IsVariadic : 1; + bool CapturesCXXThis : 1; + bool BlockMissingReturnType : 1; + bool IsConversionFromLambda : 1; + /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal + /// parameters of this function. This is null if a prototype or if there are + /// no formals. + ParmVarDecl **ParamInfo; + unsigned NumParams; + + Stmt *Body; + TypeSourceInfo *SignatureAsWritten; + + Capture *Captures; + unsigned NumCaptures; + +protected: + BlockDecl(DeclContext *DC, SourceLocation CaretLoc) + : Decl(Block, DC, CaretLoc), DeclContext(Block), + IsVariadic(false), CapturesCXXThis(false), + BlockMissingReturnType(true), IsConversionFromLambda(false), + ParamInfo(0), NumParams(0), Body(0), + SignatureAsWritten(0), Captures(0), NumCaptures(0) {} + +public: + static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); + static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + SourceLocation getCaretLocation() const { return getLocation(); } + + bool isVariadic() const { return IsVariadic; } + void setIsVariadic(bool value) { IsVariadic = value; } + + CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } + Stmt *getBody() const { return (Stmt*) Body; } + void setBody(CompoundStmt *B) { Body = (Stmt*) B; } + + void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; } + TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; } + + // Iterator access to formal parameters. + unsigned param_size() const { return getNumParams(); } + typedef ParmVarDecl **param_iterator; + typedef ParmVarDecl * const *param_const_iterator; + + bool param_empty() const { return NumParams == 0; } + param_iterator param_begin() { return ParamInfo; } + param_iterator param_end() { return ParamInfo+param_size(); } + + param_const_iterator param_begin() const { return ParamInfo; } + param_const_iterator param_end() const { return ParamInfo+param_size(); } + + unsigned getNumParams() const { return NumParams; } + const ParmVarDecl *getParamDecl(unsigned i) const { + assert(i < getNumParams() && "Illegal param #"); + return ParamInfo[i]; + } + ParmVarDecl *getParamDecl(unsigned i) { + assert(i < getNumParams() && "Illegal param #"); + return ParamInfo[i]; + } + void setParams(llvm::ArrayRef NewParamInfo); + + /// hasCaptures - True if this block (or its nested blocks) captures + /// anything of local storage from its enclosing scopes. + bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; } + + /// getNumCaptures - Returns the number of captured variables. + /// Does not include an entry for 'this'. + unsigned getNumCaptures() const { return NumCaptures; } + + typedef const Capture *capture_iterator; + typedef const Capture *capture_const_iterator; + capture_iterator capture_begin() { return Captures; } + capture_iterator capture_end() { return Captures + NumCaptures; } + capture_const_iterator capture_begin() const { return Captures; } + capture_const_iterator capture_end() const { return Captures + NumCaptures; } + + bool capturesCXXThis() const { return CapturesCXXThis; } + bool blockMissingReturnType() const { return BlockMissingReturnType; } + void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; } + + bool isConversionFromLambda() const { return IsConversionFromLambda; } + void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; } + + bool capturesVariable(const VarDecl *var) const; + + void setCaptures(ASTContext &Context, + const Capture *begin, + const Capture *end, + bool capturesCXXThis); + + virtual SourceRange getSourceRange() const LLVM_READONLY; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const BlockDecl *D) { return true; } + static bool classofKind(Kind K) { return K == Block; } + static DeclContext *castToDeclContext(const BlockDecl *D) { + return static_cast(const_cast(D)); + } + static BlockDecl *castFromDeclContext(const DeclContext *DC) { + return static_cast(const_cast(DC)); + } +}; + +/// \brief Describes a module import declaration, which makes the contents +/// of the named module visible in the current translation unit. +/// +/// An import declaration imports the named module (or submodule). For example: +/// \code +/// @__experimental_modules_import std.vector; +/// \endcode +/// +/// Import declarations can also be implicitly generated from #include/#import +/// directives. +class ImportDecl : public Decl { + /// \brief The imported module, along with a bit that indicates whether + /// we have source-location information for each identifier in the module + /// name. + /// + /// When the bit is false, we only have a single source location for the + /// end of the import declaration. + llvm::PointerIntPair ImportedAndComplete; + + /// \brief The next import in the list of imports local to the translation + /// unit being parsed (not loaded from an AST file). + ImportDecl *NextLocalImport; + + friend class ASTReader; + friend class ASTDeclReader; + friend class ASTContext; + + ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, + ArrayRef IdentifierLocs); + + ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, + SourceLocation EndLoc); + + ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { } + +public: + /// \brief Create a new module import declaration. + static ImportDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, Module *Imported, + ArrayRef IdentifierLocs); + + /// \brief Create a new module import declaration for an implicitly-generated + /// import. + static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, Module *Imported, + SourceLocation EndLoc); + + /// \brief Create a new, deserialized module import declaration. + static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, + unsigned NumLocations); + + /// \brief Retrieve the module that was imported by the import declaration. + Module *getImportedModule() const { return ImportedAndComplete.getPointer(); } + + /// \brief Retrieves the locations of each of the identifiers that make up + /// the complete module name in the import declaration. + /// + /// This will return an empty array if the locations of the individual + /// identifiers aren't available. + ArrayRef getIdentifierLocs() const; + + virtual SourceRange getSourceRange() const LLVM_READONLY; + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ImportDecl *D) { return true; } + static bool classofKind(Kind K) { return K == Import; } +}; + + +/// Insertion operator for diagnostics. This allows sending NamedDecl's +/// into a diagnostic with <<. +inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, + const NamedDecl* ND) { + DB.AddTaggedVal(reinterpret_cast(ND), + DiagnosticsEngine::ak_nameddecl); + return DB; +} +inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, + const NamedDecl* ND) { + PD.AddTaggedVal(reinterpret_cast(ND), + DiagnosticsEngine::ak_nameddecl); + return PD; +} + +template +void Redeclarable::setPreviousDeclaration(decl_type *PrevDecl) { + // Note: This routine is implemented here because we need both NamedDecl + // and Redeclarable to be defined. + + decl_type *First; + + if (PrevDecl) { + // Point to previous. Make sure that this is actually the most recent + // redeclaration, or we can build invalid chains. If the most recent + // redeclaration is invalid, it won't be PrevDecl, but we want it anyway. + RedeclLink = PreviousDeclLink( + llvm::cast(PrevDecl->getMostRecentDecl())); + First = PrevDecl->getFirstDeclaration(); + assert(First->RedeclLink.NextIsLatest() && "Expected first"); + } else { + // Make this first. + First = static_cast(this); + } + + // First one will point to this one as latest. + First->RedeclLink = LatestDeclLink(static_cast(this)); + if (NamedDecl *ND = dyn_cast(static_cast(this))) + ND->ClearLinkageCache(); +} + +// Inline function definitions. + +/// \brief Check if the given decl is complete. +/// +/// We use this function to break a cycle between the inline definitions in +/// Type.h and Decl.h. +inline bool IsEnumDeclComplete(EnumDecl *ED) { + return ED->isComplete(); +} + +/// \brief Check if the given decl is scoped. +/// +/// We use this function to break a cycle between the inline definitions in +/// Type.h and Decl.h. +inline bool IsEnumDeclScoped(EnumDecl *ED) { + return ED->isScoped(); +} + +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/DeclAccessPair.h b/cpp/llvm/tools/clang/include/clang/AST/DeclAccessPair.h new file mode 100644 index 00000000..7ecd8f8b --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/DeclAccessPair.h @@ -0,0 +1,72 @@ +//===--- DeclAccessPair.h - A decl bundled with its path access -*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the DeclAccessPair class, which provides an +// efficient representation of a pair of a NamedDecl* and an +// AccessSpecifier. Generally the access specifier gives the +// natural access of a declaration when named in a class, as +// defined in C++ [class.access.base]p1. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_DECLACCESSPAIR_H +#define LLVM_CLANG_AST_DECLACCESSPAIR_H + +#include "clang/Basic/Specifiers.h" + +namespace clang { + +class NamedDecl; + +/// A POD class for pairing a NamedDecl* with an access specifier. +/// Can be put into unions. +class DeclAccessPair { + NamedDecl *Ptr; // we'd use llvm::PointerUnion, but it isn't trivial + + enum { Mask = 0x3 }; + +public: + static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS) { + DeclAccessPair p; + p.set(D, AS); + return p; + } + + NamedDecl *getDecl() const { + return (NamedDecl*) (~Mask & (uintptr_t) Ptr); + } + AccessSpecifier getAccess() const { + return AccessSpecifier(Mask & (uintptr_t) Ptr); + } + + void setDecl(NamedDecl *D) { + set(D, getAccess()); + } + void setAccess(AccessSpecifier AS) { + set(getDecl(), AS); + } + void set(NamedDecl *D, AccessSpecifier AS) { + Ptr = reinterpret_cast(uintptr_t(AS) | + reinterpret_cast(D)); + } + + operator NamedDecl*() const { return getDecl(); } + NamedDecl *operator->() const { return getDecl(); } +}; +} + +// Take a moment to tell SmallVector that DeclAccessPair is POD. +namespace llvm { +template struct isPodLike; +template<> struct isPodLike { + static const bool value = true; +}; +} + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/DeclBase.h b/cpp/llvm/tools/clang/include/clang/AST/DeclBase.h new file mode 100644 index 00000000..22328912 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/DeclBase.h @@ -0,0 +1,1636 @@ +//===-- DeclBase.h - Base Classes for representing declarations -*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the Decl and DeclContext interfaces. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_DECLBASE_H +#define LLVM_CLANG_AST_DECLBASE_H + +#include "clang/AST/Attr.h" +#include "clang/AST/Type.h" +#include "clang/Basic/Specifiers.h" +#include "llvm/ADT/PointerUnion.h" +#include "llvm/Support/Compiler.h" +#include "llvm/Support/PrettyStackTrace.h" + +namespace clang { +class DeclContext; +class TranslationUnitDecl; +class NamespaceDecl; +class UsingDirectiveDecl; +class NamedDecl; +class FunctionDecl; +class CXXRecordDecl; +class EnumDecl; +class ObjCMethodDecl; +class ObjCContainerDecl; +class ObjCInterfaceDecl; +class ObjCCategoryDecl; +class ObjCProtocolDecl; +class ObjCImplementationDecl; +class ObjCCategoryImplDecl; +class ObjCImplDecl; +class LinkageSpecDecl; +class BlockDecl; +class DeclarationName; +class CompoundStmt; +class StoredDeclsMap; +class DependentDiagnostic; +class ASTMutationListener; +} + +namespace llvm { +// DeclContext* is only 4-byte aligned on 32-bit systems. +template<> + class PointerLikeTypeTraits { + typedef clang::DeclContext* PT; +public: + static inline void *getAsVoidPointer(PT P) { return P; } + static inline PT getFromVoidPointer(void *P) { + return static_cast(P); + } + enum { NumLowBitsAvailable = 2 }; +}; +} + +namespace clang { + + /// \brief Captures the result of checking the availability of a + /// declaration. + enum AvailabilityResult { + AR_Available = 0, + AR_NotYetIntroduced, + AR_Deprecated, + AR_Unavailable + }; + +/// Decl - This represents one declaration (or definition), e.g. a variable, +/// typedef, function, struct, etc. +/// +class Decl { +public: + /// \brief Lists the kind of concrete classes of Decl. + enum Kind { +#define DECL(DERIVED, BASE) DERIVED, +#define ABSTRACT_DECL(DECL) +#define DECL_RANGE(BASE, START, END) \ + first##BASE = START, last##BASE = END, +#define LAST_DECL_RANGE(BASE, START, END) \ + first##BASE = START, last##BASE = END +#include "clang/AST/DeclNodes.inc" + }; + + /// \brief A placeholder type used to construct an empty shell of a + /// decl-derived type that will be filled in later (e.g., by some + /// deserialization method). + struct EmptyShell { }; + + /// IdentifierNamespace - The different namespaces in which + /// declarations may appear. According to C99 6.2.3, there are + /// four namespaces, labels, tags, members and ordinary + /// identifiers. C++ describes lookup completely differently: + /// certain lookups merely "ignore" certain kinds of declarations, + /// usually based on whether the declaration is of a type, etc. + /// + /// These are meant as bitmasks, so that searches in + /// C++ can look into the "tag" namespace during ordinary lookup. + /// + /// Decl currently provides 15 bits of IDNS bits. + enum IdentifierNamespace { + /// Labels, declared with 'x:' and referenced with 'goto x'. + IDNS_Label = 0x0001, + + /// Tags, declared with 'struct foo;' and referenced with + /// 'struct foo'. All tags are also types. This is what + /// elaborated-type-specifiers look for in C. + IDNS_Tag = 0x0002, + + /// Types, declared with 'struct foo', typedefs, etc. + /// This is what elaborated-type-specifiers look for in C++, + /// but note that it's ill-formed to find a non-tag. + IDNS_Type = 0x0004, + + /// Members, declared with object declarations within tag + /// definitions. In C, these can only be found by "qualified" + /// lookup in member expressions. In C++, they're found by + /// normal lookup. + IDNS_Member = 0x0008, + + /// Namespaces, declared with 'namespace foo {}'. + /// Lookup for nested-name-specifiers find these. + IDNS_Namespace = 0x0010, + + /// Ordinary names. In C, everything that's not a label, tag, + /// or member ends up here. + IDNS_Ordinary = 0x0020, + + /// Objective C @protocol. + IDNS_ObjCProtocol = 0x0040, + + /// This declaration is a friend function. A friend function + /// declaration is always in this namespace but may also be in + /// IDNS_Ordinary if it was previously declared. + IDNS_OrdinaryFriend = 0x0080, + + /// This declaration is a friend class. A friend class + /// declaration is always in this namespace but may also be in + /// IDNS_Tag|IDNS_Type if it was previously declared. + IDNS_TagFriend = 0x0100, + + /// This declaration is a using declaration. A using declaration + /// *introduces* a number of other declarations into the current + /// scope, and those declarations use the IDNS of their targets, + /// but the actual using declarations go in this namespace. + IDNS_Using = 0x0200, + + /// This declaration is a C++ operator declared in a non-class + /// context. All such operators are also in IDNS_Ordinary. + /// C++ lexical operator lookup looks for these. + IDNS_NonMemberOperator = 0x0400 + }; + + /// ObjCDeclQualifier - 'Qualifiers' written next to the return and + /// parameter types in method declarations. Other than remembering + /// them and mangling them into the method's signature string, these + /// are ignored by the compiler; they are consumed by certain + /// remote-messaging frameworks. + /// + /// in, inout, and out are mutually exclusive and apply only to + /// method parameters. bycopy and byref are mutually exclusive and + /// apply only to method parameters (?). oneway applies only to + /// results. All of these expect their corresponding parameter to + /// have a particular type. None of this is currently enforced by + /// clang. + /// + /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier. + enum ObjCDeclQualifier { + OBJC_TQ_None = 0x0, + OBJC_TQ_In = 0x1, + OBJC_TQ_Inout = 0x2, + OBJC_TQ_Out = 0x4, + OBJC_TQ_Bycopy = 0x8, + OBJC_TQ_Byref = 0x10, + OBJC_TQ_Oneway = 0x20 + }; + +protected: + // Enumeration values used in the bits stored in NextInContextAndBits. + enum { + /// \brief Whether this declaration is a top-level declaration (function, + /// global variable, etc.) that is lexically inside an objc container + /// definition. + TopLevelDeclInObjCContainerFlag = 0x01, + + /// \brief Whether this declaration is private to the module in which it was + /// defined. + ModulePrivateFlag = 0x02 + }; + + /// \brief The next declaration within the same lexical + /// DeclContext. These pointers form the linked list that is + /// traversed via DeclContext's decls_begin()/decls_end(). + /// + /// The extra two bits are used for the TopLevelDeclInObjCContainer and + /// ModulePrivate bits. + llvm::PointerIntPair NextInContextAndBits; + +private: + friend class DeclContext; + + struct MultipleDC { + DeclContext *SemanticDC; + DeclContext *LexicalDC; + }; + + + /// DeclCtx - Holds either a DeclContext* or a MultipleDC*. + /// For declarations that don't contain C++ scope specifiers, it contains + /// the DeclContext where the Decl was declared. + /// For declarations with C++ scope specifiers, it contains a MultipleDC* + /// with the context where it semantically belongs (SemanticDC) and the + /// context where it was lexically declared (LexicalDC). + /// e.g.: + /// + /// namespace A { + /// void f(); // SemanticDC == LexicalDC == 'namespace A' + /// } + /// void A::f(); // SemanticDC == namespace 'A' + /// // LexicalDC == global namespace + llvm::PointerUnion DeclCtx; + + inline bool isInSemaDC() const { return DeclCtx.is(); } + inline bool isOutOfSemaDC() const { return DeclCtx.is(); } + inline MultipleDC *getMultipleDC() const { + return DeclCtx.get(); + } + inline DeclContext *getSemanticDC() const { + return DeclCtx.get(); + } + + /// Loc - The location of this decl. + SourceLocation Loc; + + /// DeclKind - This indicates which class this is. + unsigned DeclKind : 8; + + /// InvalidDecl - This indicates a semantic error occurred. + unsigned InvalidDecl : 1; + + /// HasAttrs - This indicates whether the decl has attributes or not. + unsigned HasAttrs : 1; + + /// Implicit - Whether this declaration was implicitly generated by + /// the implementation rather than explicitly written by the user. + unsigned Implicit : 1; + + /// \brief Whether this declaration was "used", meaning that a definition is + /// required. + unsigned Used : 1; + + /// \brief Whether this declaration was "referenced". + /// The difference with 'Used' is whether the reference appears in a + /// evaluated context or not, e.g. functions used in uninstantiated templates + /// are regarded as "referenced" but not "used". + unsigned Referenced : 1; + + /// \brief Whether statistic collection is enabled. + static bool StatisticsEnabled; + +protected: + /// Access - Used by C++ decls for the access specifier. + // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum + unsigned Access : 2; + friend class CXXClassMemberWrapper; + + /// \brief Whether this declaration was loaded from an AST file. + unsigned FromASTFile : 1; + + /// \brief Whether this declaration is hidden from normal name lookup, e.g., + /// because it is was loaded from an AST file is either module-private or + /// because its submodule has not been made visible. + unsigned Hidden : 1; + + /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in. + unsigned IdentifierNamespace : 12; + + /// \brief Whether the \c CachedLinkage field is active. + /// + /// This field is only valid for NamedDecls subclasses. + mutable unsigned HasCachedLinkage : 1; + + /// \brief If \c HasCachedLinkage, the linkage of this declaration. + /// + /// This field is only valid for NamedDecls subclasses. + mutable unsigned CachedLinkage : 2; + + friend class ASTDeclWriter; + friend class ASTDeclReader; + friend class ASTReader; + +private: + void CheckAccessDeclContext() const; + +protected: + + Decl(Kind DK, DeclContext *DC, SourceLocation L) + : NextInContextAndBits(), DeclCtx(DC), + Loc(L), DeclKind(DK), InvalidDecl(0), + HasAttrs(false), Implicit(false), Used(false), Referenced(false), + Access(AS_none), FromASTFile(0), Hidden(0), + IdentifierNamespace(getIdentifierNamespaceForKind(DK)), + HasCachedLinkage(0) + { + if (StatisticsEnabled) add(DK); + } + + Decl(Kind DK, EmptyShell Empty) + : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0), + HasAttrs(false), Implicit(false), Used(false), Referenced(false), + Access(AS_none), FromASTFile(0), Hidden(0), + IdentifierNamespace(getIdentifierNamespaceForKind(DK)), + HasCachedLinkage(0) + { + if (StatisticsEnabled) add(DK); + } + + virtual ~Decl(); + + /// \brief Allocate memory for a deserialized declaration. + /// + /// This routine must be used to allocate memory for any declaration that is + /// deserialized from a module file. + /// + /// \param Context The context in which we will allocate memory. + /// \param ID The global ID of the deserialized declaration. + /// \param Size The size of the allocated object. + static void *AllocateDeserializedDecl(const ASTContext &Context, + unsigned ID, + unsigned Size); + +public: + + /// \brief Source range that this declaration covers. + virtual SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(getLocation(), getLocation()); + } + SourceLocation getLocStart() const LLVM_READONLY { + return getSourceRange().getBegin(); + } + SourceLocation getLocEnd() const LLVM_READONLY { + return getSourceRange().getEnd(); + } + + SourceLocation getLocation() const { return Loc; } + void setLocation(SourceLocation L) { Loc = L; } + + Kind getKind() const { return static_cast(DeclKind); } + const char *getDeclKindName() const; + + Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); } + const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();} + + DeclContext *getDeclContext() { + if (isInSemaDC()) + return getSemanticDC(); + return getMultipleDC()->SemanticDC; + } + const DeclContext *getDeclContext() const { + return const_cast(this)->getDeclContext(); + } + + /// Finds the innermost non-closure context of this declaration. + /// That is, walk out the DeclContext chain, skipping any blocks. + DeclContext *getNonClosureContext(); + const DeclContext *getNonClosureContext() const { + return const_cast(this)->getNonClosureContext(); + } + + TranslationUnitDecl *getTranslationUnitDecl(); + const TranslationUnitDecl *getTranslationUnitDecl() const { + return const_cast(this)->getTranslationUnitDecl(); + } + + bool isInAnonymousNamespace() const; + + ASTContext &getASTContext() const LLVM_READONLY; + + void setAccess(AccessSpecifier AS) { + Access = AS; +#ifndef NDEBUG + CheckAccessDeclContext(); +#endif + } + + AccessSpecifier getAccess() const { +#ifndef NDEBUG + CheckAccessDeclContext(); +#endif + return AccessSpecifier(Access); + } + + bool hasAttrs() const { return HasAttrs; } + void setAttrs(const AttrVec& Attrs) { + return setAttrsImpl(Attrs, getASTContext()); + } + AttrVec &getAttrs() { + return const_cast(const_cast(this)->getAttrs()); + } + const AttrVec &getAttrs() const; + void swapAttrs(Decl *D); + void dropAttrs(); + + void addAttr(Attr *A) { + if (hasAttrs()) + getAttrs().push_back(A); + else + setAttrs(AttrVec(1, A)); + } + + typedef AttrVec::const_iterator attr_iterator; + + // FIXME: Do not rely on iterators having comparable singular values. + // Note that this should error out if they do not. + attr_iterator attr_begin() const { + return hasAttrs() ? getAttrs().begin() : 0; + } + attr_iterator attr_end() const { + return hasAttrs() ? getAttrs().end() : 0; + } + + template + void dropAttr() { + if (!HasAttrs) return; + + AttrVec &Attrs = getAttrs(); + for (unsigned i = 0, e = Attrs.size(); i != e; /* in loop */) { + if (isa(Attrs[i])) { + Attrs.erase(Attrs.begin() + i); + --e; + } + else + ++i; + } + if (Attrs.empty()) + HasAttrs = false; + } + + template + specific_attr_iterator specific_attr_begin() const { + return specific_attr_iterator(attr_begin()); + } + template + specific_attr_iterator specific_attr_end() const { + return specific_attr_iterator(attr_end()); + } + + template T *getAttr() const { + return hasAttrs() ? getSpecificAttr(getAttrs()) : 0; + } + template bool hasAttr() const { + return hasAttrs() && hasSpecificAttr(getAttrs()); + } + + /// getMaxAlignment - return the maximum alignment specified by attributes + /// on this decl, 0 if there are none. + unsigned getMaxAlignment() const { + return hasAttrs() ? getMaxAttrAlignment(getAttrs(), getASTContext()) : 0; + } + + /// setInvalidDecl - Indicates the Decl had a semantic error. This + /// allows for graceful error recovery. + void setInvalidDecl(bool Invalid = true); + bool isInvalidDecl() const { return (bool) InvalidDecl; } + + /// isImplicit - Indicates whether the declaration was implicitly + /// generated by the implementation. If false, this declaration + /// was written explicitly in the source code. + bool isImplicit() const { return Implicit; } + void setImplicit(bool I = true) { Implicit = I; } + + /// \brief Whether this declaration was used, meaning that a definition + /// is required. + /// + /// \param CheckUsedAttr When true, also consider the "used" attribute + /// (in addition to the "used" bit set by \c setUsed()) when determining + /// whether the function is used. + bool isUsed(bool CheckUsedAttr = true) const; + + void setUsed(bool U = true) { Used = U; } + + /// \brief Whether this declaration was referenced. + bool isReferenced() const; + + void setReferenced(bool R = true) { Referenced = R; } + + /// \brief Whether this declaration is a top-level declaration (function, + /// global variable, etc.) that is lexically inside an objc container + /// definition. + bool isTopLevelDeclInObjCContainer() const { + return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag; + } + + void setTopLevelDeclInObjCContainer(bool V = true) { + unsigned Bits = NextInContextAndBits.getInt(); + if (V) + Bits |= TopLevelDeclInObjCContainerFlag; + else + Bits &= ~TopLevelDeclInObjCContainerFlag; + NextInContextAndBits.setInt(Bits); + } + +protected: + /// \brief Whether this declaration was marked as being private to the + /// module in which it was defined. + bool isModulePrivate() const { + return NextInContextAndBits.getInt() & ModulePrivateFlag; + } + + /// \brief Specify whether this declaration was marked as being private + /// to the module in which it was defined. + void setModulePrivate(bool MP = true) { + unsigned Bits = NextInContextAndBits.getInt(); + if (MP) + Bits |= ModulePrivateFlag; + else + Bits &= ~ModulePrivateFlag; + NextInContextAndBits.setInt(Bits); + } + + /// \brief Set the owning module ID. + void setOwningModuleID(unsigned ID) { + assert(isFromASTFile() && "Only works on a deserialized declaration"); + *((unsigned*)this - 2) = ID; + } + +public: + + /// \brief Determine the availability of the given declaration. + /// + /// This routine will determine the most restrictive availability of + /// the given declaration (e.g., preferring 'unavailable' to + /// 'deprecated'). + /// + /// \param Message If non-NULL and the result is not \c + /// AR_Available, will be set to a (possibly empty) message + /// describing why the declaration has not been introduced, is + /// deprecated, or is unavailable. + AvailabilityResult getAvailability(std::string *Message = 0) const; + + /// \brief Determine whether this declaration is marked 'deprecated'. + /// + /// \param Message If non-NULL and the declaration is deprecated, + /// this will be set to the message describing why the declaration + /// was deprecated (which may be empty). + bool isDeprecated(std::string *Message = 0) const { + return getAvailability(Message) == AR_Deprecated; + } + + /// \brief Determine whether this declaration is marked 'unavailable'. + /// + /// \param Message If non-NULL and the declaration is unavailable, + /// this will be set to the message describing why the declaration + /// was made unavailable (which may be empty). + bool isUnavailable(std::string *Message = 0) const { + return getAvailability(Message) == AR_Unavailable; + } + + /// \brief Determine whether this is a weak-imported symbol. + /// + /// Weak-imported symbols are typically marked with the + /// 'weak_import' attribute, but may also be marked with an + /// 'availability' attribute where we're targing a platform prior to + /// the introduction of this feature. + bool isWeakImported() const; + + /// \brief Determines whether this symbol can be weak-imported, + /// e.g., whether it would be well-formed to add the weak_import + /// attribute. + /// + /// \param IsDefinition Set to \c true to indicate that this + /// declaration cannot be weak-imported because it has a definition. + bool canBeWeakImported(bool &IsDefinition) const; + + /// \brief Determine whether this declaration came from an AST file (such as + /// a precompiled header or module) rather than having been parsed. + bool isFromASTFile() const { return FromASTFile; } + + /// \brief Retrieve the global declaration ID associated with this + /// declaration, which specifies where in the + unsigned getGlobalID() const { + if (isFromASTFile()) + return *((const unsigned*)this - 1); + return 0; + } + + /// \brief Retrieve the global ID of the module that owns this particular + /// declaration. + unsigned getOwningModuleID() const { + if (isFromASTFile()) + return *((const unsigned*)this - 2); + + return 0; + } + + unsigned getIdentifierNamespace() const { + return IdentifierNamespace; + } + bool isInIdentifierNamespace(unsigned NS) const { + return getIdentifierNamespace() & NS; + } + static unsigned getIdentifierNamespaceForKind(Kind DK); + + bool hasTagIdentifierNamespace() const { + return isTagIdentifierNamespace(getIdentifierNamespace()); + } + static bool isTagIdentifierNamespace(unsigned NS) { + // TagDecls have Tag and Type set and may also have TagFriend. + return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type); + } + + /// getLexicalDeclContext - The declaration context where this Decl was + /// lexically declared (LexicalDC). May be different from + /// getDeclContext() (SemanticDC). + /// e.g.: + /// + /// namespace A { + /// void f(); // SemanticDC == LexicalDC == 'namespace A' + /// } + /// void A::f(); // SemanticDC == namespace 'A' + /// // LexicalDC == global namespace + DeclContext *getLexicalDeclContext() { + if (isInSemaDC()) + return getSemanticDC(); + return getMultipleDC()->LexicalDC; + } + const DeclContext *getLexicalDeclContext() const { + return const_cast(this)->getLexicalDeclContext(); + } + + virtual bool isOutOfLine() const { + return getLexicalDeclContext() != getDeclContext(); + } + + /// setDeclContext - Set both the semantic and lexical DeclContext + /// to DC. + void setDeclContext(DeclContext *DC); + + void setLexicalDeclContext(DeclContext *DC); + + /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this + /// scoped decl is defined outside the current function or method. This is + /// roughly global variables and functions, but also handles enums (which + /// could be defined inside or outside a function etc). + bool isDefinedOutsideFunctionOrMethod() const { + return getParentFunctionOrMethod() == 0; + } + + /// \brief If this decl is defined inside a function/method/block it returns + /// the corresponding DeclContext, otherwise it returns null. + const DeclContext *getParentFunctionOrMethod() const; + DeclContext *getParentFunctionOrMethod() { + return const_cast( + const_cast(this)->getParentFunctionOrMethod()); + } + + /// \brief Retrieves the "canonical" declaration of the given declaration. + virtual Decl *getCanonicalDecl() { return this; } + const Decl *getCanonicalDecl() const { + return const_cast(this)->getCanonicalDecl(); + } + + /// \brief Whether this particular Decl is a canonical one. + bool isCanonicalDecl() const { return getCanonicalDecl() == this; } + +protected: + /// \brief Returns the next redeclaration or itself if this is the only decl. + /// + /// Decl subclasses that can be redeclared should override this method so that + /// Decl::redecl_iterator can iterate over them. + virtual Decl *getNextRedeclaration() { return this; } + + /// \brief Implementation of getPreviousDecl(), to be overridden by any + /// subclass that has a redeclaration chain. + virtual Decl *getPreviousDeclImpl() { return 0; } + + /// \brief Implementation of getMostRecentDecl(), to be overridden by any + /// subclass that has a redeclaration chain. + virtual Decl *getMostRecentDeclImpl() { return this; } + +public: + /// \brief Iterates through all the redeclarations of the same decl. + class redecl_iterator { + /// Current - The current declaration. + Decl *Current; + Decl *Starter; + + public: + typedef Decl* value_type; + typedef Decl* reference; + typedef Decl* pointer; + typedef std::forward_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + + redecl_iterator() : Current(0) { } + explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { } + + reference operator*() const { return Current; } + pointer operator->() const { return Current; } + + redecl_iterator& operator++() { + assert(Current && "Advancing while iterator has reached end"); + // Get either previous decl or latest decl. + Decl *Next = Current->getNextRedeclaration(); + assert(Next && "Should return next redeclaration or itself, never null!"); + Current = (Next != Starter ? Next : 0); + return *this; + } + + redecl_iterator operator++(int) { + redecl_iterator tmp(*this); + ++(*this); + return tmp; + } + + friend bool operator==(redecl_iterator x, redecl_iterator y) { + return x.Current == y.Current; + } + friend bool operator!=(redecl_iterator x, redecl_iterator y) { + return x.Current != y.Current; + } + }; + + /// \brief Returns iterator for all the redeclarations of the same decl. + /// It will iterate at least once (when this decl is the only one). + redecl_iterator redecls_begin() const { + return redecl_iterator(const_cast(this)); + } + redecl_iterator redecls_end() const { return redecl_iterator(); } + + /// \brief Retrieve the previous declaration that declares the same entity + /// as this declaration, or NULL if there is no previous declaration. + Decl *getPreviousDecl() { return getPreviousDeclImpl(); } + + /// \brief Retrieve the most recent declaration that declares the same entity + /// as this declaration, or NULL if there is no previous declaration. + const Decl *getPreviousDecl() const { + return const_cast(this)->getPreviousDeclImpl(); + } + + /// \brief Retrieve the most recent declaration that declares the same entity + /// as this declaration (which may be this declaration). + Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); } + + /// \brief Retrieve the most recent declaration that declares the same entity + /// as this declaration (which may be this declaration). + const Decl *getMostRecentDecl() const { + return const_cast(this)->getMostRecentDeclImpl(); + } + + /// getBody - If this Decl represents a declaration for a body of code, + /// such as a function or method definition, this method returns the + /// top-level Stmt* of that body. Otherwise this method returns null. + virtual Stmt* getBody() const { return 0; } + + /// \brief Returns true if this Decl represents a declaration for a body of + /// code, such as a function or method definition. + virtual bool hasBody() const { return getBody() != 0; } + + /// getBodyRBrace - Gets the right brace of the body, if a body exists. + /// This works whether the body is a CompoundStmt or a CXXTryStmt. + SourceLocation getBodyRBrace() const; + + // global temp stats (until we have a per-module visitor) + static void add(Kind k); + static void EnableStatistics(); + static void PrintStats(); + + /// isTemplateParameter - Determines whether this declaration is a + /// template parameter. + bool isTemplateParameter() const; + + /// isTemplateParameter - Determines whether this declaration is a + /// template parameter pack. + bool isTemplateParameterPack() const; + + /// \brief Whether this declaration is a parameter pack. + bool isParameterPack() const; + + /// \brief returns true if this declaration is a template + bool isTemplateDecl() const; + + /// \brief Whether this declaration is a function or function template. + bool isFunctionOrFunctionTemplate() const; + + /// \brief Changes the namespace of this declaration to reflect that it's + /// the object of a friend declaration. + /// + /// These declarations appear in the lexical context of the friending + /// class, but in the semantic context of the actual entity. This property + /// applies only to a specific decl object; other redeclarations of the + /// same entity may not (and probably don't) share this property. + void setObjectOfFriendDecl(bool PreviouslyDeclared) { + unsigned OldNS = IdentifierNamespace; + assert((OldNS & (IDNS_Tag | IDNS_Ordinary | + IDNS_TagFriend | IDNS_OrdinaryFriend)) && + "namespace includes neither ordinary nor tag"); + assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | + IDNS_TagFriend | IDNS_OrdinaryFriend)) && + "namespace includes other than ordinary or tag"); + + IdentifierNamespace = 0; + if (OldNS & (IDNS_Tag | IDNS_TagFriend)) { + IdentifierNamespace |= IDNS_TagFriend; + if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Tag | IDNS_Type; + } + + if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend)) { + IdentifierNamespace |= IDNS_OrdinaryFriend; + if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Ordinary; + } + } + + enum FriendObjectKind { + FOK_None, // not a friend object + FOK_Declared, // a friend of a previously-declared entity + FOK_Undeclared // a friend of a previously-undeclared entity + }; + + /// \brief Determines whether this declaration is the object of a + /// friend declaration and, if so, what kind. + /// + /// There is currently no direct way to find the associated FriendDecl. + FriendObjectKind getFriendObjectKind() const { + unsigned mask + = (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend)); + if (!mask) return FOK_None; + return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? + FOK_Declared : FOK_Undeclared); + } + + /// Specifies that this declaration is a C++ overloaded non-member. + void setNonMemberOperator() { + assert(getKind() == Function || getKind() == FunctionTemplate); + assert((IdentifierNamespace & IDNS_Ordinary) && + "visible non-member operators should be in ordinary namespace"); + IdentifierNamespace |= IDNS_NonMemberOperator; + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *) { return true; } + static bool classofKind(Kind K) { return true; } + static DeclContext *castToDeclContext(const Decl *); + static Decl *castFromDeclContext(const DeclContext *); + + void print(raw_ostream &Out, unsigned Indentation = 0, + bool PrintInstantiation = false) const; + void print(raw_ostream &Out, const PrintingPolicy &Policy, + unsigned Indentation = 0, bool PrintInstantiation = false) const; + static void printGroup(Decl** Begin, unsigned NumDecls, + raw_ostream &Out, const PrintingPolicy &Policy, + unsigned Indentation = 0); + LLVM_ATTRIBUTE_USED void dump() const; + LLVM_ATTRIBUTE_USED void dumpXML() const; + void dumpXML(raw_ostream &OS) const; + +private: + void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx); + void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC, + ASTContext &Ctx); + +protected: + ASTMutationListener *getASTMutationListener() const; +}; + +/// \brief Determine whether two declarations declare the same entity. +inline bool declaresSameEntity(const Decl *D1, const Decl *D2) { + if (!D1 || !D2) + return false; + + if (D1 == D2) + return true; + + return D1->getCanonicalDecl() == D2->getCanonicalDecl(); +} + +/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when +/// doing something to a specific decl. +class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry { + const Decl *TheDecl; + SourceLocation Loc; + SourceManager &SM; + const char *Message; +public: + PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L, + SourceManager &sm, const char *Msg) + : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {} + + virtual void print(raw_ostream &OS) const; +}; + +class DeclContextLookupResult + : public std::pair { +public: + DeclContextLookupResult(NamedDecl **I, NamedDecl **E) + : std::pair(I, E) {} + DeclContextLookupResult() + : std::pair() {} + + using std::pair::operator=; +}; + +class DeclContextLookupConstResult + : public std::pair { +public: + DeclContextLookupConstResult(std::pair R) + : std::pair(R) {} + DeclContextLookupConstResult(NamedDecl * const *I, NamedDecl * const *E) + : std::pair(I, E) {} + DeclContextLookupConstResult() + : std::pair() {} + + using std::pair::operator=; +}; + +/// DeclContext - This is used only as base class of specific decl types that +/// can act as declaration contexts. These decls are (only the top classes +/// that directly derive from DeclContext are mentioned, not their subclasses): +/// +/// TranslationUnitDecl +/// NamespaceDecl +/// FunctionDecl +/// TagDecl +/// ObjCMethodDecl +/// ObjCContainerDecl +/// LinkageSpecDecl +/// BlockDecl +/// +class DeclContext { + /// DeclKind - This indicates which class this is. + unsigned DeclKind : 8; + + /// \brief Whether this declaration context also has some external + /// storage that contains additional declarations that are lexically + /// part of this context. + mutable unsigned ExternalLexicalStorage : 1; + + /// \brief Whether this declaration context also has some external + /// storage that contains additional declarations that are visible + /// in this context. + mutable unsigned ExternalVisibleStorage : 1; + + /// \brief Pointer to the data structure used to lookup declarations + /// within this context (or a DependentStoredDeclsMap if this is a + /// dependent context), and a bool indicating whether we have lazily + /// omitted any declarations from the map. We maintain the invariant + /// that, if the map contains an entry for a DeclarationName, then it + /// contains all relevant entries for that name. + mutable llvm::PointerIntPair LookupPtr; + +protected: + /// FirstDecl - The first declaration stored within this declaration + /// context. + mutable Decl *FirstDecl; + + /// LastDecl - The last declaration stored within this declaration + /// context. FIXME: We could probably cache this value somewhere + /// outside of the DeclContext, to reduce the size of DeclContext by + /// another pointer. + mutable Decl *LastDecl; + + friend class ExternalASTSource; + friend class ASTWriter; + + /// \brief Build up a chain of declarations. + /// + /// \returns the first/last pair of declarations. + static std::pair + BuildDeclChain(ArrayRef Decls, bool FieldsAlreadyLoaded); + + DeclContext(Decl::Kind K) + : DeclKind(K), ExternalLexicalStorage(false), + ExternalVisibleStorage(false), LookupPtr(0, false), FirstDecl(0), + LastDecl(0) { } + +public: + ~DeclContext(); + + Decl::Kind getDeclKind() const { + return static_cast(DeclKind); + } + const char *getDeclKindName() const; + + /// getParent - Returns the containing DeclContext. + DeclContext *getParent() { + return cast(this)->getDeclContext(); + } + const DeclContext *getParent() const { + return const_cast(this)->getParent(); + } + + /// getLexicalParent - Returns the containing lexical DeclContext. May be + /// different from getParent, e.g.: + /// + /// namespace A { + /// struct S; + /// } + /// struct A::S {}; // getParent() == namespace 'A' + /// // getLexicalParent() == translation unit + /// + DeclContext *getLexicalParent() { + return cast(this)->getLexicalDeclContext(); + } + const DeclContext *getLexicalParent() const { + return const_cast(this)->getLexicalParent(); + } + + DeclContext *getLookupParent(); + + const DeclContext *getLookupParent() const { + return const_cast(this)->getLookupParent(); + } + + ASTContext &getParentASTContext() const { + return cast(this)->getASTContext(); + } + + bool isClosure() const { + return DeclKind == Decl::Block; + } + + bool isObjCContainer() const { + switch (DeclKind) { + case Decl::ObjCCategory: + case Decl::ObjCCategoryImpl: + case Decl::ObjCImplementation: + case Decl::ObjCInterface: + case Decl::ObjCProtocol: + return true; + } + return false; + } + + bool isFunctionOrMethod() const { + switch (DeclKind) { + case Decl::Block: + case Decl::ObjCMethod: + return true; + default: + return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction; + } + } + + bool isFileContext() const { + return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace; + } + + bool isTranslationUnit() const { + return DeclKind == Decl::TranslationUnit; + } + + bool isRecord() const { + return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord; + } + + bool isNamespace() const { + return DeclKind == Decl::Namespace; + } + + bool isInlineNamespace() const; + + /// \brief Determines whether this context is dependent on a + /// template parameter. + bool isDependentContext() const; + + /// isTransparentContext - Determines whether this context is a + /// "transparent" context, meaning that the members declared in this + /// context are semantically declared in the nearest enclosing + /// non-transparent (opaque) context but are lexically declared in + /// this context. For example, consider the enumerators of an + /// enumeration type: + /// @code + /// enum E { + /// Val1 + /// }; + /// @endcode + /// Here, E is a transparent context, so its enumerator (Val1) will + /// appear (semantically) that it is in the same context of E. + /// Examples of transparent contexts include: enumerations (except for + /// C++0x scoped enums), and C++ linkage specifications. + bool isTransparentContext() const; + + /// \brief Determines whether this context is, or is nested within, + /// a C++ extern "C" linkage spec. + bool isExternCContext() const; + + /// \brief Determine whether this declaration context is equivalent + /// to the declaration context DC. + bool Equals(const DeclContext *DC) const { + return DC && this->getPrimaryContext() == DC->getPrimaryContext(); + } + + /// \brief Determine whether this declaration context encloses the + /// declaration context DC. + bool Encloses(const DeclContext *DC) const; + + /// \brief Find the nearest non-closure ancestor of this context, + /// i.e. the innermost semantic parent of this context which is not + /// a closure. A context may be its own non-closure ancestor. + DeclContext *getNonClosureAncestor(); + const DeclContext *getNonClosureAncestor() const { + return const_cast(this)->getNonClosureAncestor(); + } + + /// getPrimaryContext - There may be many different + /// declarations of the same entity (including forward declarations + /// of classes, multiple definitions of namespaces, etc.), each with + /// a different set of declarations. This routine returns the + /// "primary" DeclContext structure, which will contain the + /// information needed to perform name lookup into this context. + DeclContext *getPrimaryContext(); + const DeclContext *getPrimaryContext() const { + return const_cast(this)->getPrimaryContext(); + } + + /// getRedeclContext - Retrieve the context in which an entity conflicts with + /// other entities of the same name, or where it is a redeclaration if the + /// two entities are compatible. This skips through transparent contexts. + DeclContext *getRedeclContext(); + const DeclContext *getRedeclContext() const { + return const_cast(this)->getRedeclContext(); + } + + /// \brief Retrieve the nearest enclosing namespace context. + DeclContext *getEnclosingNamespaceContext(); + const DeclContext *getEnclosingNamespaceContext() const { + return const_cast(this)->getEnclosingNamespaceContext(); + } + + /// \brief Test if this context is part of the enclosing namespace set of + /// the context NS, as defined in C++0x [namespace.def]p9. If either context + /// isn't a namespace, this is equivalent to Equals(). + /// + /// The enclosing namespace set of a namespace is the namespace and, if it is + /// inline, its enclosing namespace, recursively. + bool InEnclosingNamespaceSetOf(const DeclContext *NS) const; + + /// \\brief Collects all of the declaration contexts that are semantically + /// connected to this declaration context. + /// + /// For declaration contexts that have multiple semantically connected but + /// syntactically distinct contexts, such as C++ namespaces, this routine + /// retrieves the complete set of such declaration contexts in source order. + /// For example, given: + /// + /// \code + /// namespace N { + /// int x; + /// } + /// namespace N { + /// int y; + /// } + /// \endcode + /// + /// The \c Contexts parameter will contain both definitions of N. + /// + /// \param Contexts Will be cleared and set to the set of declaration + /// contexts that are semanticaly connected to this declaration context, + /// in source order, including this context (which may be the only result, + /// for non-namespace contexts). + void collectAllContexts(llvm::SmallVectorImpl &Contexts); + + /// decl_iterator - Iterates through the declarations stored + /// within this context. + class decl_iterator { + /// Current - The current declaration. + Decl *Current; + + public: + typedef Decl* value_type; + typedef Decl* reference; + typedef Decl* pointer; + typedef std::forward_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + + decl_iterator() : Current(0) { } + explicit decl_iterator(Decl *C) : Current(C) { } + + reference operator*() const { return Current; } + pointer operator->() const { return Current; } + + decl_iterator& operator++() { + Current = Current->getNextDeclInContext(); + return *this; + } + + decl_iterator operator++(int) { + decl_iterator tmp(*this); + ++(*this); + return tmp; + } + + friend bool operator==(decl_iterator x, decl_iterator y) { + return x.Current == y.Current; + } + friend bool operator!=(decl_iterator x, decl_iterator y) { + return x.Current != y.Current; + } + }; + + /// decls_begin/decls_end - Iterate over the declarations stored in + /// this context. + decl_iterator decls_begin() const; + decl_iterator decls_end() const; + bool decls_empty() const; + + /// noload_decls_begin/end - Iterate over the declarations stored in this + /// context that are currently loaded; don't attempt to retrieve anything + /// from an external source. + decl_iterator noload_decls_begin() const; + decl_iterator noload_decls_end() const; + + /// specific_decl_iterator - Iterates over a subrange of + /// declarations stored in a DeclContext, providing only those that + /// are of type SpecificDecl (or a class derived from it). This + /// iterator is used, for example, to provide iteration over just + /// the fields within a RecordDecl (with SpecificDecl = FieldDecl). + template + class specific_decl_iterator { + /// Current - The current, underlying declaration iterator, which + /// will either be NULL or will point to a declaration of + /// type SpecificDecl. + DeclContext::decl_iterator Current; + + /// SkipToNextDecl - Advances the current position up to the next + /// declaration of type SpecificDecl that also meets the criteria + /// required by Acceptable. + void SkipToNextDecl() { + while (*Current && !isa(*Current)) + ++Current; + } + + public: + typedef SpecificDecl* value_type; + typedef SpecificDecl* reference; + typedef SpecificDecl* pointer; + typedef std::iterator_traits::difference_type + difference_type; + typedef std::forward_iterator_tag iterator_category; + + specific_decl_iterator() : Current() { } + + /// specific_decl_iterator - Construct a new iterator over a + /// subset of the declarations the range [C, + /// end-of-declarations). If A is non-NULL, it is a pointer to a + /// member function of SpecificDecl that should return true for + /// all of the SpecificDecl instances that will be in the subset + /// of iterators. For example, if you want Objective-C instance + /// methods, SpecificDecl will be ObjCMethodDecl and A will be + /// &ObjCMethodDecl::isInstanceMethod. + explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) { + SkipToNextDecl(); + } + + reference operator*() const { return cast(*Current); } + pointer operator->() const { return cast(*Current); } + + specific_decl_iterator& operator++() { + ++Current; + SkipToNextDecl(); + return *this; + } + + specific_decl_iterator operator++(int) { + specific_decl_iterator tmp(*this); + ++(*this); + return tmp; + } + + friend bool operator==(const specific_decl_iterator& x, + const specific_decl_iterator& y) { + return x.Current == y.Current; + } + + friend bool operator!=(const specific_decl_iterator& x, + const specific_decl_iterator& y) { + return x.Current != y.Current; + } + }; + + /// \brief Iterates over a filtered subrange of declarations stored + /// in a DeclContext. + /// + /// This iterator visits only those declarations that are of type + /// SpecificDecl (or a class derived from it) and that meet some + /// additional run-time criteria. This iterator is used, for + /// example, to provide access to the instance methods within an + /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and + /// Acceptable = ObjCMethodDecl::isInstanceMethod). + template + class filtered_decl_iterator { + /// Current - The current, underlying declaration iterator, which + /// will either be NULL or will point to a declaration of + /// type SpecificDecl. + DeclContext::decl_iterator Current; + + /// SkipToNextDecl - Advances the current position up to the next + /// declaration of type SpecificDecl that also meets the criteria + /// required by Acceptable. + void SkipToNextDecl() { + while (*Current && + (!isa(*Current) || + (Acceptable && !(cast(*Current)->*Acceptable)()))) + ++Current; + } + + public: + typedef SpecificDecl* value_type; + typedef SpecificDecl* reference; + typedef SpecificDecl* pointer; + typedef std::iterator_traits::difference_type + difference_type; + typedef std::forward_iterator_tag iterator_category; + + filtered_decl_iterator() : Current() { } + + /// specific_decl_iterator - Construct a new iterator over a + /// subset of the declarations the range [C, + /// end-of-declarations). If A is non-NULL, it is a pointer to a + /// member function of SpecificDecl that should return true for + /// all of the SpecificDecl instances that will be in the subset + /// of iterators. For example, if you want Objective-C instance + /// methods, SpecificDecl will be ObjCMethodDecl and A will be + /// &ObjCMethodDecl::isInstanceMethod. + explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) { + SkipToNextDecl(); + } + + reference operator*() const { return cast(*Current); } + pointer operator->() const { return cast(*Current); } + + filtered_decl_iterator& operator++() { + ++Current; + SkipToNextDecl(); + return *this; + } + + filtered_decl_iterator operator++(int) { + filtered_decl_iterator tmp(*this); + ++(*this); + return tmp; + } + + friend bool operator==(const filtered_decl_iterator& x, + const filtered_decl_iterator& y) { + return x.Current == y.Current; + } + + friend bool operator!=(const filtered_decl_iterator& x, + const filtered_decl_iterator& y) { + return x.Current != y.Current; + } + }; + + /// @brief Add the declaration D into this context. + /// + /// This routine should be invoked when the declaration D has first + /// been declared, to place D into the context where it was + /// (lexically) defined. Every declaration must be added to one + /// (and only one!) context, where it can be visited via + /// [decls_begin(), decls_end()). Once a declaration has been added + /// to its lexical context, the corresponding DeclContext owns the + /// declaration. + /// + /// If D is also a NamedDecl, it will be made visible within its + /// semantic context via makeDeclVisibleInContext. + void addDecl(Decl *D); + + /// @brief Add the declaration D into this context, but suppress + /// searches for external declarations with the same name. + /// + /// Although analogous in function to addDecl, this removes an + /// important check. This is only useful if the Decl is being + /// added in response to an external search; in all other cases, + /// addDecl() is the right function to use. + /// See the ASTImporter for use cases. + void addDeclInternal(Decl *D); + + /// @brief Add the declaration D to this context without modifying + /// any lookup tables. + /// + /// This is useful for some operations in dependent contexts where + /// the semantic context might not be dependent; this basically + /// only happens with friends. + void addHiddenDecl(Decl *D); + + /// @brief Removes a declaration from this context. + void removeDecl(Decl *D); + + /// lookup_iterator - An iterator that provides access to the results + /// of looking up a name within this context. + typedef NamedDecl **lookup_iterator; + + /// lookup_const_iterator - An iterator that provides non-mutable + /// access to the results of lookup up a name within this context. + typedef NamedDecl * const * lookup_const_iterator; + + typedef DeclContextLookupResult lookup_result; + typedef DeclContextLookupConstResult lookup_const_result; + + /// lookup - Find the declarations (if any) with the given Name in + /// this context. Returns a range of iterators that contains all of + /// the declarations with this name, with object, function, member, + /// and enumerator names preceding any tag name. Note that this + /// routine will not look into parent contexts. + lookup_result lookup(DeclarationName Name); + lookup_const_result lookup(DeclarationName Name) const; + + /// \brief A simplistic name lookup mechanism that performs name lookup + /// into this declaration context without consulting the external source. + /// + /// This function should almost never be used, because it subverts the + /// usual relationship between a DeclContext and the external source. + /// See the ASTImporter for the (few, but important) use cases. + void localUncachedLookup(DeclarationName Name, + llvm::SmallVectorImpl &Results); + + /// @brief Makes a declaration visible within this context. + /// + /// This routine makes the declaration D visible to name lookup + /// within this context and, if this is a transparent context, + /// within its parent contexts up to the first enclosing + /// non-transparent context. Making a declaration visible within a + /// context does not transfer ownership of a declaration, and a + /// declaration can be visible in many contexts that aren't its + /// lexical context. + /// + /// If D is a redeclaration of an existing declaration that is + /// visible from this context, as determined by + /// NamedDecl::declarationReplaces, the previous declaration will be + /// replaced with D. + void makeDeclVisibleInContext(NamedDecl *D); + + /// all_lookups_iterator - An iterator that provides a view over the results + /// of looking up every possible name. + class all_lookups_iterator; + + all_lookups_iterator lookups_begin() const; + + all_lookups_iterator lookups_end() const; + + /// udir_iterator - Iterates through the using-directives stored + /// within this context. + typedef UsingDirectiveDecl * const * udir_iterator; + + typedef std::pair udir_iterator_range; + + udir_iterator_range getUsingDirectives() const; + + udir_iterator using_directives_begin() const { + return getUsingDirectives().first; + } + + udir_iterator using_directives_end() const { + return getUsingDirectives().second; + } + + // These are all defined in DependentDiagnostic.h. + class ddiag_iterator; + inline ddiag_iterator ddiag_begin() const; + inline ddiag_iterator ddiag_end() const; + + // Low-level accessors + + /// \brief Retrieve the internal representation of the lookup structure. + /// This may omit some names if we are lazily building the structure. + StoredDeclsMap *getLookupPtr() const { return LookupPtr.getPointer(); } + + /// \brief Ensure the lookup structure is fully-built and return it. + StoredDeclsMap *buildLookup(); + + /// \brief Whether this DeclContext has external storage containing + /// additional declarations that are lexically in this context. + bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; } + + /// \brief State whether this DeclContext has external storage for + /// declarations lexically in this context. + void setHasExternalLexicalStorage(bool ES = true) { + ExternalLexicalStorage = ES; + } + + /// \brief Whether this DeclContext has external storage containing + /// additional declarations that are visible in this context. + bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; } + + /// \brief State whether this DeclContext has external storage for + /// declarations visible in this context. + void setHasExternalVisibleStorage(bool ES = true) { + ExternalVisibleStorage = ES; + } + + /// \brief Determine whether the given declaration is stored in the list of + /// declarations lexically within this context. + bool isDeclInLexicalTraversal(const Decl *D) const { + return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || + D == LastDecl); + } + + static bool classof(const Decl *D); + static bool classof(const DeclContext *D) { return true; } +#define DECL(NAME, BASE) +#define DECL_CONTEXT(NAME) \ + static bool classof(const NAME##Decl *D) { return true; } +#include "clang/AST/DeclNodes.inc" + + LLVM_ATTRIBUTE_USED void dumpDeclContext() const; + +private: + void LoadLexicalDeclsFromExternalStorage() const; + + /// @brief Makes a declaration visible within this context, but + /// suppresses searches for external declarations with the same + /// name. + /// + /// Analogous to makeDeclVisibleInContext, but for the exclusive + /// use of addDeclInternal(). + void makeDeclVisibleInContextInternal(NamedDecl *D); + + friend class DependentDiagnostic; + StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const; + + void buildLookupImpl(DeclContext *DCtx); + void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, + bool Rediscoverable); + void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal); +}; + +inline bool Decl::isTemplateParameter() const { + return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm || + getKind() == TemplateTemplateParm; +} + +// Specialization selected when ToTy is not a known subclass of DeclContext. +template ::value> +struct cast_convert_decl_context { + static const ToTy *doit(const DeclContext *Val) { + return static_cast(Decl::castFromDeclContext(Val)); + } + + static ToTy *doit(DeclContext *Val) { + return static_cast(Decl::castFromDeclContext(Val)); + } +}; + +// Specialization selected when ToTy is a known subclass of DeclContext. +template +struct cast_convert_decl_context { + static const ToTy *doit(const DeclContext *Val) { + return static_cast(Val); + } + + static ToTy *doit(DeclContext *Val) { + return static_cast(Val); + } +}; + + +} // end clang. + +namespace llvm { + +/// isa(DeclContext*) +template +struct isa_impl { + static bool doit(const ::clang::DeclContext &Val) { + return To::classofKind(Val.getDeclKind()); + } +}; + +/// cast(DeclContext*) +template +struct cast_convert_val { + static const ToTy &doit(const ::clang::DeclContext &Val) { + return *::clang::cast_convert_decl_context::doit(&Val); + } +}; +template +struct cast_convert_val { + static ToTy &doit(::clang::DeclContext &Val) { + return *::clang::cast_convert_decl_context::doit(&Val); + } +}; +template +struct cast_convert_val { + static const ToTy *doit(const ::clang::DeclContext *Val) { + return ::clang::cast_convert_decl_context::doit(Val); + } +}; +template +struct cast_convert_val { + static ToTy *doit(::clang::DeclContext *Val) { + return ::clang::cast_convert_decl_context::doit(Val); + } +}; + +/// Implement cast_convert_val for Decl -> DeclContext conversions. +template +struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> { + static ::clang::DeclContext &doit(const FromTy &Val) { + return *FromTy::castToDeclContext(&Val); + } +}; + +template +struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> { + static ::clang::DeclContext *doit(const FromTy *Val) { + return FromTy::castToDeclContext(Val); + } +}; + +template +struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> { + static const ::clang::DeclContext &doit(const FromTy &Val) { + return *FromTy::castToDeclContext(&Val); + } +}; + +template +struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> { + static const ::clang::DeclContext *doit(const FromTy *Val) { + return FromTy::castToDeclContext(Val); + } +}; + +} // end namespace llvm + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/DeclCXX.h b/cpp/llvm/tools/clang/include/clang/AST/DeclCXX.h new file mode 100644 index 00000000..7f3ec4c6 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/DeclCXX.h @@ -0,0 +1,2938 @@ +//===-- DeclCXX.h - Classes for representing C++ declarations -*- C++ -*-=====// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the C++ Decl subclasses, other than those for +// templates (in DeclTemplate.h) and friends (in DeclFriend.h). +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_DECLCXX_H +#define LLVM_CLANG_AST_DECLCXX_H + +#include "clang/AST/Expr.h" +#include "clang/AST/ExprCXX.h" +#include "clang/AST/Decl.h" +#include "clang/AST/TypeLoc.h" +#include "clang/AST/UnresolvedSet.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/PointerIntPair.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/Support/Compiler.h" + +namespace clang { + +class ClassTemplateDecl; +class ClassTemplateSpecializationDecl; +class CXXBasePath; +class CXXBasePaths; +class CXXConstructorDecl; +class CXXConversionDecl; +class CXXDestructorDecl; +class CXXMethodDecl; +class CXXRecordDecl; +class CXXMemberLookupCriteria; +class CXXFinalOverriderMap; +class CXXIndirectPrimaryBaseSet; +class FriendDecl; +class LambdaExpr; + +/// \brief Represents any kind of function declaration, whether it is a +/// concrete function or a function template. +class AnyFunctionDecl { + NamedDecl *Function; + + AnyFunctionDecl(NamedDecl *ND) : Function(ND) { } + +public: + AnyFunctionDecl(FunctionDecl *FD) : Function(FD) { } + AnyFunctionDecl(FunctionTemplateDecl *FTD); + + /// \brief Implicily converts any function or function template into a + /// named declaration. + operator NamedDecl *() const { return Function; } + + /// \brief Retrieve the underlying function or function template. + NamedDecl *get() const { return Function; } + + static AnyFunctionDecl getFromNamedDecl(NamedDecl *ND) { + return AnyFunctionDecl(ND); + } +}; + +} // end namespace clang + +namespace llvm { + /// Implement simplify_type for AnyFunctionDecl, so that we can dyn_cast from + /// AnyFunctionDecl to any function or function template declaration. + template<> struct simplify_type { + typedef ::clang::NamedDecl* SimpleType; + static SimpleType getSimplifiedValue(const ::clang::AnyFunctionDecl &Val) { + return Val; + } + }; + template<> struct simplify_type< ::clang::AnyFunctionDecl> + : public simplify_type {}; + + // Provide PointerLikeTypeTraits for non-cvr pointers. + template<> + class PointerLikeTypeTraits< ::clang::AnyFunctionDecl> { + public: + static inline void *getAsVoidPointer(::clang::AnyFunctionDecl F) { + return F.get(); + } + static inline ::clang::AnyFunctionDecl getFromVoidPointer(void *P) { + return ::clang::AnyFunctionDecl::getFromNamedDecl( + static_cast< ::clang::NamedDecl*>(P)); + } + + enum { NumLowBitsAvailable = 2 }; + }; + +} // end namespace llvm + +namespace clang { + +/// AccessSpecDecl - An access specifier followed by colon ':'. +/// +/// An objects of this class represents sugar for the syntactic occurrence +/// of an access specifier followed by a colon in the list of member +/// specifiers of a C++ class definition. +/// +/// Note that they do not represent other uses of access specifiers, +/// such as those occurring in a list of base specifiers. +/// Also note that this class has nothing to do with so-called +/// "access declarations" (C++98 11.3 [class.access.dcl]). +class AccessSpecDecl : public Decl { + virtual void anchor(); + /// ColonLoc - The location of the ':'. + SourceLocation ColonLoc; + + AccessSpecDecl(AccessSpecifier AS, DeclContext *DC, + SourceLocation ASLoc, SourceLocation ColonLoc) + : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) { + setAccess(AS); + } + AccessSpecDecl(EmptyShell Empty) + : Decl(AccessSpec, Empty) { } +public: + /// getAccessSpecifierLoc - The location of the access specifier. + SourceLocation getAccessSpecifierLoc() const { return getLocation(); } + /// setAccessSpecifierLoc - Sets the location of the access specifier. + void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); } + + /// getColonLoc - The location of the colon following the access specifier. + SourceLocation getColonLoc() const { return ColonLoc; } + /// setColonLoc - Sets the location of the colon. + void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; } + + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(getAccessSpecifierLoc(), getColonLoc()); + } + + static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS, + DeclContext *DC, SourceLocation ASLoc, + SourceLocation ColonLoc) { + return new (C) AccessSpecDecl(AS, DC, ASLoc, ColonLoc); + } + static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const AccessSpecDecl *D) { return true; } + static bool classofKind(Kind K) { return K == AccessSpec; } +}; + + +/// CXXBaseSpecifier - A base class of a C++ class. +/// +/// Each CXXBaseSpecifier represents a single, direct base class (or +/// struct) of a C++ class (or struct). It specifies the type of that +/// base class, whether it is a virtual or non-virtual base, and what +/// level of access (public, protected, private) is used for the +/// derivation. For example: +/// +/// @code +/// class A { }; +/// class B { }; +/// class C : public virtual A, protected B { }; +/// @endcode +/// +/// In this code, C will have two CXXBaseSpecifiers, one for "public +/// virtual A" and the other for "protected B". +class CXXBaseSpecifier { + /// Range - The source code range that covers the full base + /// specifier, including the "virtual" (if present) and access + /// specifier (if present). + SourceRange Range; + + /// \brief The source location of the ellipsis, if this is a pack + /// expansion. + SourceLocation EllipsisLoc; + + /// Virtual - Whether this is a virtual base class or not. + bool Virtual : 1; + + /// BaseOfClass - Whether this is the base of a class (true) or of a + /// struct (false). This determines the mapping from the access + /// specifier as written in the source code to the access specifier + /// used for semantic analysis. + bool BaseOfClass : 1; + + /// Access - Access specifier as written in the source code (which + /// may be AS_none). The actual type of data stored here is an + /// AccessSpecifier, but we use "unsigned" here to work around a + /// VC++ bug. + unsigned Access : 2; + + /// InheritConstructors - Whether the class contains a using declaration + /// to inherit the named class's constructors. + bool InheritConstructors : 1; + + /// BaseTypeInfo - The type of the base class. This will be a class or struct + /// (or a typedef of such). The source code range does not include the + /// "virtual" or access specifier. + TypeSourceInfo *BaseTypeInfo; + +public: + CXXBaseSpecifier() { } + + CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A, + TypeSourceInfo *TInfo, SourceLocation EllipsisLoc) + : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC), + Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) { } + + /// getSourceRange - Retrieves the source range that contains the + /// entire base specifier. + SourceRange getSourceRange() const LLVM_READONLY { return Range; } + SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); } + SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); } + + /// isVirtual - Determines whether the base class is a virtual base + /// class (or not). + bool isVirtual() const { return Virtual; } + + /// \brief Determine whether this base class is a base of a class declared + /// with the 'class' keyword (vs. one declared with the 'struct' keyword). + bool isBaseOfClass() const { return BaseOfClass; } + + /// \brief Determine whether this base specifier is a pack expansion. + bool isPackExpansion() const { return EllipsisLoc.isValid(); } + + /// \brief Determine whether this base class's constructors get inherited. + bool getInheritConstructors() const { return InheritConstructors; } + + /// \brief Set that this base class's constructors should be inherited. + void setInheritConstructors(bool Inherit = true) { + InheritConstructors = Inherit; + } + + /// \brief For a pack expansion, determine the location of the ellipsis. + SourceLocation getEllipsisLoc() const { + return EllipsisLoc; + } + + /// getAccessSpecifier - Returns the access specifier for this base + /// specifier. This is the actual base specifier as used for + /// semantic analysis, so the result can never be AS_none. To + /// retrieve the access specifier as written in the source code, use + /// getAccessSpecifierAsWritten(). + AccessSpecifier getAccessSpecifier() const { + if ((AccessSpecifier)Access == AS_none) + return BaseOfClass? AS_private : AS_public; + else + return (AccessSpecifier)Access; + } + + /// getAccessSpecifierAsWritten - Retrieves the access specifier as + /// written in the source code (which may mean that no access + /// specifier was explicitly written). Use getAccessSpecifier() to + /// retrieve the access specifier for use in semantic analysis. + AccessSpecifier getAccessSpecifierAsWritten() const { + return (AccessSpecifier)Access; + } + + /// getType - Retrieves the type of the base class. This type will + /// always be an unqualified class type. + QualType getType() const { return BaseTypeInfo->getType(); } + + /// getTypeLoc - Retrieves the type and source location of the base class. + TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; } +}; + +/// CXXRecordDecl - Represents a C++ struct/union/class. +/// FIXME: This class will disappear once we've properly taught RecordDecl +/// to deal with C++-specific things. +class CXXRecordDecl : public RecordDecl { + + friend void TagDecl::startDefinition(); + + struct DefinitionData { + DefinitionData(CXXRecordDecl *D); + + /// UserDeclaredConstructor - True when this class has a + /// user-declared constructor. + bool UserDeclaredConstructor : 1; + + /// UserDeclaredCopyConstructor - True when this class has a + /// user-declared copy constructor. + bool UserDeclaredCopyConstructor : 1; + + /// UserDeclareMoveConstructor - True when this class has a + /// user-declared move constructor. + bool UserDeclaredMoveConstructor : 1; + + /// UserDeclaredCopyAssignment - True when this class has a + /// user-declared copy assignment operator. + bool UserDeclaredCopyAssignment : 1; + + /// UserDeclareMoveAssignment - True when this class has a + /// user-declared move assignment. + bool UserDeclaredMoveAssignment : 1; + + /// UserDeclaredDestructor - True when this class has a + /// user-declared destructor. + bool UserDeclaredDestructor : 1; + + /// Aggregate - True when this class is an aggregate. + bool Aggregate : 1; + + /// PlainOldData - True when this class is a POD-type. + bool PlainOldData : 1; + + /// Empty - true when this class is empty for traits purposes, + /// i.e. has no data members other than 0-width bit-fields, has no + /// virtual function/base, and doesn't inherit from a non-empty + /// class. Doesn't take union-ness into account. + bool Empty : 1; + + /// Polymorphic - True when this class is polymorphic, i.e. has at + /// least one virtual member or derives from a polymorphic class. + bool Polymorphic : 1; + + /// Abstract - True when this class is abstract, i.e. has at least + /// one pure virtual function, (that can come from a base class). + bool Abstract : 1; + + /// IsStandardLayout - True when this class has standard layout. + /// + /// C++0x [class]p7. A standard-layout class is a class that: + /// * has no non-static data members of type non-standard-layout class (or + /// array of such types) or reference, + /// * has no virtual functions (10.3) and no virtual base classes (10.1), + /// * has the same access control (Clause 11) for all non-static data + /// members + /// * has no non-standard-layout base classes, + /// * either has no non-static data members in the most derived class and at + /// most one base class with non-static data members, or has no base + /// classes with non-static data members, and + /// * has no base classes of the same type as the first non-static data + /// member. + bool IsStandardLayout : 1; + + /// HasNoNonEmptyBases - True when there are no non-empty base classes. + /// + /// This is a helper bit of state used to implement IsStandardLayout more + /// efficiently. + bool HasNoNonEmptyBases : 1; + + /// HasPrivateFields - True when there are private non-static data members. + bool HasPrivateFields : 1; + + /// HasProtectedFields - True when there are protected non-static data + /// members. + bool HasProtectedFields : 1; + + /// HasPublicFields - True when there are private non-static data members. + bool HasPublicFields : 1; + + /// \brief True if this class (or any subobject) has mutable fields. + bool HasMutableFields : 1; + + /// \brief True if there no non-field members declared by the user. + bool HasOnlyCMembers : 1; + + /// HasTrivialDefaultConstructor - True when, if this class has a default + /// constructor, this default constructor is trivial. + /// + /// C++0x [class.ctor]p5 + /// A default constructor is trivial if it is not user-provided and if + /// -- its class has no virtual functions and no virtual base classes, + /// and + /// -- no non-static data member of its class has a + /// brace-or-equal-initializer, and + /// -- all the direct base classes of its class have trivial + /// default constructors, and + /// -- for all the nonstatic data members of its class that are of class + /// type (or array thereof), each such class has a trivial + /// default constructor. + bool HasTrivialDefaultConstructor : 1; + + /// HasConstexprNonCopyMoveConstructor - True when this class has at least + /// one user-declared constexpr constructor which is neither the copy nor + /// move constructor. + bool HasConstexprNonCopyMoveConstructor : 1; + + /// DefaultedDefaultConstructorIsConstexpr - True if a defaulted default + /// constructor for this class would be constexpr. + bool DefaultedDefaultConstructorIsConstexpr : 1; + + /// DefaultedCopyConstructorIsConstexpr - True if a defaulted copy + /// constructor for this class would be constexpr. + bool DefaultedCopyConstructorIsConstexpr : 1; + + /// DefaultedMoveConstructorIsConstexpr - True if a defaulted move + /// constructor for this class would be constexpr. + bool DefaultedMoveConstructorIsConstexpr : 1; + + /// HasConstexprDefaultConstructor - True if this class has a constexpr + /// default constructor (either user-declared or implicitly declared). + bool HasConstexprDefaultConstructor : 1; + + /// HasConstexprCopyConstructor - True if this class has a constexpr copy + /// constructor (either user-declared or implicitly declared). + bool HasConstexprCopyConstructor : 1; + + /// HasConstexprMoveConstructor - True if this class has a constexpr move + /// constructor (either user-declared or implicitly declared). + bool HasConstexprMoveConstructor : 1; + + /// HasTrivialCopyConstructor - True when this class has a trivial copy + /// constructor. + /// + /// C++0x [class.copy]p13: + /// A copy/move constructor for class X is trivial if it is neither + /// user-provided and if + /// -- class X has no virtual functions and no virtual base classes, and + /// -- the constructor selected to copy/move each direct base class + /// subobject is trivial, and + /// -- for each non-static data member of X that is of class type (or an + /// array thereof), the constructor selected to copy/move that member + /// is trivial; + /// otherwise the copy/move constructor is non-trivial. + bool HasTrivialCopyConstructor : 1; + + /// HasTrivialMoveConstructor - True when this class has a trivial move + /// constructor. + /// + /// C++0x [class.copy]p13: + /// A copy/move constructor for class X is trivial if it is neither + /// user-provided and if + /// -- class X has no virtual functions and no virtual base classes, and + /// -- the constructor selected to copy/move each direct base class + /// subobject is trivial, and + /// -- for each non-static data member of X that is of class type (or an + /// array thereof), the constructor selected to copy/move that member + /// is trivial; + /// otherwise the copy/move constructor is non-trivial. + bool HasTrivialMoveConstructor : 1; + + /// HasTrivialCopyAssignment - True when this class has a trivial copy + /// assignment operator. + /// + /// C++0x [class.copy]p27: + /// A copy/move assignment operator for class X is trivial if it is + /// neither user-provided nor deleted and if + /// -- class X has no virtual functions and no virtual base classes, and + /// -- the assignment operator selected to copy/move each direct base + /// class subobject is trivial, and + /// -- for each non-static data member of X that is of class type (or an + /// array thereof), the assignment operator selected to copy/move + /// that member is trivial; + /// otherwise the copy/move assignment operator is non-trivial. + bool HasTrivialCopyAssignment : 1; + + /// HasTrivialMoveAssignment - True when this class has a trivial move + /// assignment operator. + /// + /// C++0x [class.copy]p27: + /// A copy/move assignment operator for class X is trivial if it is + /// neither user-provided nor deleted and if + /// -- class X has no virtual functions and no virtual base classes, and + /// -- the assignment operator selected to copy/move each direct base + /// class subobject is trivial, and + /// -- for each non-static data member of X that is of class type (or an + /// array thereof), the assignment operator selected to copy/move + /// that member is trivial; + /// otherwise the copy/move assignment operator is non-trivial. + bool HasTrivialMoveAssignment : 1; + + /// HasTrivialDestructor - True when this class has a trivial destructor. + /// + /// C++ [class.dtor]p3. A destructor is trivial if it is an + /// implicitly-declared destructor and if: + /// * all of the direct base classes of its class have trivial destructors + /// and + /// * for all of the non-static data members of its class that are of class + /// type (or array thereof), each such class has a trivial destructor. + bool HasTrivialDestructor : 1; + + /// HasIrrelevantDestructor - True when this class has a destructor with no + /// semantic effect. + bool HasIrrelevantDestructor : 1; + + /// HasNonLiteralTypeFieldsOrBases - True when this class contains at least + /// one non-static data member or base class of non-literal or volatile + /// type. + bool HasNonLiteralTypeFieldsOrBases : 1; + + /// ComputedVisibleConversions - True when visible conversion functions are + /// already computed and are available. + bool ComputedVisibleConversions : 1; + + /// \brief Whether we have a C++0x user-provided default constructor (not + /// explicitly deleted or defaulted). + bool UserProvidedDefaultConstructor : 1; + + /// \brief Whether we have already declared the default constructor. + bool DeclaredDefaultConstructor : 1; + + /// \brief Whether we have already declared the copy constructor. + bool DeclaredCopyConstructor : 1; + + /// \brief Whether we have already declared the move constructor. + bool DeclaredMoveConstructor : 1; + + /// \brief Whether we have already declared the copy-assignment operator. + bool DeclaredCopyAssignment : 1; + + /// \brief Whether we have already declared the move-assignment operator. + bool DeclaredMoveAssignment : 1; + + /// \brief Whether we have already declared a destructor within the class. + bool DeclaredDestructor : 1; + + /// \brief Whether an implicit move constructor was attempted to be declared + /// but would have been deleted. + bool FailedImplicitMoveConstructor : 1; + + /// \brief Whether an implicit move assignment operator was attempted to be + /// declared but would have been deleted. + bool FailedImplicitMoveAssignment : 1; + + /// \brief Whether this class describes a C++ lambda. + bool IsLambda : 1; + + /// NumBases - The number of base class specifiers in Bases. + unsigned NumBases; + + /// NumVBases - The number of virtual base class specifiers in VBases. + unsigned NumVBases; + + /// Bases - Base classes of this class. + /// FIXME: This is wasted space for a union. + LazyCXXBaseSpecifiersPtr Bases; + + /// VBases - direct and indirect virtual base classes of this class. + LazyCXXBaseSpecifiersPtr VBases; + + /// Conversions - Overload set containing the conversion functions + /// of this C++ class (but not its inherited conversion + /// functions). Each of the entries in this overload set is a + /// CXXConversionDecl. + UnresolvedSet<4> Conversions; + + /// VisibleConversions - Overload set containing the conversion + /// functions of this C++ class and all those inherited conversion + /// functions that are visible in this class. Each of the entries + /// in this overload set is a CXXConversionDecl or a + /// FunctionTemplateDecl. + UnresolvedSet<4> VisibleConversions; + + /// Definition - The declaration which defines this record. + CXXRecordDecl *Definition; + + /// FirstFriend - The first friend declaration in this class, or + /// null if there aren't any. This is actually currently stored + /// in reverse order. + FriendDecl *FirstFriend; + + /// \brief Retrieve the set of direct base classes. + CXXBaseSpecifier *getBases() const { + return Bases.get(Definition->getASTContext().getExternalSource()); + } + + /// \brief Retrieve the set of virtual base classes. + CXXBaseSpecifier *getVBases() const { + return VBases.get(Definition->getASTContext().getExternalSource()); + } + } *DefinitionData; + + /// \brief Describes a C++ closure type (generated by a lambda expression). + struct LambdaDefinitionData : public DefinitionData { + typedef LambdaExpr::Capture Capture; + + LambdaDefinitionData(CXXRecordDecl *D, bool Dependent) + : DefinitionData(D), Dependent(Dependent), NumCaptures(0), + NumExplicitCaptures(0), ManglingNumber(0), ContextDecl(0), Captures(0) + { + IsLambda = true; + } + + /// \brief Whether this lambda is known to be dependent, even if its + /// context isn't dependent. + /// + /// A lambda with a non-dependent context can be dependent if it occurs + /// within the default argument of a function template, because the + /// lambda will have been created with the enclosing context as its + /// declaration context, rather than function. This is an unfortunate + /// artifact of having to parse the default arguments before + unsigned Dependent : 1; + + /// \brief The number of captures in this lambda. + unsigned NumCaptures : 16; + + /// \brief The number of explicit captures in this lambda. + unsigned NumExplicitCaptures : 15; + + /// \brief The number used to indicate this lambda expression for name + /// mangling in the Itanium C++ ABI. + unsigned ManglingNumber; + + /// \brief The declaration that provides context for this lambda, if the + /// actual DeclContext does not suffice. This is used for lambdas that + /// occur within default arguments of function parameters within the class + /// or within a data member initializer. + Decl *ContextDecl; + + /// \brief The list of captures, both explicit and implicit, for this + /// lambda. + Capture *Captures; + }; + + struct DefinitionData &data() { + assert(DefinitionData && "queried property of class with no definition"); + return *DefinitionData; + } + + const struct DefinitionData &data() const { + assert(DefinitionData && "queried property of class with no definition"); + return *DefinitionData; + } + + struct LambdaDefinitionData &getLambdaData() const { + assert(DefinitionData && "queried property of lambda with no definition"); + assert(DefinitionData->IsLambda && + "queried lambda property of non-lambda class"); + return static_cast(*DefinitionData); + } + + /// \brief The template or declaration that this declaration + /// describes or was instantiated from, respectively. + /// + /// For non-templates, this value will be NULL. For record + /// declarations that describe a class template, this will be a + /// pointer to a ClassTemplateDecl. For member + /// classes of class template specializations, this will be the + /// MemberSpecializationInfo referring to the member class that was + /// instantiated or specialized. + llvm::PointerUnion + TemplateOrInstantiation; + + friend class DeclContext; + friend class LambdaExpr; + + /// \brief Notify the class that member has been added. + /// + /// This routine helps maintain information about the class based on which + /// members have been added. It will be invoked by DeclContext::addDecl() + /// whenever a member is added to this record. + void addedMember(Decl *D); + + void markedVirtualFunctionPure(); + friend void FunctionDecl::setPure(bool); + + friend class ASTNodeImporter; + +protected: + CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, CXXRecordDecl *PrevDecl); + +public: + /// base_class_iterator - Iterator that traverses the base classes + /// of a class. + typedef CXXBaseSpecifier* base_class_iterator; + + /// base_class_const_iterator - Iterator that traverses the base + /// classes of a class. + typedef const CXXBaseSpecifier* base_class_const_iterator; + + /// reverse_base_class_iterator = Iterator that traverses the base classes + /// of a class in reverse order. + typedef std::reverse_iterator + reverse_base_class_iterator; + + /// reverse_base_class_iterator = Iterator that traverses the base classes + /// of a class in reverse order. + typedef std::reverse_iterator + reverse_base_class_const_iterator; + + virtual CXXRecordDecl *getCanonicalDecl() { + return cast(RecordDecl::getCanonicalDecl()); + } + virtual const CXXRecordDecl *getCanonicalDecl() const { + return cast(RecordDecl::getCanonicalDecl()); + } + + const CXXRecordDecl *getPreviousDecl() const { + return cast_or_null(RecordDecl::getPreviousDecl()); + } + CXXRecordDecl *getPreviousDecl() { + return cast_or_null(RecordDecl::getPreviousDecl()); + } + + const CXXRecordDecl *getMostRecentDecl() const { + return cast_or_null(RecordDecl::getMostRecentDecl()); + } + CXXRecordDecl *getMostRecentDecl() { + return cast_or_null(RecordDecl::getMostRecentDecl()); + } + + CXXRecordDecl *getDefinition() const { + if (!DefinitionData) return 0; + return data().Definition; + } + + bool hasDefinition() const { return DefinitionData != 0; } + + static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, CXXRecordDecl* PrevDecl=0, + bool DelayTypeCreation = false); + static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC, + SourceLocation Loc, bool DependentLambda); + static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); + + bool isDynamicClass() const { + return data().Polymorphic || data().NumVBases != 0; + } + + /// setBases - Sets the base classes of this struct or class. + void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases); + + /// getNumBases - Retrieves the number of base classes of this + /// class. + unsigned getNumBases() const { return data().NumBases; } + + base_class_iterator bases_begin() { return data().getBases(); } + base_class_const_iterator bases_begin() const { return data().getBases(); } + base_class_iterator bases_end() { return bases_begin() + data().NumBases; } + base_class_const_iterator bases_end() const { + return bases_begin() + data().NumBases; + } + reverse_base_class_iterator bases_rbegin() { + return reverse_base_class_iterator(bases_end()); + } + reverse_base_class_const_iterator bases_rbegin() const { + return reverse_base_class_const_iterator(bases_end()); + } + reverse_base_class_iterator bases_rend() { + return reverse_base_class_iterator(bases_begin()); + } + reverse_base_class_const_iterator bases_rend() const { + return reverse_base_class_const_iterator(bases_begin()); + } + + /// getNumVBases - Retrieves the number of virtual base classes of this + /// class. + unsigned getNumVBases() const { return data().NumVBases; } + + base_class_iterator vbases_begin() { return data().getVBases(); } + base_class_const_iterator vbases_begin() const { return data().getVBases(); } + base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; } + base_class_const_iterator vbases_end() const { + return vbases_begin() + data().NumVBases; + } + reverse_base_class_iterator vbases_rbegin() { + return reverse_base_class_iterator(vbases_end()); + } + reverse_base_class_const_iterator vbases_rbegin() const { + return reverse_base_class_const_iterator(vbases_end()); + } + reverse_base_class_iterator vbases_rend() { + return reverse_base_class_iterator(vbases_begin()); + } + reverse_base_class_const_iterator vbases_rend() const { + return reverse_base_class_const_iterator(vbases_begin()); + } + + /// \brief Determine whether this class has any dependent base classes. + bool hasAnyDependentBases() const; + + /// Iterator access to method members. The method iterator visits + /// all method members of the class, including non-instance methods, + /// special methods, etc. + typedef specific_decl_iterator method_iterator; + + /// method_begin - Method begin iterator. Iterates in the order the methods + /// were declared. + method_iterator method_begin() const { + return method_iterator(decls_begin()); + } + /// method_end - Method end iterator. + method_iterator method_end() const { + return method_iterator(decls_end()); + } + + /// Iterator access to constructor members. + typedef specific_decl_iterator ctor_iterator; + + ctor_iterator ctor_begin() const { + return ctor_iterator(decls_begin()); + } + ctor_iterator ctor_end() const { + return ctor_iterator(decls_end()); + } + + /// An iterator over friend declarations. All of these are defined + /// in DeclFriend.h. + class friend_iterator; + friend_iterator friend_begin() const; + friend_iterator friend_end() const; + void pushFriendDecl(FriendDecl *FD); + + /// Determines whether this record has any friends. + bool hasFriends() const { + return data().FirstFriend != 0; + } + + /// \brief Determine if we need to declare a default constructor for + /// this class. + /// + /// This value is used for lazy creation of default constructors. + bool needsImplicitDefaultConstructor() const { + return !data().UserDeclaredConstructor && + !data().DeclaredDefaultConstructor; + } + + /// hasDeclaredDefaultConstructor - Whether this class's default constructor + /// has been declared (either explicitly or implicitly). + bool hasDeclaredDefaultConstructor() const { + return data().DeclaredDefaultConstructor; + } + + /// hasConstCopyConstructor - Determines whether this class has a + /// copy constructor that accepts a const-qualified argument. + bool hasConstCopyConstructor() const; + + /// getCopyConstructor - Returns the copy constructor for this class + CXXConstructorDecl *getCopyConstructor(unsigned TypeQuals) const; + + /// getMoveConstructor - Returns the move constructor for this class + CXXConstructorDecl *getMoveConstructor() const; + + /// \brief Retrieve the copy-assignment operator for this class, if available. + /// + /// This routine attempts to find the copy-assignment operator for this + /// class, using a simplistic form of overload resolution. + /// + /// \param ArgIsConst Whether the argument to the copy-assignment operator + /// is const-qualified. + /// + /// \returns The copy-assignment operator that can be invoked, or NULL if + /// a unique copy-assignment operator could not be found. + CXXMethodDecl *getCopyAssignmentOperator(bool ArgIsConst) const; + + /// getMoveAssignmentOperator - Returns the move assignment operator for this + /// class + CXXMethodDecl *getMoveAssignmentOperator() const; + + /// hasUserDeclaredConstructor - Whether this class has any + /// user-declared constructors. When true, a default constructor + /// will not be implicitly declared. + bool hasUserDeclaredConstructor() const { + return data().UserDeclaredConstructor; + } + + /// hasUserProvidedDefaultconstructor - Whether this class has a + /// user-provided default constructor per C++0x. + bool hasUserProvidedDefaultConstructor() const { + return data().UserProvidedDefaultConstructor; + } + + /// hasUserDeclaredCopyConstructor - Whether this class has a + /// user-declared copy constructor. When false, a copy constructor + /// will be implicitly declared. + bool hasUserDeclaredCopyConstructor() const { + return data().UserDeclaredCopyConstructor; + } + + /// \brief Determine whether this class has had its copy constructor + /// declared, either via the user or via an implicit declaration. + /// + /// This value is used for lazy creation of copy constructors. + bool hasDeclaredCopyConstructor() const { + return data().DeclaredCopyConstructor; + } + + /// hasUserDeclaredMoveOperation - Whether this class has a user- + /// declared move constructor or assignment operator. When false, a + /// move constructor and assignment operator may be implicitly declared. + bool hasUserDeclaredMoveOperation() const { + return data().UserDeclaredMoveConstructor || + data().UserDeclaredMoveAssignment; + } + + /// \brief Determine whether this class has had a move constructor + /// declared by the user. + bool hasUserDeclaredMoveConstructor() const { + return data().UserDeclaredMoveConstructor; + } + + /// \brief Determine whether this class has had a move constructor + /// declared. + bool hasDeclaredMoveConstructor() const { + return data().DeclaredMoveConstructor; + } + + /// \brief Determine whether implicit move constructor generation for this + /// class has failed before. + bool hasFailedImplicitMoveConstructor() const { + return data().FailedImplicitMoveConstructor; + } + + /// \brief Set whether implicit move constructor generation for this class + /// has failed before. + void setFailedImplicitMoveConstructor(bool Failed = true) { + data().FailedImplicitMoveConstructor = Failed; + } + + /// \brief Determine whether this class should get an implicit move + /// constructor or if any existing special member function inhibits this. + /// + /// Covers all bullets of C++0x [class.copy]p9 except the last, that the + /// constructor wouldn't be deleted, which is only looked up from a cached + /// result. + bool needsImplicitMoveConstructor() const { + return !hasFailedImplicitMoveConstructor() && + !hasDeclaredMoveConstructor() && + !hasUserDeclaredCopyConstructor() && + !hasUserDeclaredCopyAssignment() && + !hasUserDeclaredMoveAssignment() && + !hasUserDeclaredDestructor(); + } + + /// hasUserDeclaredCopyAssignment - Whether this class has a + /// user-declared copy assignment operator. When false, a copy + /// assigment operator will be implicitly declared. + bool hasUserDeclaredCopyAssignment() const { + return data().UserDeclaredCopyAssignment; + } + + /// \brief Determine whether this class has had its copy assignment operator + /// declared, either via the user or via an implicit declaration. + /// + /// This value is used for lazy creation of copy assignment operators. + bool hasDeclaredCopyAssignment() const { + return data().DeclaredCopyAssignment; + } + + /// \brief Determine whether this class has had a move assignment + /// declared by the user. + bool hasUserDeclaredMoveAssignment() const { + return data().UserDeclaredMoveAssignment; + } + + /// hasDeclaredMoveAssignment - Whether this class has a + /// declared move assignment operator. + bool hasDeclaredMoveAssignment() const { + return data().DeclaredMoveAssignment; + } + + /// \brief Determine whether implicit move assignment generation for this + /// class has failed before. + bool hasFailedImplicitMoveAssignment() const { + return data().FailedImplicitMoveAssignment; + } + + /// \brief Set whether implicit move assignment generation for this class + /// has failed before. + void setFailedImplicitMoveAssignment(bool Failed = true) { + data().FailedImplicitMoveAssignment = Failed; + } + + /// \brief Determine whether this class should get an implicit move + /// assignment operator or if any existing special member function inhibits + /// this. + /// + /// Covers all bullets of C++0x [class.copy]p20 except the last, that the + /// constructor wouldn't be deleted. + bool needsImplicitMoveAssignment() const { + return !hasFailedImplicitMoveAssignment() && + !hasDeclaredMoveAssignment() && + !hasUserDeclaredCopyConstructor() && + !hasUserDeclaredCopyAssignment() && + !hasUserDeclaredMoveConstructor() && + !hasUserDeclaredDestructor(); + } + + /// hasUserDeclaredDestructor - Whether this class has a + /// user-declared destructor. When false, a destructor will be + /// implicitly declared. + bool hasUserDeclaredDestructor() const { + return data().UserDeclaredDestructor; + } + + /// \brief Determine whether this class has had its destructor declared, + /// either via the user or via an implicit declaration. + /// + /// This value is used for lazy creation of destructors. + bool hasDeclaredDestructor() const { return data().DeclaredDestructor; } + + /// \brief Determine whether this class describes a lambda function object. + bool isLambda() const { return hasDefinition() && data().IsLambda; } + + /// \brief For a closure type, retrieve the mapping from captured + /// variables and this to the non-static data members that store the + /// values or references of the captures. + /// + /// \param Captures Will be populated with the mapping from captured + /// variables to the corresponding fields. + /// + /// \param ThisCapture Will be set to the field declaration for the + /// 'this' capture. + void getCaptureFields(llvm::DenseMap &Captures, + FieldDecl *&ThisCapture) const; + + typedef const LambdaExpr::Capture* capture_const_iterator; + capture_const_iterator captures_begin() const { + return isLambda() ? getLambdaData().Captures : NULL; + } + capture_const_iterator captures_end() const { + return isLambda() ? captures_begin() + getLambdaData().NumCaptures : NULL; + } + + /// getConversions - Retrieve the overload set containing all of the + /// conversion functions in this class. + UnresolvedSetImpl *getConversionFunctions() { + return &data().Conversions; + } + const UnresolvedSetImpl *getConversionFunctions() const { + return &data().Conversions; + } + + typedef UnresolvedSetImpl::iterator conversion_iterator; + conversion_iterator conversion_begin() const { + return getConversionFunctions()->begin(); + } + conversion_iterator conversion_end() const { + return getConversionFunctions()->end(); + } + + /// Removes a conversion function from this class. The conversion + /// function must currently be a member of this class. Furthermore, + /// this class must currently be in the process of being defined. + void removeConversion(const NamedDecl *Old); + + /// getVisibleConversionFunctions - get all conversion functions visible + /// in current class; including conversion function templates. + const UnresolvedSetImpl *getVisibleConversionFunctions(); + + /// isAggregate - Whether this class is an aggregate (C++ + /// [dcl.init.aggr]), which is a class with no user-declared + /// constructors, no private or protected non-static data members, + /// no base classes, and no virtual functions (C++ [dcl.init.aggr]p1). + bool isAggregate() const { return data().Aggregate; } + + /// isPOD - Whether this class is a POD-type (C++ [class]p4), which is a class + /// that is an aggregate that has no non-static non-POD data members, no + /// reference data members, no user-defined copy assignment operator and no + /// user-defined destructor. + bool isPOD() const { return data().PlainOldData; } + + /// \brief True if this class is C-like, without C++-specific features, e.g. + /// it contains only public fields, no bases, tag kind is not 'class', etc. + bool isCLike() const; + + /// isEmpty - Whether this class is empty (C++0x [meta.unary.prop]), which + /// means it has a virtual function, virtual base, data member (other than + /// 0-width bit-field) or inherits from a non-empty class. Does NOT include + /// a check for union-ness. + bool isEmpty() const { return data().Empty; } + + /// isPolymorphic - Whether this class is polymorphic (C++ [class.virtual]), + /// which means that the class contains or inherits a virtual function. + bool isPolymorphic() const { return data().Polymorphic; } + + /// isAbstract - Whether this class is abstract (C++ [class.abstract]), + /// which means that the class contains or inherits a pure virtual function. + bool isAbstract() const { return data().Abstract; } + + /// isStandardLayout - Whether this class has standard layout + /// (C++ [class]p7) + bool isStandardLayout() const { return data().IsStandardLayout; } + + /// \brief Whether this class, or any of its class subobjects, contains a + /// mutable field. + bool hasMutableFields() const { return data().HasMutableFields; } + + /// hasTrivialDefaultConstructor - Whether this class has a trivial default + /// constructor (C++11 [class.ctor]p5). + bool hasTrivialDefaultConstructor() const { + return data().HasTrivialDefaultConstructor && + (!data().UserDeclaredConstructor || + data().DeclaredDefaultConstructor); + } + + /// hasConstexprNonCopyMoveConstructor - Whether this class has at least one + /// constexpr constructor other than the copy or move constructors. + bool hasConstexprNonCopyMoveConstructor() const { + return data().HasConstexprNonCopyMoveConstructor || + (!hasUserDeclaredConstructor() && + defaultedDefaultConstructorIsConstexpr()); + } + + /// defaultedDefaultConstructorIsConstexpr - Whether a defaulted default + /// constructor for this class would be constexpr. + bool defaultedDefaultConstructorIsConstexpr() const { + return data().DefaultedDefaultConstructorIsConstexpr; + } + + /// defaultedCopyConstructorIsConstexpr - Whether a defaulted copy + /// constructor for this class would be constexpr. + bool defaultedCopyConstructorIsConstexpr() const { + return data().DefaultedCopyConstructorIsConstexpr; + } + + /// defaultedMoveConstructorIsConstexpr - Whether a defaulted move + /// constructor for this class would be constexpr. + bool defaultedMoveConstructorIsConstexpr() const { + return data().DefaultedMoveConstructorIsConstexpr; + } + + /// hasConstexprDefaultConstructor - Whether this class has a constexpr + /// default constructor. + bool hasConstexprDefaultConstructor() const { + return data().HasConstexprDefaultConstructor || + (!data().UserDeclaredConstructor && + data().DefaultedDefaultConstructorIsConstexpr && isLiteral()); + } + + /// hasConstexprCopyConstructor - Whether this class has a constexpr copy + /// constructor. + bool hasConstexprCopyConstructor() const { + return data().HasConstexprCopyConstructor || + (!data().DeclaredCopyConstructor && + data().DefaultedCopyConstructorIsConstexpr && isLiteral()); + } + + /// hasConstexprMoveConstructor - Whether this class has a constexpr move + /// constructor. + bool hasConstexprMoveConstructor() const { + return data().HasConstexprMoveConstructor || + (needsImplicitMoveConstructor() && + data().DefaultedMoveConstructorIsConstexpr && isLiteral()); + } + + // hasTrivialCopyConstructor - Whether this class has a trivial copy + // constructor (C++ [class.copy]p6, C++0x [class.copy]p13) + bool hasTrivialCopyConstructor() const { + return data().HasTrivialCopyConstructor; + } + + // hasTrivialMoveConstructor - Whether this class has a trivial move + // constructor (C++0x [class.copy]p13) + bool hasTrivialMoveConstructor() const { + return data().HasTrivialMoveConstructor; + } + + // hasTrivialCopyAssignment - Whether this class has a trivial copy + // assignment operator (C++ [class.copy]p11, C++0x [class.copy]p27) + bool hasTrivialCopyAssignment() const { + return data().HasTrivialCopyAssignment; + } + + // hasTrivialMoveAssignment - Whether this class has a trivial move + // assignment operator (C++0x [class.copy]p27) + bool hasTrivialMoveAssignment() const { + return data().HasTrivialMoveAssignment; + } + + // hasTrivialDestructor - Whether this class has a trivial destructor + // (C++ [class.dtor]p3) + bool hasTrivialDestructor() const { return data().HasTrivialDestructor; } + + // hasIrrelevantDestructor - Whether this class has a destructor which has no + // semantic effect. Any such destructor will be trivial, public, defaulted + // and not deleted, and will call only irrelevant destructors. + bool hasIrrelevantDestructor() const { + return data().HasIrrelevantDestructor; + } + + // hasNonLiteralTypeFieldsOrBases - Whether this class has a non-literal or + // volatile type non-static data member or base class. + bool hasNonLiteralTypeFieldsOrBases() const { + return data().HasNonLiteralTypeFieldsOrBases; + } + + // isTriviallyCopyable - Whether this class is considered trivially copyable + // (C++0x [class]p6). + bool isTriviallyCopyable() const; + + // isTrivial - Whether this class is considered trivial + // + // C++0x [class]p6 + // A trivial class is a class that has a trivial default constructor and + // is trivially copiable. + bool isTrivial() const { + return isTriviallyCopyable() && hasTrivialDefaultConstructor(); + } + + // isLiteral - Whether this class is a literal type. + // + // C++11 [basic.types]p10 + // A class type that has all the following properties: + // -- it has a trivial destructor + // -- every constructor call and full-expression in the + // brace-or-equal-intializers for non-static data members (if any) is + // a constant expression. + // -- it is an aggregate type or has at least one constexpr constructor or + // constructor template that is not a copy or move constructor, and + // -- all of its non-static data members and base classes are of literal + // types + // + // We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by + // treating types with trivial default constructors as literal types. + bool isLiteral() const { + return hasTrivialDestructor() && + (isAggregate() || hasConstexprNonCopyMoveConstructor() || + hasTrivialDefaultConstructor()) && + !hasNonLiteralTypeFieldsOrBases(); + } + + /// \brief If this record is an instantiation of a member class, + /// retrieves the member class from which it was instantiated. + /// + /// This routine will return non-NULL for (non-templated) member + /// classes of class templates. For example, given: + /// + /// \code + /// template + /// struct X { + /// struct A { }; + /// }; + /// \endcode + /// + /// The declaration for X::A is a (non-templated) CXXRecordDecl + /// whose parent is the class template specialization X. For + /// this declaration, getInstantiatedFromMemberClass() will return + /// the CXXRecordDecl X::A. When a complete definition of + /// X::A is required, it will be instantiated from the + /// declaration returned by getInstantiatedFromMemberClass(). + CXXRecordDecl *getInstantiatedFromMemberClass() const; + + /// \brief If this class is an instantiation of a member class of a + /// class template specialization, retrieves the member specialization + /// information. + MemberSpecializationInfo *getMemberSpecializationInfo() const; + + /// \brief Specify that this record is an instantiation of the + /// member class RD. + void setInstantiationOfMemberClass(CXXRecordDecl *RD, + TemplateSpecializationKind TSK); + + /// \brief Retrieves the class template that is described by this + /// class declaration. + /// + /// Every class template is represented as a ClassTemplateDecl and a + /// CXXRecordDecl. The former contains template properties (such as + /// the template parameter lists) while the latter contains the + /// actual description of the template's + /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the + /// CXXRecordDecl that from a ClassTemplateDecl, while + /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from + /// a CXXRecordDecl. + ClassTemplateDecl *getDescribedClassTemplate() const { + return TemplateOrInstantiation.dyn_cast(); + } + + void setDescribedClassTemplate(ClassTemplateDecl *Template) { + TemplateOrInstantiation = Template; + } + + /// \brief Determine whether this particular class is a specialization or + /// instantiation of a class template or member class of a class template, + /// and how it was instantiated or specialized. + TemplateSpecializationKind getTemplateSpecializationKind() const; + + /// \brief Set the kind of specialization or template instantiation this is. + void setTemplateSpecializationKind(TemplateSpecializationKind TSK); + + /// getDestructor - Returns the destructor decl for this class. + CXXDestructorDecl *getDestructor() const; + + /// isLocalClass - If the class is a local class [class.local], returns + /// the enclosing function declaration. + const FunctionDecl *isLocalClass() const { + if (const CXXRecordDecl *RD = dyn_cast(getDeclContext())) + return RD->isLocalClass(); + + return dyn_cast(getDeclContext()); + } + + /// \brief Determine whether this class is derived from the class \p Base. + /// + /// This routine only determines whether this class is derived from \p Base, + /// but does not account for factors that may make a Derived -> Base class + /// ill-formed, such as private/protected inheritance or multiple, ambiguous + /// base class subobjects. + /// + /// \param Base the base class we are searching for. + /// + /// \returns true if this class is derived from Base, false otherwise. + bool isDerivedFrom(const CXXRecordDecl *Base) const; + + /// \brief Determine whether this class is derived from the type \p Base. + /// + /// This routine only determines whether this class is derived from \p Base, + /// but does not account for factors that may make a Derived -> Base class + /// ill-formed, such as private/protected inheritance or multiple, ambiguous + /// base class subobjects. + /// + /// \param Base the base class we are searching for. + /// + /// \param Paths will contain the paths taken from the current class to the + /// given \p Base class. + /// + /// \returns true if this class is derived from Base, false otherwise. + /// + /// \todo add a separate paramaeter to configure IsDerivedFrom, rather than + /// tangling input and output in \p Paths + bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const; + + /// \brief Determine whether this class is virtually derived from + /// the class \p Base. + /// + /// This routine only determines whether this class is virtually + /// derived from \p Base, but does not account for factors that may + /// make a Derived -> Base class ill-formed, such as + /// private/protected inheritance or multiple, ambiguous base class + /// subobjects. + /// + /// \param Base the base class we are searching for. + /// + /// \returns true if this class is virtually derived from Base, + /// false otherwise. + bool isVirtuallyDerivedFrom(CXXRecordDecl *Base) const; + + /// \brief Determine whether this class is provably not derived from + /// the type \p Base. + bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const; + + /// \brief Function type used by forallBases() as a callback. + /// + /// \param Base the definition of the base class + /// + /// \returns true if this base matched the search criteria + typedef bool ForallBasesCallback(const CXXRecordDecl *BaseDefinition, + void *UserData); + + /// \brief Determines if the given callback holds for all the direct + /// or indirect base classes of this type. + /// + /// The class itself does not count as a base class. This routine + /// returns false if the class has non-computable base classes. + /// + /// \param AllowShortCircuit if false, forces the callback to be called + /// for every base class, even if a dependent or non-matching base was + /// found. + bool forallBases(ForallBasesCallback *BaseMatches, void *UserData, + bool AllowShortCircuit = true) const; + + /// \brief Function type used by lookupInBases() to determine whether a + /// specific base class subobject matches the lookup criteria. + /// + /// \param Specifier the base-class specifier that describes the inheritance + /// from the base class we are trying to match. + /// + /// \param Path the current path, from the most-derived class down to the + /// base named by the \p Specifier. + /// + /// \param UserData a single pointer to user-specified data, provided to + /// lookupInBases(). + /// + /// \returns true if this base matched the search criteria, false otherwise. + typedef bool BaseMatchesCallback(const CXXBaseSpecifier *Specifier, + CXXBasePath &Path, + void *UserData); + + /// \brief Look for entities within the base classes of this C++ class, + /// transitively searching all base class subobjects. + /// + /// This routine uses the callback function \p BaseMatches to find base + /// classes meeting some search criteria, walking all base class subobjects + /// and populating the given \p Paths structure with the paths through the + /// inheritance hierarchy that resulted in a match. On a successful search, + /// the \p Paths structure can be queried to retrieve the matching paths and + /// to determine if there were any ambiguities. + /// + /// \param BaseMatches callback function used to determine whether a given + /// base matches the user-defined search criteria. + /// + /// \param UserData user data pointer that will be provided to \p BaseMatches. + /// + /// \param Paths used to record the paths from this class to its base class + /// subobjects that match the search criteria. + /// + /// \returns true if there exists any path from this class to a base class + /// subobject that matches the search criteria. + bool lookupInBases(BaseMatchesCallback *BaseMatches, void *UserData, + CXXBasePaths &Paths) const; + + /// \brief Base-class lookup callback that determines whether the given + /// base class specifier refers to a specific class declaration. + /// + /// This callback can be used with \c lookupInBases() to determine whether + /// a given derived class has is a base class subobject of a particular type. + /// The user data pointer should refer to the canonical CXXRecordDecl of the + /// base class that we are searching for. + static bool FindBaseClass(const CXXBaseSpecifier *Specifier, + CXXBasePath &Path, void *BaseRecord); + + /// \brief Base-class lookup callback that determines whether the + /// given base class specifier refers to a specific class + /// declaration and describes virtual derivation. + /// + /// This callback can be used with \c lookupInBases() to determine + /// whether a given derived class has is a virtual base class + /// subobject of a particular type. The user data pointer should + /// refer to the canonical CXXRecordDecl of the base class that we + /// are searching for. + static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, + CXXBasePath &Path, void *BaseRecord); + + /// \brief Base-class lookup callback that determines whether there exists + /// a tag with the given name. + /// + /// This callback can be used with \c lookupInBases() to find tag members + /// of the given name within a C++ class hierarchy. The user data pointer + /// is an opaque \c DeclarationName pointer. + static bool FindTagMember(const CXXBaseSpecifier *Specifier, + CXXBasePath &Path, void *Name); + + /// \brief Base-class lookup callback that determines whether there exists + /// a member with the given name. + /// + /// This callback can be used with \c lookupInBases() to find members + /// of the given name within a C++ class hierarchy. The user data pointer + /// is an opaque \c DeclarationName pointer. + static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier, + CXXBasePath &Path, void *Name); + + /// \brief Base-class lookup callback that determines whether there exists + /// a member with the given name that can be used in a nested-name-specifier. + /// + /// This callback can be used with \c lookupInBases() to find membes of + /// the given name within a C++ class hierarchy that can occur within + /// nested-name-specifiers. + static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, + CXXBasePath &Path, + void *UserData); + + /// \brief Retrieve the final overriders for each virtual member + /// function in the class hierarchy where this class is the + /// most-derived class in the class hierarchy. + void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const; + + /// \brief Get the indirect primary bases for this class. + void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const; + + /// viewInheritance - Renders and displays an inheritance diagram + /// for this C++ class and all of its base classes (transitively) using + /// GraphViz. + void viewInheritance(ASTContext& Context) const; + + /// MergeAccess - Calculates the access of a decl that is reached + /// along a path. + static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, + AccessSpecifier DeclAccess) { + assert(DeclAccess != AS_none); + if (DeclAccess == AS_private) return AS_none; + return (PathAccess > DeclAccess ? PathAccess : DeclAccess); + } + + /// \brief Indicates that the definition of this class is now complete. + virtual void completeDefinition(); + + /// \brief Indicates that the definition of this class is now complete, + /// and provides a final overrider map to help determine + /// + /// \param FinalOverriders The final overrider map for this class, which can + /// be provided as an optimization for abstract-class checking. If NULL, + /// final overriders will be computed if they are needed to complete the + /// definition. + void completeDefinition(CXXFinalOverriderMap *FinalOverriders); + + /// \brief Determine whether this class may end up being abstract, even though + /// it is not yet known to be abstract. + /// + /// \returns true if this class is not known to be abstract but has any + /// base classes that are abstract. In this case, \c completeDefinition() + /// will need to compute final overriders to determine whether the class is + /// actually abstract. + bool mayBeAbstract() const; + + /// \brief If this is the closure type of a lambda expression, retrieve the + /// number to be used for name mangling in the Itanium C++ ABI. + /// + /// Zero indicates that this closure type has internal linkage, so the + /// mangling number does not matter, while a non-zero value indicates which + /// lambda expression this is in this particular context. + unsigned getLambdaManglingNumber() const { + assert(isLambda() && "Not a lambda closure type!"); + return getLambdaData().ManglingNumber; + } + + /// \brief Retrieve the declaration that provides additional context for a + /// lambda, when the normal declaration context is not specific enough. + /// + /// Certain contexts (default arguments of in-class function parameters and + /// the initializers of data members) have separate name mangling rules for + /// lambdas within the Itanium C++ ABI. For these cases, this routine provides + /// the declaration in which the lambda occurs, e.g., the function parameter + /// or the non-static data member. Otherwise, it returns NULL to imply that + /// the declaration context suffices. + Decl *getLambdaContextDecl() const { + assert(isLambda() && "Not a lambda closure type!"); + return getLambdaData().ContextDecl; + } + + /// \brief Set the mangling number and context declaration for a lambda + /// class. + void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) { + getLambdaData().ManglingNumber = ManglingNumber; + getLambdaData().ContextDecl = ContextDecl; + } + + /// \brief Determine whether this lambda expression was known to be dependent + /// at the time it was created, even if its context does not appear to be + /// dependent. + /// + /// This flag is a workaround for an issue with parsing, where default + /// arguments are parsed before their enclosing function declarations have + /// been created. This means that any lambda expressions within those + /// default arguments will have as their DeclContext the context enclosing + /// the function declaration, which may be non-dependent even when the + /// function declaration itself is dependent. This flag indicates when we + /// know that the lambda is dependent despite that. + bool isDependentLambda() const { + return isLambda() && getLambdaData().Dependent; + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classofKind(Kind K) { + return K >= firstCXXRecord && K <= lastCXXRecord; + } + static bool classof(const CXXRecordDecl *D) { return true; } + static bool classof(const ClassTemplateSpecializationDecl *D) { + return true; + } + + friend class ASTDeclReader; + friend class ASTDeclWriter; + friend class ASTReader; + friend class ASTWriter; +}; + +/// CXXMethodDecl - Represents a static or instance method of a +/// struct/union/class. +class CXXMethodDecl : public FunctionDecl { + virtual void anchor(); +protected: + CXXMethodDecl(Kind DK, CXXRecordDecl *RD, SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + bool isStatic, StorageClass SCAsWritten, bool isInline, + bool isConstexpr, SourceLocation EndLocation) + : FunctionDecl(DK, RD, StartLoc, NameInfo, T, TInfo, + (isStatic ? SC_Static : SC_None), + SCAsWritten, isInline, isConstexpr) { + if (EndLocation.isValid()) + setRangeEnd(EndLocation); + } + +public: + static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD, + SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + bool isStatic, + StorageClass SCAsWritten, + bool isInline, + bool isConstexpr, + SourceLocation EndLocation); + + static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + bool isStatic() const { return getStorageClass() == SC_Static; } + bool isInstance() const { return !isStatic(); } + + bool isVirtual() const { + CXXMethodDecl *CD = + cast(const_cast(this)->getCanonicalDecl()); + + if (CD->isVirtualAsWritten()) + return true; + + return (CD->begin_overridden_methods() != CD->end_overridden_methods()); + } + + /// \brief Determine whether this is a usual deallocation function + /// (C++ [basic.stc.dynamic.deallocation]p2), which is an overloaded + /// delete or delete[] operator with a particular signature. + bool isUsualDeallocationFunction() const; + + /// \brief Determine whether this is a copy-assignment operator, regardless + /// of whether it was declared implicitly or explicitly. + bool isCopyAssignmentOperator() const; + + /// \brief Determine whether this is a move assignment operator. + bool isMoveAssignmentOperator() const; + + const CXXMethodDecl *getCanonicalDecl() const { + return cast(FunctionDecl::getCanonicalDecl()); + } + CXXMethodDecl *getCanonicalDecl() { + return cast(FunctionDecl::getCanonicalDecl()); + } + + /// isUserProvided - True if it is either an implicit constructor or + /// if it was defaulted or deleted on first declaration. + bool isUserProvided() const { + return !(isDeleted() || getCanonicalDecl()->isDefaulted()); + } + + /// + void addOverriddenMethod(const CXXMethodDecl *MD); + + typedef const CXXMethodDecl *const* method_iterator; + + method_iterator begin_overridden_methods() const; + method_iterator end_overridden_methods() const; + unsigned size_overridden_methods() const; + + /// getParent - Returns the parent of this method declaration, which + /// is the class in which this method is defined. + const CXXRecordDecl *getParent() const { + return cast(FunctionDecl::getParent()); + } + + /// getParent - Returns the parent of this method declaration, which + /// is the class in which this method is defined. + CXXRecordDecl *getParent() { + return const_cast( + cast(FunctionDecl::getParent())); + } + + /// getThisType - Returns the type of 'this' pointer. + /// Should only be called for instance methods. + QualType getThisType(ASTContext &C) const; + + unsigned getTypeQualifiers() const { + return getType()->getAs()->getTypeQuals(); + } + + /// \brief Retrieve the ref-qualifier associated with this method. + /// + /// In the following example, \c f() has an lvalue ref-qualifier, \c g() + /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier. + /// \code + /// struct X { + /// void f() &; + /// void g() &&; + /// void h(); + /// }; + /// \endcode + RefQualifierKind getRefQualifier() const { + return getType()->getAs()->getRefQualifier(); + } + + bool hasInlineBody() const; + + /// \brief Determine whether this is a lambda closure type's static member + /// function that is used for the result of the lambda's conversion to + /// function pointer (for a lambda with no captures). + /// + /// The function itself, if used, will have a placeholder body that will be + /// supplied by IR generation to either forward to the function call operator + /// or clone the function call operator. + bool isLambdaStaticInvoker() const; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const CXXMethodDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstCXXMethod && K <= lastCXXMethod; + } +}; + +/// CXXCtorInitializer - Represents a C++ base or member +/// initializer, which is part of a constructor initializer that +/// initializes one non-static member variable or one base class. For +/// example, in the following, both 'A(a)' and 'f(3.14159)' are member +/// initializers: +/// +/// @code +/// class A { }; +/// class B : public A { +/// float f; +/// public: +/// B(A& a) : A(a), f(3.14159) { } +/// }; +/// @endcode +class CXXCtorInitializer { + /// \brief Either the base class name/delegating constructor type (stored as + /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field + /// (IndirectFieldDecl*) being initialized. + llvm::PointerUnion3 + Initializee; + + /// \brief The source location for the field name or, for a base initializer + /// pack expansion, the location of the ellipsis. In the case of a delegating + /// constructor, it will still include the type's source location as the + /// Initializee points to the CXXConstructorDecl (to allow loop detection). + SourceLocation MemberOrEllipsisLocation; + + /// \brief The argument used to initialize the base or member, which may + /// end up constructing an object (when multiple arguments are involved). + /// If 0, this is a field initializer, and the in-class member initializer + /// will be used. + Stmt *Init; + + /// LParenLoc - Location of the left paren of the ctor-initializer. + SourceLocation LParenLoc; + + /// RParenLoc - Location of the right paren of the ctor-initializer. + SourceLocation RParenLoc; + + /// \brief If the initializee is a type, whether that type makes this + /// a delegating initialization. + bool IsDelegating : 1; + + /// IsVirtual - If the initializer is a base initializer, this keeps track + /// of whether the base is virtual or not. + bool IsVirtual : 1; + + /// IsWritten - Whether or not the initializer is explicitly written + /// in the sources. + bool IsWritten : 1; + + /// SourceOrderOrNumArrayIndices - If IsWritten is true, then this + /// number keeps track of the textual order of this initializer in the + /// original sources, counting from 0; otherwise, if IsWritten is false, + /// it stores the number of array index variables stored after this + /// object in memory. + unsigned SourceOrderOrNumArrayIndices : 13; + + CXXCtorInitializer(ASTContext &Context, FieldDecl *Member, + SourceLocation MemberLoc, SourceLocation L, Expr *Init, + SourceLocation R, VarDecl **Indices, unsigned NumIndices); + +public: + /// CXXCtorInitializer - Creates a new base-class initializer. + explicit + CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual, + SourceLocation L, Expr *Init, SourceLocation R, + SourceLocation EllipsisLoc); + + /// CXXCtorInitializer - Creates a new member initializer. + explicit + CXXCtorInitializer(ASTContext &Context, FieldDecl *Member, + SourceLocation MemberLoc, SourceLocation L, Expr *Init, + SourceLocation R); + + /// CXXCtorInitializer - Creates a new anonymous field initializer. + explicit + CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member, + SourceLocation MemberLoc, SourceLocation L, Expr *Init, + SourceLocation R); + + /// CXXCtorInitializer - Creates a new delegating Initializer. + explicit + CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, + SourceLocation L, Expr *Init, SourceLocation R); + + /// \brief Creates a new member initializer that optionally contains + /// array indices used to describe an elementwise initialization. + static CXXCtorInitializer *Create(ASTContext &Context, FieldDecl *Member, + SourceLocation MemberLoc, SourceLocation L, + Expr *Init, SourceLocation R, + VarDecl **Indices, unsigned NumIndices); + + /// isBaseInitializer - Returns true when this initializer is + /// initializing a base class. + bool isBaseInitializer() const { + return Initializee.is() && !IsDelegating; + } + + /// isMemberInitializer - Returns true when this initializer is + /// initializing a non-static data member. + bool isMemberInitializer() const { return Initializee.is(); } + + bool isAnyMemberInitializer() const { + return isMemberInitializer() || isIndirectMemberInitializer(); + } + + bool isIndirectMemberInitializer() const { + return Initializee.is(); + } + + /// isInClassMemberInitializer - Returns true when this initializer is an + /// implicit ctor initializer generated for a field with an initializer + /// defined on the member declaration. + bool isInClassMemberInitializer() const { + return !Init; + } + + /// isDelegatingInitializer - Returns true when this initializer is creating + /// a delegating constructor. + bool isDelegatingInitializer() const { + return Initializee.is() && IsDelegating; + } + + /// \brief Determine whether this initializer is a pack expansion. + bool isPackExpansion() const { + return isBaseInitializer() && MemberOrEllipsisLocation.isValid(); + } + + // \brief For a pack expansion, returns the location of the ellipsis. + SourceLocation getEllipsisLoc() const { + assert(isPackExpansion() && "Initializer is not a pack expansion"); + return MemberOrEllipsisLocation; + } + + /// If this is a base class initializer, returns the type of the + /// base class with location information. Otherwise, returns an NULL + /// type location. + TypeLoc getBaseClassLoc() const; + + /// If this is a base class initializer, returns the type of the base class. + /// Otherwise, returns NULL. + const Type *getBaseClass() const; + + /// Returns whether the base is virtual or not. + bool isBaseVirtual() const { + assert(isBaseInitializer() && "Must call this on base initializer!"); + + return IsVirtual; + } + + /// \brief Returns the declarator information for a base class or delegating + /// initializer. + TypeSourceInfo *getTypeSourceInfo() const { + return Initializee.dyn_cast(); + } + + /// getMember - If this is a member initializer, returns the + /// declaration of the non-static data member being + /// initialized. Otherwise, returns NULL. + FieldDecl *getMember() const { + if (isMemberInitializer()) + return Initializee.get(); + return 0; + } + FieldDecl *getAnyMember() const { + if (isMemberInitializer()) + return Initializee.get(); + if (isIndirectMemberInitializer()) + return Initializee.get()->getAnonField(); + return 0; + } + + IndirectFieldDecl *getIndirectMember() const { + if (isIndirectMemberInitializer()) + return Initializee.get(); + return 0; + } + + SourceLocation getMemberLocation() const { + return MemberOrEllipsisLocation; + } + + /// \brief Determine the source location of the initializer. + SourceLocation getSourceLocation() const; + + /// \brief Determine the source range covering the entire initializer. + SourceRange getSourceRange() const LLVM_READONLY; + + /// isWritten - Returns true if this initializer is explicitly written + /// in the source code. + bool isWritten() const { return IsWritten; } + + /// \brief Return the source position of the initializer, counting from 0. + /// If the initializer was implicit, -1 is returned. + int getSourceOrder() const { + return IsWritten ? static_cast(SourceOrderOrNumArrayIndices) : -1; + } + + /// \brief Set the source order of this initializer. This method can only + /// be called once for each initializer; it cannot be called on an + /// initializer having a positive number of (implicit) array indices. + void setSourceOrder(int pos) { + assert(!IsWritten && + "calling twice setSourceOrder() on the same initializer"); + assert(SourceOrderOrNumArrayIndices == 0 && + "setSourceOrder() used when there are implicit array indices"); + assert(pos >= 0 && + "setSourceOrder() used to make an initializer implicit"); + IsWritten = true; + SourceOrderOrNumArrayIndices = static_cast(pos); + } + + SourceLocation getLParenLoc() const { return LParenLoc; } + SourceLocation getRParenLoc() const { return RParenLoc; } + + /// \brief Determine the number of implicit array indices used while + /// described an array member initialization. + unsigned getNumArrayIndices() const { + return IsWritten ? 0 : SourceOrderOrNumArrayIndices; + } + + /// \brief Retrieve a particular array index variable used to + /// describe an array member initialization. + VarDecl *getArrayIndex(unsigned I) { + assert(I < getNumArrayIndices() && "Out of bounds member array index"); + return reinterpret_cast(this + 1)[I]; + } + const VarDecl *getArrayIndex(unsigned I) const { + assert(I < getNumArrayIndices() && "Out of bounds member array index"); + return reinterpret_cast(this + 1)[I]; + } + void setArrayIndex(unsigned I, VarDecl *Index) { + assert(I < getNumArrayIndices() && "Out of bounds member array index"); + reinterpret_cast(this + 1)[I] = Index; + } + ArrayRef getArrayIndexes() { + assert(getNumArrayIndices() != 0 && "Getting indexes for non-array init"); + return ArrayRef(reinterpret_cast(this + 1), + getNumArrayIndices()); + } + + /// \brief Get the initializer. This is 0 if this is an in-class initializer + /// for a non-static data member which has not yet been parsed. + Expr *getInit() const { + if (!Init) + return getAnyMember()->getInClassInitializer(); + + return static_cast(Init); + } +}; + +/// CXXConstructorDecl - Represents a C++ constructor within a +/// class. For example: +/// +/// @code +/// class X { +/// public: +/// explicit X(int); // represented by a CXXConstructorDecl. +/// }; +/// @endcode +class CXXConstructorDecl : public CXXMethodDecl { + virtual void anchor(); + /// IsExplicitSpecified - Whether this constructor declaration has the + /// 'explicit' keyword specified. + bool IsExplicitSpecified : 1; + + /// ImplicitlyDefined - Whether this constructor was implicitly + /// defined by the compiler. When false, the constructor was defined + /// by the user. In C++03, this flag will have the same value as + /// Implicit. In C++0x, however, a constructor that is + /// explicitly defaulted (i.e., defined with " = default") will have + /// @c !Implicit && ImplicitlyDefined. + bool ImplicitlyDefined : 1; + + /// Support for base and member initializers. + /// CtorInitializers - The arguments used to initialize the base + /// or member. + CXXCtorInitializer **CtorInitializers; + unsigned NumCtorInitializers; + + CXXConstructorDecl(CXXRecordDecl *RD, SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + bool isExplicitSpecified, bool isInline, + bool isImplicitlyDeclared, bool isConstexpr) + : CXXMethodDecl(CXXConstructor, RD, StartLoc, NameInfo, T, TInfo, false, + SC_None, isInline, isConstexpr, SourceLocation()), + IsExplicitSpecified(isExplicitSpecified), ImplicitlyDefined(false), + CtorInitializers(0), NumCtorInitializers(0) { + setImplicit(isImplicitlyDeclared); + } + +public: + static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID); + static CXXConstructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, + SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + bool isExplicit, + bool isInline, bool isImplicitlyDeclared, + bool isConstexpr); + + /// isExplicitSpecified - Whether this constructor declaration has the + /// 'explicit' keyword specified. + bool isExplicitSpecified() const { return IsExplicitSpecified; } + + /// isExplicit - Whether this constructor was marked "explicit" or not. + bool isExplicit() const { + return cast(getFirstDeclaration()) + ->isExplicitSpecified(); + } + + /// isImplicitlyDefined - Whether this constructor was implicitly + /// defined. If false, then this constructor was defined by the + /// user. This operation can only be invoked if the constructor has + /// already been defined. + bool isImplicitlyDefined() const { + assert(isThisDeclarationADefinition() && + "Can only get the implicit-definition flag once the " + "constructor has been defined"); + return ImplicitlyDefined; + } + + /// setImplicitlyDefined - Set whether this constructor was + /// implicitly defined or not. + void setImplicitlyDefined(bool ID) { + assert(isThisDeclarationADefinition() && + "Can only set the implicit-definition flag once the constructor " + "has been defined"); + ImplicitlyDefined = ID; + } + + /// init_iterator - Iterates through the member/base initializer list. + typedef CXXCtorInitializer **init_iterator; + + /// init_const_iterator - Iterates through the memberbase initializer list. + typedef CXXCtorInitializer * const * init_const_iterator; + + /// init_begin() - Retrieve an iterator to the first initializer. + init_iterator init_begin() { return CtorInitializers; } + /// begin() - Retrieve an iterator to the first initializer. + init_const_iterator init_begin() const { return CtorInitializers; } + + /// init_end() - Retrieve an iterator past the last initializer. + init_iterator init_end() { + return CtorInitializers + NumCtorInitializers; + } + /// end() - Retrieve an iterator past the last initializer. + init_const_iterator init_end() const { + return CtorInitializers + NumCtorInitializers; + } + + typedef std::reverse_iterator init_reverse_iterator; + typedef std::reverse_iterator + init_const_reverse_iterator; + + init_reverse_iterator init_rbegin() { + return init_reverse_iterator(init_end()); + } + init_const_reverse_iterator init_rbegin() const { + return init_const_reverse_iterator(init_end()); + } + + init_reverse_iterator init_rend() { + return init_reverse_iterator(init_begin()); + } + init_const_reverse_iterator init_rend() const { + return init_const_reverse_iterator(init_begin()); + } + + /// getNumArgs - Determine the number of arguments used to + /// initialize the member or base. + unsigned getNumCtorInitializers() const { + return NumCtorInitializers; + } + + void setNumCtorInitializers(unsigned numCtorInitializers) { + NumCtorInitializers = numCtorInitializers; + } + + void setCtorInitializers(CXXCtorInitializer ** initializers) { + CtorInitializers = initializers; + } + + /// isDelegatingConstructor - Whether this constructor is a + /// delegating constructor + bool isDelegatingConstructor() const { + return (getNumCtorInitializers() == 1) && + CtorInitializers[0]->isDelegatingInitializer(); + } + + /// getTargetConstructor - When this constructor delegates to + /// another, retrieve the target + CXXConstructorDecl *getTargetConstructor() const; + + /// isDefaultConstructor - Whether this constructor is a default + /// constructor (C++ [class.ctor]p5), which can be used to + /// default-initialize a class of this type. + bool isDefaultConstructor() const; + + /// isCopyConstructor - Whether this constructor is a copy + /// constructor (C++ [class.copy]p2, which can be used to copy the + /// class. @p TypeQuals will be set to the qualifiers on the + /// argument type. For example, @p TypeQuals would be set to @c + /// QualType::Const for the following copy constructor: + /// + /// @code + /// class X { + /// public: + /// X(const X&); + /// }; + /// @endcode + bool isCopyConstructor(unsigned &TypeQuals) const; + + /// isCopyConstructor - Whether this constructor is a copy + /// constructor (C++ [class.copy]p2, which can be used to copy the + /// class. + bool isCopyConstructor() const { + unsigned TypeQuals = 0; + return isCopyConstructor(TypeQuals); + } + + /// \brief Determine whether this constructor is a move constructor + /// (C++0x [class.copy]p3), which can be used to move values of the class. + /// + /// \param TypeQuals If this constructor is a move constructor, will be set + /// to the type qualifiers on the referent of the first parameter's type. + bool isMoveConstructor(unsigned &TypeQuals) const; + + /// \brief Determine whether this constructor is a move constructor + /// (C++0x [class.copy]p3), which can be used to move values of the class. + bool isMoveConstructor() const { + unsigned TypeQuals = 0; + return isMoveConstructor(TypeQuals); + } + + /// \brief Determine whether this is a copy or move constructor. + /// + /// \param TypeQuals Will be set to the type qualifiers on the reference + /// parameter, if in fact this is a copy or move constructor. + bool isCopyOrMoveConstructor(unsigned &TypeQuals) const; + + /// \brief Determine whether this a copy or move constructor. + bool isCopyOrMoveConstructor() const { + unsigned Quals; + return isCopyOrMoveConstructor(Quals); + } + + /// isConvertingConstructor - Whether this constructor is a + /// converting constructor (C++ [class.conv.ctor]), which can be + /// used for user-defined conversions. + bool isConvertingConstructor(bool AllowExplicit) const; + + /// \brief Determine whether this is a member template specialization that + /// would copy the object to itself. Such constructors are never used to copy + /// an object. + bool isSpecializationCopyingObject() const; + + /// \brief Get the constructor that this inheriting constructor is based on. + const CXXConstructorDecl *getInheritedConstructor() const; + + /// \brief Set the constructor that this inheriting constructor is based on. + void setInheritedConstructor(const CXXConstructorDecl *BaseCtor); + + const CXXConstructorDecl *getCanonicalDecl() const { + return cast(FunctionDecl::getCanonicalDecl()); + } + CXXConstructorDecl *getCanonicalDecl() { + return cast(FunctionDecl::getCanonicalDecl()); + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const CXXConstructorDecl *D) { return true; } + static bool classofKind(Kind K) { return K == CXXConstructor; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// CXXDestructorDecl - Represents a C++ destructor within a +/// class. For example: +/// +/// @code +/// class X { +/// public: +/// ~X(); // represented by a CXXDestructorDecl. +/// }; +/// @endcode +class CXXDestructorDecl : public CXXMethodDecl { + virtual void anchor(); + /// ImplicitlyDefined - Whether this destructor was implicitly + /// defined by the compiler. When false, the destructor was defined + /// by the user. In C++03, this flag will have the same value as + /// Implicit. In C++0x, however, a destructor that is + /// explicitly defaulted (i.e., defined with " = default") will have + /// @c !Implicit && ImplicitlyDefined. + bool ImplicitlyDefined : 1; + + FunctionDecl *OperatorDelete; + + CXXDestructorDecl(CXXRecordDecl *RD, SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + bool isInline, bool isImplicitlyDeclared) + : CXXMethodDecl(CXXDestructor, RD, StartLoc, NameInfo, T, TInfo, false, + SC_None, isInline, /*isConstexpr=*/false, SourceLocation()), + ImplicitlyDefined(false), OperatorDelete(0) { + setImplicit(isImplicitlyDeclared); + } + +public: + static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, + SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo* TInfo, + bool isInline, + bool isImplicitlyDeclared); + static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID); + + /// isImplicitlyDefined - Whether this destructor was implicitly + /// defined. If false, then this destructor was defined by the + /// user. This operation can only be invoked if the destructor has + /// already been defined. + bool isImplicitlyDefined() const { + assert(isThisDeclarationADefinition() && + "Can only get the implicit-definition flag once the destructor has " + "been defined"); + return ImplicitlyDefined; + } + + /// setImplicitlyDefined - Set whether this destructor was + /// implicitly defined or not. + void setImplicitlyDefined(bool ID) { + assert(isThisDeclarationADefinition() && + "Can only set the implicit-definition flag once the destructor has " + "been defined"); + ImplicitlyDefined = ID; + } + + void setOperatorDelete(FunctionDecl *OD) { OperatorDelete = OD; } + const FunctionDecl *getOperatorDelete() const { return OperatorDelete; } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const CXXDestructorDecl *D) { return true; } + static bool classofKind(Kind K) { return K == CXXDestructor; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// CXXConversionDecl - Represents a C++ conversion function within a +/// class. For example: +/// +/// @code +/// class X { +/// public: +/// operator bool(); +/// }; +/// @endcode +class CXXConversionDecl : public CXXMethodDecl { + virtual void anchor(); + /// IsExplicitSpecified - Whether this conversion function declaration is + /// marked "explicit", meaning that it can only be applied when the user + /// explicitly wrote a cast. This is a C++0x feature. + bool IsExplicitSpecified : 1; + + CXXConversionDecl(CXXRecordDecl *RD, SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + bool isInline, bool isExplicitSpecified, + bool isConstexpr, SourceLocation EndLocation) + : CXXMethodDecl(CXXConversion, RD, StartLoc, NameInfo, T, TInfo, false, + SC_None, isInline, isConstexpr, EndLocation), + IsExplicitSpecified(isExplicitSpecified) { } + +public: + static CXXConversionDecl *Create(ASTContext &C, CXXRecordDecl *RD, + SourceLocation StartLoc, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + bool isInline, bool isExplicit, + bool isConstexpr, + SourceLocation EndLocation); + static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + /// IsExplicitSpecified - Whether this conversion function declaration is + /// marked "explicit", meaning that it can only be applied when the user + /// explicitly wrote a cast. This is a C++0x feature. + bool isExplicitSpecified() const { return IsExplicitSpecified; } + + /// isExplicit - Whether this is an explicit conversion operator + /// (C++0x only). Explicit conversion operators are only considered + /// when the user has explicitly written a cast. + bool isExplicit() const { + return cast(getFirstDeclaration()) + ->isExplicitSpecified(); + } + + /// getConversionType - Returns the type that this conversion + /// function is converting to. + QualType getConversionType() const { + return getType()->getAs()->getResultType(); + } + + /// \brief Determine whether this conversion function is a conversion from + /// a lambda closure type to a block pointer. + bool isLambdaToBlockPointerConversion() const; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const CXXConversionDecl *D) { return true; } + static bool classofKind(Kind K) { return K == CXXConversion; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// LinkageSpecDecl - This represents a linkage specification. For example: +/// extern "C" void foo(); +/// +class LinkageSpecDecl : public Decl, public DeclContext { + virtual void anchor(); +public: + /// LanguageIDs - Used to represent the language in a linkage + /// specification. The values are part of the serialization abi for + /// ASTs and cannot be changed without altering that abi. To help + /// ensure a stable abi for this, we choose the DW_LANG_ encodings + /// from the dwarf standard. + enum LanguageIDs { + lang_c = /* DW_LANG_C */ 0x0002, + lang_cxx = /* DW_LANG_C_plus_plus */ 0x0004 + }; +private: + /// Language - The language for this linkage specification. + LanguageIDs Language; + /// ExternLoc - The source location for the extern keyword. + SourceLocation ExternLoc; + /// RBraceLoc - The source location for the right brace (if valid). + SourceLocation RBraceLoc; + + LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc, + SourceLocation LangLoc, LanguageIDs lang, + SourceLocation RBLoc) + : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec), + Language(lang), ExternLoc(ExternLoc), RBraceLoc(RBLoc) { } + +public: + static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation ExternLoc, + SourceLocation LangLoc, LanguageIDs Lang, + SourceLocation RBraceLoc = SourceLocation()); + static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + /// \brief Return the language specified by this linkage specification. + LanguageIDs getLanguage() const { return Language; } + /// \brief Set the language specified by this linkage specification. + void setLanguage(LanguageIDs L) { Language = L; } + + /// \brief Determines whether this linkage specification had braces in + /// its syntactic form. + bool hasBraces() const { return RBraceLoc.isValid(); } + + SourceLocation getExternLoc() const { return ExternLoc; } + SourceLocation getRBraceLoc() const { return RBraceLoc; } + void setExternLoc(SourceLocation L) { ExternLoc = L; } + void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } + + SourceLocation getLocEnd() const LLVM_READONLY { + if (hasBraces()) + return getRBraceLoc(); + // No braces: get the end location of the (only) declaration in context + // (if present). + return decls_empty() ? getLocation() : decls_begin()->getLocEnd(); + } + + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(ExternLoc, getLocEnd()); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const LinkageSpecDecl *D) { return true; } + static bool classofKind(Kind K) { return K == LinkageSpec; } + static DeclContext *castToDeclContext(const LinkageSpecDecl *D) { + return static_cast(const_cast(D)); + } + static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) { + return static_cast(const_cast(DC)); + } +}; + +/// UsingDirectiveDecl - Represents C++ using-directive. For example: +/// +/// using namespace std; +/// +// NB: UsingDirectiveDecl should be Decl not NamedDecl, but we provide +// artificial names for all using-directives in order to store +// them in DeclContext effectively. +class UsingDirectiveDecl : public NamedDecl { + virtual void anchor(); + /// \brief The location of the "using" keyword. + SourceLocation UsingLoc; + + /// SourceLocation - Location of 'namespace' token. + SourceLocation NamespaceLoc; + + /// \brief The nested-name-specifier that precedes the namespace. + NestedNameSpecifierLoc QualifierLoc; + + /// NominatedNamespace - Namespace nominated by using-directive. + NamedDecl *NominatedNamespace; + + /// Enclosing context containing both using-directive and nominated + /// namespace. + DeclContext *CommonAncestor; + + /// getUsingDirectiveName - Returns special DeclarationName used by + /// using-directives. This is only used by DeclContext for storing + /// UsingDirectiveDecls in its lookup structure. + static DeclarationName getName() { + return DeclarationName::getUsingDirectiveName(); + } + + UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc, + SourceLocation NamespcLoc, + NestedNameSpecifierLoc QualifierLoc, + SourceLocation IdentLoc, + NamedDecl *Nominated, + DeclContext *CommonAncestor) + : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc), + NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc), + NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) { } + +public: + /// \brief Retrieve the nested-name-specifier that qualifies the + /// name of the namespace, with source-location information. + NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } + + /// \brief Retrieve the nested-name-specifier that qualifies the + /// name of the namespace. + NestedNameSpecifier *getQualifier() const { + return QualifierLoc.getNestedNameSpecifier(); + } + + NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; } + const NamedDecl *getNominatedNamespaceAsWritten() const { + return NominatedNamespace; + } + + /// getNominatedNamespace - Returns namespace nominated by using-directive. + NamespaceDecl *getNominatedNamespace(); + + const NamespaceDecl *getNominatedNamespace() const { + return const_cast(this)->getNominatedNamespace(); + } + + /// \brief Returns the common ancestor context of this using-directive and + /// its nominated namespace. + DeclContext *getCommonAncestor() { return CommonAncestor; } + const DeclContext *getCommonAncestor() const { return CommonAncestor; } + + /// \brief Return the location of the "using" keyword. + SourceLocation getUsingLoc() const { return UsingLoc; } + + // FIXME: Could omit 'Key' in name. + /// getNamespaceKeyLocation - Returns location of namespace keyword. + SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; } + + /// getIdentLocation - Returns location of identifier. + SourceLocation getIdentLocation() const { return getLocation(); } + + static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation UsingLoc, + SourceLocation NamespaceLoc, + NestedNameSpecifierLoc QualifierLoc, + SourceLocation IdentLoc, + NamedDecl *Nominated, + DeclContext *CommonAncestor); + static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(UsingLoc, getLocation()); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const UsingDirectiveDecl *D) { return true; } + static bool classofKind(Kind K) { return K == UsingDirective; } + + // Friend for getUsingDirectiveName. + friend class DeclContext; + + friend class ASTDeclReader; +}; + +/// NamespaceAliasDecl - Represents a C++ namespace alias. For example: +/// +/// @code +/// namespace Foo = Bar; +/// @endcode +class NamespaceAliasDecl : public NamedDecl { + virtual void anchor(); + + /// \brief The location of the "namespace" keyword. + SourceLocation NamespaceLoc; + + /// IdentLoc - Location of namespace identifier. Accessed by TargetNameLoc. + SourceLocation IdentLoc; + + /// \brief The nested-name-specifier that precedes the namespace. + NestedNameSpecifierLoc QualifierLoc; + + /// Namespace - The Decl that this alias points to. Can either be a + /// NamespaceDecl or a NamespaceAliasDecl. + NamedDecl *Namespace; + + NamespaceAliasDecl(DeclContext *DC, SourceLocation NamespaceLoc, + SourceLocation AliasLoc, IdentifierInfo *Alias, + NestedNameSpecifierLoc QualifierLoc, + SourceLocation IdentLoc, NamedDecl *Namespace) + : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), + NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc), + QualifierLoc(QualifierLoc), Namespace(Namespace) { } + + friend class ASTDeclReader; + +public: + /// \brief Retrieve the nested-name-specifier that qualifies the + /// name of the namespace, with source-location information. + NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } + + /// \brief Retrieve the nested-name-specifier that qualifies the + /// name of the namespace. + NestedNameSpecifier *getQualifier() const { + return QualifierLoc.getNestedNameSpecifier(); + } + + /// \brief Retrieve the namespace declaration aliased by this directive. + NamespaceDecl *getNamespace() { + if (NamespaceAliasDecl *AD = dyn_cast(Namespace)) + return AD->getNamespace(); + + return cast(Namespace); + } + + const NamespaceDecl *getNamespace() const { + return const_cast(this)->getNamespace(); + } + + /// Returns the location of the alias name, i.e. 'foo' in + /// "namespace foo = ns::bar;". + SourceLocation getAliasLoc() const { return getLocation(); } + + /// Returns the location of the 'namespace' keyword. + SourceLocation getNamespaceLoc() const { return NamespaceLoc; } + + /// Returns the location of the identifier in the named namespace. + SourceLocation getTargetNameLoc() const { return IdentLoc; } + + /// \brief Retrieve the namespace that this alias refers to, which + /// may either be a NamespaceDecl or a NamespaceAliasDecl. + NamedDecl *getAliasedNamespace() const { return Namespace; } + + static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation NamespaceLoc, + SourceLocation AliasLoc, + IdentifierInfo *Alias, + NestedNameSpecifierLoc QualifierLoc, + SourceLocation IdentLoc, + NamedDecl *Namespace); + + static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + virtual SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(NamespaceLoc, IdentLoc); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const NamespaceAliasDecl *D) { return true; } + static bool classofKind(Kind K) { return K == NamespaceAlias; } +}; + +/// UsingShadowDecl - Represents a shadow declaration introduced into +/// a scope by a (resolved) using declaration. For example, +/// +/// namespace A { +/// void foo(); +/// } +/// namespace B { +/// using A::foo(); // <- a UsingDecl +/// // Also creates a UsingShadowDecl for A::foo in B +/// } +/// +class UsingShadowDecl : public NamedDecl { + virtual void anchor(); + + /// The referenced declaration. + NamedDecl *Underlying; + + /// \brief The using declaration which introduced this decl or the next using + /// shadow declaration contained in the aforementioned using declaration. + NamedDecl *UsingOrNextShadow; + friend class UsingDecl; + + UsingShadowDecl(DeclContext *DC, SourceLocation Loc, UsingDecl *Using, + NamedDecl *Target) + : NamedDecl(UsingShadow, DC, Loc, DeclarationName()), + Underlying(Target), + UsingOrNextShadow(reinterpret_cast(Using)) { + if (Target) { + setDeclName(Target->getDeclName()); + IdentifierNamespace = Target->getIdentifierNamespace(); + } + setImplicit(); + } + +public: + static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation Loc, UsingDecl *Using, + NamedDecl *Target) { + return new (C) UsingShadowDecl(DC, Loc, Using, Target); + } + + static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + /// \brief Gets the underlying declaration which has been brought into the + /// local scope. + NamedDecl *getTargetDecl() const { return Underlying; } + + /// \brief Sets the underlying declaration which has been brought into the + /// local scope. + void setTargetDecl(NamedDecl* ND) { + assert(ND && "Target decl is null!"); + Underlying = ND; + IdentifierNamespace = ND->getIdentifierNamespace(); + } + + /// \brief Gets the using declaration to which this declaration is tied. + UsingDecl *getUsingDecl() const; + + /// \brief The next using shadow declaration contained in the shadow decl + /// chain of the using declaration which introduced this decl. + UsingShadowDecl *getNextUsingShadowDecl() const { + return dyn_cast_or_null(UsingOrNextShadow); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const UsingShadowDecl *D) { return true; } + static bool classofKind(Kind K) { return K == Decl::UsingShadow; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// UsingDecl - Represents a C++ using-declaration. For example: +/// using someNameSpace::someIdentifier; +class UsingDecl : public NamedDecl { + virtual void anchor(); + + /// \brief The source location of the "using" location itself. + SourceLocation UsingLocation; + + /// \brief The nested-name-specifier that precedes the name. + NestedNameSpecifierLoc QualifierLoc; + + /// DNLoc - Provides source/type location info for the + /// declaration name embedded in the ValueDecl base class. + DeclarationNameLoc DNLoc; + + /// \brief The first shadow declaration of the shadow decl chain associated + /// with this using declaration. The bool member of the pair store whether + /// this decl has the 'typename' keyword. + llvm::PointerIntPair FirstUsingShadow; + + UsingDecl(DeclContext *DC, SourceLocation UL, + NestedNameSpecifierLoc QualifierLoc, + const DeclarationNameInfo &NameInfo, bool IsTypeNameArg) + : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()), + UsingLocation(UL), QualifierLoc(QualifierLoc), + DNLoc(NameInfo.getInfo()), FirstUsingShadow(0, IsTypeNameArg) { + } + +public: + /// \brief Returns the source location of the "using" keyword. + SourceLocation getUsingLocation() const { return UsingLocation; } + + /// \brief Set the source location of the 'using' keyword. + void setUsingLocation(SourceLocation L) { UsingLocation = L; } + + /// \brief Retrieve the nested-name-specifier that qualifies the name, + /// with source-location information. + NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } + + /// \brief Retrieve the nested-name-specifier that qualifies the name. + NestedNameSpecifier *getQualifier() const { + return QualifierLoc.getNestedNameSpecifier(); + } + + DeclarationNameInfo getNameInfo() const { + return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); + } + + /// \brief Return true if the using declaration has 'typename'. + bool isTypeName() const { return FirstUsingShadow.getInt(); } + + /// \brief Sets whether the using declaration has 'typename'. + void setTypeName(bool TN) { FirstUsingShadow.setInt(TN); } + + /// \brief Iterates through the using shadow declarations assosiated with + /// this using declaration. + class shadow_iterator { + /// \brief The current using shadow declaration. + UsingShadowDecl *Current; + + public: + typedef UsingShadowDecl* value_type; + typedef UsingShadowDecl* reference; + typedef UsingShadowDecl* pointer; + typedef std::forward_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + + shadow_iterator() : Current(0) { } + explicit shadow_iterator(UsingShadowDecl *C) : Current(C) { } + + reference operator*() const { return Current; } + pointer operator->() const { return Current; } + + shadow_iterator& operator++() { + Current = Current->getNextUsingShadowDecl(); + return *this; + } + + shadow_iterator operator++(int) { + shadow_iterator tmp(*this); + ++(*this); + return tmp; + } + + friend bool operator==(shadow_iterator x, shadow_iterator y) { + return x.Current == y.Current; + } + friend bool operator!=(shadow_iterator x, shadow_iterator y) { + return x.Current != y.Current; + } + }; + + shadow_iterator shadow_begin() const { + return shadow_iterator(FirstUsingShadow.getPointer()); + } + shadow_iterator shadow_end() const { return shadow_iterator(); } + + /// \brief Return the number of shadowed declarations associated with this + /// using declaration. + unsigned shadow_size() const { + return std::distance(shadow_begin(), shadow_end()); + } + + void addShadowDecl(UsingShadowDecl *S); + void removeShadowDecl(UsingShadowDecl *S); + + static UsingDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation UsingL, + NestedNameSpecifierLoc QualifierLoc, + const DeclarationNameInfo &NameInfo, + bool IsTypeNameArg); + + static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(UsingLocation, getNameInfo().getEndLoc()); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const UsingDecl *D) { return true; } + static bool classofKind(Kind K) { return K == Using; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// UnresolvedUsingValueDecl - Represents a dependent using +/// declaration which was not marked with 'typename'. Unlike +/// non-dependent using declarations, these *only* bring through +/// non-types; otherwise they would break two-phase lookup. +/// +/// template class A : public Base { +/// using Base::foo; +/// }; +class UnresolvedUsingValueDecl : public ValueDecl { + virtual void anchor(); + + /// \brief The source location of the 'using' keyword + SourceLocation UsingLocation; + + /// \brief The nested-name-specifier that precedes the name. + NestedNameSpecifierLoc QualifierLoc; + + /// DNLoc - Provides source/type location info for the + /// declaration name embedded in the ValueDecl base class. + DeclarationNameLoc DNLoc; + + UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty, + SourceLocation UsingLoc, + NestedNameSpecifierLoc QualifierLoc, + const DeclarationNameInfo &NameInfo) + : ValueDecl(UnresolvedUsingValue, DC, + NameInfo.getLoc(), NameInfo.getName(), Ty), + UsingLocation(UsingLoc), QualifierLoc(QualifierLoc), + DNLoc(NameInfo.getInfo()) + { } + +public: + /// \brief Returns the source location of the 'using' keyword. + SourceLocation getUsingLoc() const { return UsingLocation; } + + /// \brief Set the source location of the 'using' keyword. + void setUsingLoc(SourceLocation L) { UsingLocation = L; } + + /// \brief Retrieve the nested-name-specifier that qualifies the name, + /// with source-location information. + NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } + + /// \brief Retrieve the nested-name-specifier that qualifies the name. + NestedNameSpecifier *getQualifier() const { + return QualifierLoc.getNestedNameSpecifier(); + } + + DeclarationNameInfo getNameInfo() const { + return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); + } + + static UnresolvedUsingValueDecl * + Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, + NestedNameSpecifierLoc QualifierLoc, + const DeclarationNameInfo &NameInfo); + + static UnresolvedUsingValueDecl * + CreateDeserialized(ASTContext &C, unsigned ID); + + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(UsingLocation, getNameInfo().getEndLoc()); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const UnresolvedUsingValueDecl *D) { return true; } + static bool classofKind(Kind K) { return K == UnresolvedUsingValue; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// UnresolvedUsingTypenameDecl - Represents a dependent using +/// declaration which was marked with 'typename'. +/// +/// template class A : public Base { +/// using typename Base::foo; +/// }; +/// +/// The type associated with a unresolved using typename decl is +/// currently always a typename type. +class UnresolvedUsingTypenameDecl : public TypeDecl { + virtual void anchor(); + + /// \brief The source location of the 'using' keyword + SourceLocation UsingLocation; + + /// \brief The source location of the 'typename' keyword + SourceLocation TypenameLocation; + + /// \brief The nested-name-specifier that precedes the name. + NestedNameSpecifierLoc QualifierLoc; + + UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc, + SourceLocation TypenameLoc, + NestedNameSpecifierLoc QualifierLoc, + SourceLocation TargetNameLoc, + IdentifierInfo *TargetName) + : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName, + UsingLoc), + TypenameLocation(TypenameLoc), QualifierLoc(QualifierLoc) { } + + friend class ASTDeclReader; + +public: + /// \brief Returns the source location of the 'using' keyword. + SourceLocation getUsingLoc() const { return getLocStart(); } + + /// \brief Returns the source location of the 'typename' keyword. + SourceLocation getTypenameLoc() const { return TypenameLocation; } + + /// \brief Retrieve the nested-name-specifier that qualifies the name, + /// with source-location information. + NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } + + /// \brief Retrieve the nested-name-specifier that qualifies the name. + NestedNameSpecifier *getQualifier() const { + return QualifierLoc.getNestedNameSpecifier(); + } + + static UnresolvedUsingTypenameDecl * + Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, + SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, + SourceLocation TargetNameLoc, DeclarationName TargetName); + + static UnresolvedUsingTypenameDecl * + CreateDeserialized(ASTContext &C, unsigned ID); + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const UnresolvedUsingTypenameDecl *D) { return true; } + static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; } +}; + +/// StaticAssertDecl - Represents a C++0x static_assert declaration. +class StaticAssertDecl : public Decl { + virtual void anchor(); + Expr *AssertExpr; + StringLiteral *Message; + SourceLocation RParenLoc; + + StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc, + Expr *assertexpr, StringLiteral *message, + SourceLocation RParenLoc) + : Decl(StaticAssert, DC, StaticAssertLoc), AssertExpr(assertexpr), + Message(message), RParenLoc(RParenLoc) { } + +public: + static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StaticAssertLoc, + Expr *AssertExpr, StringLiteral *Message, + SourceLocation RParenLoc); + static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + Expr *getAssertExpr() { return AssertExpr; } + const Expr *getAssertExpr() const { return AssertExpr; } + + StringLiteral *getMessage() { return Message; } + const StringLiteral *getMessage() const { return Message; } + + SourceLocation getRParenLoc() const { return RParenLoc; } + void setRParenLoc(SourceLocation L) { RParenLoc = L; } + + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(getLocation(), getRParenLoc()); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(StaticAssertDecl *D) { return true; } + static bool classofKind(Kind K) { return K == StaticAssert; } + + friend class ASTDeclReader; +}; + +/// Insertion operator for diagnostics. This allows sending AccessSpecifier's +/// into a diagnostic with <<. +const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, + AccessSpecifier AS); + +const PartialDiagnostic &operator<<(const PartialDiagnostic &DB, + AccessSpecifier AS); + +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/DeclContextInternals.h b/cpp/llvm/tools/clang/include/clang/AST/DeclContextInternals.h new file mode 100644 index 00000000..c5f2aa0b --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/DeclContextInternals.h @@ -0,0 +1,223 @@ +//===-- DeclContextInternals.h - DeclContext Representation -----*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the data structures used in the implementation +// of DeclContext. +// +//===----------------------------------------------------------------------===// +#ifndef LLVM_CLANG_AST_DECLCONTEXTINTERNALS_H +#define LLVM_CLANG_AST_DECLCONTEXTINTERNALS_H + +#include "clang/AST/Decl.h" +#include "clang/AST/DeclarationName.h" +#include "clang/AST/DeclCXX.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/PointerUnion.h" +#include "llvm/ADT/SmallVector.h" +#include + +namespace clang { + +class DependentDiagnostic; + +/// StoredDeclsList - This is an array of decls optimized a common case of only +/// containing one entry. +struct StoredDeclsList { + + /// DeclsTy - When in vector form, this is what the Data pointer points to. + typedef SmallVector DeclsTy; + + /// \brief The stored data, which will be either a pointer to a NamedDecl, + /// or a pointer to a vector. + llvm::PointerUnion Data; + +public: + StoredDeclsList() {} + + StoredDeclsList(const StoredDeclsList &RHS) : Data(RHS.Data) { + if (DeclsTy *RHSVec = RHS.getAsVector()) + Data = new DeclsTy(*RHSVec); + } + + ~StoredDeclsList() { + // If this is a vector-form, free the vector. + if (DeclsTy *Vector = getAsVector()) + delete Vector; + } + + StoredDeclsList &operator=(const StoredDeclsList &RHS) { + if (DeclsTy *Vector = getAsVector()) + delete Vector; + Data = RHS.Data; + if (DeclsTy *RHSVec = RHS.getAsVector()) + Data = new DeclsTy(*RHSVec); + return *this; + } + + bool isNull() const { return Data.isNull(); } + + NamedDecl *getAsDecl() const { + return Data.dyn_cast(); + } + + DeclsTy *getAsVector() const { + return Data.dyn_cast(); + } + + void setOnlyValue(NamedDecl *ND) { + assert(!getAsVector() && "Not inline"); + Data = ND; + // Make sure that Data is a plain NamedDecl* so we can use its address + // at getLookupResult. + assert(*(NamedDecl **)&Data == ND && + "PointerUnion mangles the NamedDecl pointer!"); + } + + void remove(NamedDecl *D) { + assert(!isNull() && "removing from empty list"); + if (NamedDecl *Singleton = getAsDecl()) { + assert(Singleton == D && "list is different singleton"); + (void)Singleton; + Data = (NamedDecl *)0; + return; + } + + DeclsTy &Vec = *getAsVector(); + DeclsTy::iterator I = std::find(Vec.begin(), Vec.end(), D); + assert(I != Vec.end() && "list does not contain decl"); + Vec.erase(I); + + assert(std::find(Vec.begin(), Vec.end(), D) + == Vec.end() && "list still contains decl"); + } + + /// getLookupResult - Return an array of all the decls that this list + /// represents. + DeclContext::lookup_result getLookupResult() { + if (isNull()) + return DeclContext::lookup_result(DeclContext::lookup_iterator(0), + DeclContext::lookup_iterator(0)); + + // If we have a single NamedDecl, return it. + if (getAsDecl()) { + assert(!isNull() && "Empty list isn't allowed"); + + // Data is a raw pointer to a NamedDecl*, return it. + void *Ptr = &Data; + return DeclContext::lookup_result((NamedDecl**)Ptr, (NamedDecl**)Ptr+1); + } + + assert(getAsVector() && "Must have a vector at this point"); + DeclsTy &Vector = *getAsVector(); + + // Otherwise, we have a range result. + return DeclContext::lookup_result(&Vector[0], &Vector[0]+Vector.size()); + } + + /// HandleRedeclaration - If this is a redeclaration of an existing decl, + /// replace the old one with D and return true. Otherwise return false. + bool HandleRedeclaration(NamedDecl *D) { + // Most decls only have one entry in their list, special case it. + if (NamedDecl *OldD = getAsDecl()) { + if (!D->declarationReplaces(OldD)) + return false; + setOnlyValue(D); + return true; + } + + // Determine if this declaration is actually a redeclaration. + DeclsTy &Vec = *getAsVector(); + for (DeclsTy::iterator OD = Vec.begin(), ODEnd = Vec.end(); + OD != ODEnd; ++OD) { + NamedDecl *OldD = *OD; + if (D->declarationReplaces(OldD)) { + *OD = D; + return true; + } + } + + return false; + } + + /// AddSubsequentDecl - This is called on the second and later decl when it is + /// not a redeclaration to merge it into the appropriate place in our list. + /// + void AddSubsequentDecl(NamedDecl *D) { + // If this is the second decl added to the list, convert this to vector + // form. + if (NamedDecl *OldD = getAsDecl()) { + DeclsTy *VT = new DeclsTy(); + VT->push_back(OldD); + Data = VT; + } + + DeclsTy &Vec = *getAsVector(); + + // Using directives end up in a special entry which contains only + // other using directives, so all this logic is wasted for them. + // But avoiding the logic wastes time in the far-more-common case + // that we're *not* adding a new using directive. + + // Tag declarations always go at the end of the list so that an + // iterator which points at the first tag will start a span of + // decls that only contains tags. + if (D->hasTagIdentifierNamespace()) + Vec.push_back(D); + + // Resolved using declarations go at the front of the list so that + // they won't show up in other lookup results. Unresolved using + // declarations (which are always in IDNS_Using | IDNS_Ordinary) + // follow that so that the using declarations will be contiguous. + else if (D->getIdentifierNamespace() & Decl::IDNS_Using) { + DeclsTy::iterator I = Vec.begin(); + if (D->getIdentifierNamespace() != Decl::IDNS_Using) { + while (I != Vec.end() && + (*I)->getIdentifierNamespace() == Decl::IDNS_Using) + ++I; + } + Vec.insert(I, D); + + // All other declarations go at the end of the list, but before any + // tag declarations. But we can be clever about tag declarations + // because there can only ever be one in a scope. + } else if (Vec.back()->hasTagIdentifierNamespace()) { + NamedDecl *TagD = Vec.back(); + Vec.back() = D; + Vec.push_back(TagD); + } else + Vec.push_back(D); + } +}; + +class StoredDeclsMap + : public llvm::DenseMap { + +public: + static void DestroyAll(StoredDeclsMap *Map, bool Dependent); + +private: + friend class ASTContext; // walks the chain deleting these + friend class DeclContext; + llvm::PointerIntPair Previous; +}; + +class DependentStoredDeclsMap : public StoredDeclsMap { +public: + DependentStoredDeclsMap() : FirstDiagnostic(0) {} + +private: + friend class DependentDiagnostic; + friend class DeclContext; // iterates over diagnostics + + DependentDiagnostic *FirstDiagnostic; +}; + +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/DeclFriend.h b/cpp/llvm/tools/clang/include/clang/AST/DeclFriend.h new file mode 100644 index 00000000..ba1eb8d7 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/DeclFriend.h @@ -0,0 +1,198 @@ +//===-- DeclFriend.h - Classes for C++ friend declarations -*- C++ -*------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the section of the AST representing C++ friend +// declarations. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_DECLFRIEND_H +#define LLVM_CLANG_AST_DECLFRIEND_H + +#include "clang/AST/DeclCXX.h" +#include "llvm/Support/Compiler.h" + +namespace clang { + +/// FriendDecl - Represents the declaration of a friend entity, +/// which can be a function, a type, or a templated function or type. +// For example: +/// +/// @code +/// template class A { +/// friend int foo(T); +/// friend class B; +/// friend T; // only in C++0x +/// template friend class C; +/// template friend A& operator+=(A&, const U&) { ... } +/// }; +/// @endcode +/// +/// The semantic context of a friend decl is its declaring class. +class FriendDecl : public Decl { + virtual void anchor(); +public: + typedef llvm::PointerUnion FriendUnion; + +private: + // The declaration that's a friend of this class. + FriendUnion Friend; + + // A pointer to the next friend in the sequence. + LazyDeclPtr NextFriend; + + // Location of the 'friend' specifier. + SourceLocation FriendLoc; + + /// True if this 'friend' declaration is unsupported. Eventually we + /// will support every possible friend declaration, but for now we + /// silently ignore some and set this flag to authorize all access. + bool UnsupportedFriend; + + friend class CXXRecordDecl::friend_iterator; + friend class CXXRecordDecl; + + FriendDecl(DeclContext *DC, SourceLocation L, FriendUnion Friend, + SourceLocation FriendL) + : Decl(Decl::Friend, DC, L), + Friend(Friend), + NextFriend(), + FriendLoc(FriendL), + UnsupportedFriend(false) { + } + + explicit FriendDecl(EmptyShell Empty) + : Decl(Decl::Friend, Empty), NextFriend() { } + + FriendDecl *getNextFriend() { + return cast_or_null( + NextFriend.get(getASTContext().getExternalSource())); + } + +public: + static FriendDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, FriendUnion Friend_, + SourceLocation FriendL); + static FriendDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + /// If this friend declaration names an (untemplated but possibly + /// dependent) type, return the type; otherwise return null. This + /// is used for elaborated-type-specifiers and, in C++0x, for + /// arbitrary friend type declarations. + TypeSourceInfo *getFriendType() const { + return Friend.dyn_cast(); + } + + /// If this friend declaration doesn't name a type, return the inner + /// declaration. + NamedDecl *getFriendDecl() const { + return Friend.dyn_cast(); + } + + /// Retrieves the location of the 'friend' keyword. + SourceLocation getFriendLoc() const { + return FriendLoc; + } + + /// Retrieves the source range for the friend declaration. + SourceRange getSourceRange() const LLVM_READONLY { + /* FIXME: consider the case of templates wrt start of range. */ + if (NamedDecl *ND = getFriendDecl()) + return SourceRange(getFriendLoc(), ND->getLocEnd()); + else if (TypeSourceInfo *TInfo = getFriendType()) + return SourceRange(getFriendLoc(), TInfo->getTypeLoc().getEndLoc()); + else + return SourceRange(getFriendLoc(), getLocation()); + } + + /// Determines if this friend kind is unsupported. + bool isUnsupportedFriend() const { + return UnsupportedFriend; + } + void setUnsupportedFriend(bool Unsupported) { + UnsupportedFriend = Unsupported; + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const FriendDecl *D) { return true; } + static bool classofKind(Kind K) { return K == Decl::Friend; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// An iterator over the friend declarations of a class. +class CXXRecordDecl::friend_iterator { + FriendDecl *Ptr; + + friend class CXXRecordDecl; + explicit friend_iterator(FriendDecl *Ptr) : Ptr(Ptr) {} +public: + friend_iterator() {} + + typedef FriendDecl *value_type; + typedef FriendDecl *reference; + typedef FriendDecl *pointer; + typedef int difference_type; + typedef std::forward_iterator_tag iterator_category; + + reference operator*() const { return Ptr; } + + friend_iterator &operator++() { + assert(Ptr && "attempt to increment past end of friend list"); + Ptr = Ptr->getNextFriend(); + return *this; + } + + friend_iterator operator++(int) { + friend_iterator tmp = *this; + ++*this; + return tmp; + } + + bool operator==(const friend_iterator &Other) const { + return Ptr == Other.Ptr; + } + + bool operator!=(const friend_iterator &Other) const { + return Ptr != Other.Ptr; + } + + friend_iterator &operator+=(difference_type N) { + assert(N >= 0 && "cannot rewind a CXXRecordDecl::friend_iterator"); + while (N--) + ++*this; + return *this; + } + + friend_iterator operator+(difference_type N) const { + friend_iterator tmp = *this; + tmp += N; + return tmp; + } +}; + +inline CXXRecordDecl::friend_iterator CXXRecordDecl::friend_begin() const { + return friend_iterator(data().FirstFriend); +} + +inline CXXRecordDecl::friend_iterator CXXRecordDecl::friend_end() const { + return friend_iterator(0); +} + +inline void CXXRecordDecl::pushFriendDecl(FriendDecl *FD) { + assert(FD->NextFriend == 0 && "friend already has next friend?"); + FD->NextFriend = data().FirstFriend; + data().FirstFriend = FD; +} + +} + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/DeclGroup.h b/cpp/llvm/tools/clang/include/clang/AST/DeclGroup.h new file mode 100644 index 00000000..63cdac59 --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/DeclGroup.h @@ -0,0 +1,151 @@ +//===--- DeclGroup.h - Classes for representing groups of Decls -*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the DeclGroup, DeclGroupRef, and OwningDeclGroup classes. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_DECLGROUP_H +#define LLVM_CLANG_AST_DECLGROUP_H + +#include "llvm/Support/DataTypes.h" +#include + +namespace clang { + +class ASTContext; +class Decl; +class DeclGroup; +class DeclGroupIterator; + +class DeclGroup { + // FIXME: Include a TypeSpecifier object. + unsigned NumDecls; + +private: + DeclGroup() : NumDecls(0) {} + DeclGroup(unsigned numdecls, Decl** decls); + +public: + static DeclGroup *Create(ASTContext &C, Decl **Decls, unsigned NumDecls); + + unsigned size() const { return NumDecls; } + + Decl*& operator[](unsigned i) { + assert (i < NumDecls && "Out-of-bounds access."); + return ((Decl**) (this+1))[i]; + } + + Decl* const& operator[](unsigned i) const { + assert (i < NumDecls && "Out-of-bounds access."); + return ((Decl* const*) (this+1))[i]; + } +}; + +class DeclGroupRef { + // Note this is not a PointerIntPair because we need the address of the + // non-group case to be valid as a Decl** for iteration. + enum Kind { SingleDeclKind=0x0, DeclGroupKind=0x1, Mask=0x1 }; + Decl* D; + + Kind getKind() const { + return (Kind) (reinterpret_cast(D) & Mask); + } + +public: + DeclGroupRef() : D(0) {} + + explicit DeclGroupRef(Decl* d) : D(d) {} + explicit DeclGroupRef(DeclGroup* dg) + : D((Decl*) (reinterpret_cast(dg) | DeclGroupKind)) {} + + static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls) { + if (NumDecls == 0) + return DeclGroupRef(); + if (NumDecls == 1) + return DeclGroupRef(Decls[0]); + return DeclGroupRef(DeclGroup::Create(C, Decls, NumDecls)); + } + + typedef Decl** iterator; + typedef Decl* const * const_iterator; + + bool isNull() const { return D == 0; } + bool isSingleDecl() const { return getKind() == SingleDeclKind; } + bool isDeclGroup() const { return getKind() == DeclGroupKind; } + + Decl *getSingleDecl() { + assert(isSingleDecl() && "Isn't a declgroup"); + return D; + } + const Decl *getSingleDecl() const { + return const_cast(this)->getSingleDecl(); + } + + DeclGroup &getDeclGroup() { + assert(isDeclGroup() && "Isn't a declgroup"); + return *((DeclGroup*)(reinterpret_cast(D) & ~Mask)); + } + const DeclGroup &getDeclGroup() const { + return const_cast(this)->getDeclGroup(); + } + + iterator begin() { + if (isSingleDecl()) + return D ? &D : 0; + return &getDeclGroup()[0]; + } + + iterator end() { + if (isSingleDecl()) + return D ? &D+1 : 0; + DeclGroup &G = getDeclGroup(); + return &G[0] + G.size(); + } + + const_iterator begin() const { + if (isSingleDecl()) + return D ? &D : 0; + return &getDeclGroup()[0]; + } + + const_iterator end() const { + if (isSingleDecl()) + return D ? &D+1 : 0; + const DeclGroup &G = getDeclGroup(); + return &G[0] + G.size(); + } + + void *getAsOpaquePtr() const { return D; } + static DeclGroupRef getFromOpaquePtr(void *Ptr) { + DeclGroupRef X; + X.D = static_cast(Ptr); + return X; + } +}; + +} // end clang namespace + +namespace llvm { + // DeclGroupRef is "like a pointer", implement PointerLikeTypeTraits. + template + class PointerLikeTypeTraits; + template <> + class PointerLikeTypeTraits { + public: + static inline void *getAsVoidPointer(clang::DeclGroupRef P) { + return P.getAsOpaquePtr(); + } + static inline clang::DeclGroupRef getFromVoidPointer(void *P) { + return clang::DeclGroupRef::getFromOpaquePtr(P); + } + enum { NumLowBitsAvailable = 0 }; + }; +} +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/DeclLookups.h b/cpp/llvm/tools/clang/include/clang/AST/DeclLookups.h new file mode 100644 index 00000000..b8abe97b --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/DeclLookups.h @@ -0,0 +1,88 @@ +//===-- DeclLookups.h - Low-level interface to all names in a DC-*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines DeclContext::all_lookups_iterator. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_DECLLOOKUPS_H +#define LLVM_CLANG_AST_DECLLOOKUPS_H + +#include "clang/AST/DeclBase.h" +#include "clang/AST/DeclContextInternals.h" +#include "clang/AST/DeclarationName.h" + +namespace clang { + +/// all_lookups_iterator - An iterator that provides a view over the results +/// of looking up every possible name. +class DeclContext::all_lookups_iterator { + StoredDeclsMap::iterator It, End; +public: + typedef lookup_result value_type; + typedef lookup_result reference; + typedef lookup_result pointer; + typedef std::forward_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + + all_lookups_iterator() {} + all_lookups_iterator(StoredDeclsMap::iterator It, + StoredDeclsMap::iterator End) + : It(It), End(End) {} + + reference operator*() const { return It->second.getLookupResult(); } + pointer operator->() const { return It->second.getLookupResult(); } + + all_lookups_iterator& operator++() { + // Filter out using directives. They don't belong as results from name + // lookup anyways, except as an implementation detail. Users of the API + // should not expect to get them (or worse, rely on it). + do { + ++It; + } while (It != End && + It->first == DeclarationName::getUsingDirectiveName()); + + return *this; + } + + all_lookups_iterator operator++(int) { + all_lookups_iterator tmp(*this); + ++(*this); + return tmp; + } + + friend bool operator==(all_lookups_iterator x, all_lookups_iterator y) { + return x.It == y.It; + } + friend bool operator!=(all_lookups_iterator x, all_lookups_iterator y) { + return x.It != y.It; + } +}; + +DeclContext::all_lookups_iterator DeclContext::lookups_begin() const { + DeclContext *Primary = const_cast(this)->getPrimaryContext(); + if (hasExternalVisibleStorage()) + getParentASTContext().getExternalSource()->completeVisibleDeclsMap(Primary); + if (StoredDeclsMap *Map = Primary->buildLookup()) + return all_lookups_iterator(Map->begin(), Map->end()); + return all_lookups_iterator(); +} + +DeclContext::all_lookups_iterator DeclContext::lookups_end() const { + DeclContext *Primary = const_cast(this)->getPrimaryContext(); + if (hasExternalVisibleStorage()) + getParentASTContext().getExternalSource()->completeVisibleDeclsMap(Primary); + if (StoredDeclsMap *Map = Primary->buildLookup()) + return all_lookups_iterator(Map->end(), Map->end()); + return all_lookups_iterator(); +} + +} // end namespace clang + +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/DeclObjC.h b/cpp/llvm/tools/clang/include/clang/AST/DeclObjC.h new file mode 100644 index 00000000..4ae073ec --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/DeclObjC.h @@ -0,0 +1,1988 @@ +//===--- DeclObjC.h - Classes for representing declarations -----*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the DeclObjC interface and subclasses. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_DECLOBJC_H +#define LLVM_CLANG_AST_DECLOBJC_H + +#include "clang/AST/Decl.h" +#include "clang/AST/SelectorLocationsKind.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/Support/Compiler.h" + +namespace clang { +class Expr; +class Stmt; +class FunctionDecl; +class RecordDecl; +class ObjCIvarDecl; +class ObjCMethodDecl; +class ObjCProtocolDecl; +class ObjCCategoryDecl; +class ObjCPropertyDecl; +class ObjCPropertyImplDecl; +class CXXCtorInitializer; + +class ObjCListBase { + void operator=(const ObjCListBase &); // DO NOT IMPLEMENT + ObjCListBase(const ObjCListBase&); // DO NOT IMPLEMENT +protected: + /// List is an array of pointers to objects that are not owned by this object. + void **List; + unsigned NumElts; + +public: + ObjCListBase() : List(0), NumElts(0) {} + unsigned size() const { return NumElts; } + bool empty() const { return NumElts == 0; } + +protected: + void set(void *const* InList, unsigned Elts, ASTContext &Ctx); +}; + + +/// ObjCList - This is a simple template class used to hold various lists of +/// decls etc, which is heavily used by the ObjC front-end. This only use case +/// this supports is setting the list all at once and then reading elements out +/// of it. +template +class ObjCList : public ObjCListBase { +public: + void set(T* const* InList, unsigned Elts, ASTContext &Ctx) { + ObjCListBase::set(reinterpret_cast(InList), Elts, Ctx); + } + + typedef T* const * iterator; + iterator begin() const { return (iterator)List; } + iterator end() const { return (iterator)List+NumElts; } + + T* operator[](unsigned Idx) const { + assert(Idx < NumElts && "Invalid access"); + return (T*)List[Idx]; + } +}; + +/// \brief A list of Objective-C protocols, along with the source +/// locations at which they were referenced. +class ObjCProtocolList : public ObjCList { + SourceLocation *Locations; + + using ObjCList::set; + +public: + ObjCProtocolList() : ObjCList(), Locations(0) { } + + typedef const SourceLocation *loc_iterator; + loc_iterator loc_begin() const { return Locations; } + loc_iterator loc_end() const { return Locations + size(); } + + void set(ObjCProtocolDecl* const* InList, unsigned Elts, + const SourceLocation *Locs, ASTContext &Ctx); +}; + + +/// ObjCMethodDecl - Represents an instance or class method declaration. +/// ObjC methods can be declared within 4 contexts: class interfaces, +/// categories, protocols, and class implementations. While C++ member +/// functions leverage C syntax, Objective-C method syntax is modeled after +/// Smalltalk (using colons to specify argument types/expressions). +/// Here are some brief examples: +/// +/// Setter/getter instance methods: +/// - (void)setMenu:(NSMenu *)menu; +/// - (NSMenu *)menu; +/// +/// Instance method that takes 2 NSView arguments: +/// - (void)replaceSubview:(NSView *)oldView with:(NSView *)newView; +/// +/// Getter class method: +/// + (NSMenu *)defaultMenu; +/// +/// A selector represents a unique name for a method. The selector names for +/// the above methods are setMenu:, menu, replaceSubview:with:, and defaultMenu. +/// +class ObjCMethodDecl : public NamedDecl, public DeclContext { +public: + enum ImplementationControl { None, Required, Optional }; +private: + // The conventional meaning of this method; an ObjCMethodFamily. + // This is not serialized; instead, it is computed on demand and + // cached. + mutable unsigned Family : ObjCMethodFamilyBitWidth; + + /// instance (true) or class (false) method. + unsigned IsInstance : 1; + unsigned IsVariadic : 1; + + // Synthesized declaration method for a property setter/getter + unsigned IsSynthesized : 1; + + // Method has a definition. + unsigned IsDefined : 1; + + /// \brief Method redeclaration in the same interface. + unsigned IsRedeclaration : 1; + + /// \brief Is redeclared in the same interface. + mutable unsigned HasRedeclaration : 1; + + // NOTE: VC++ treats enums as signed, avoid using ImplementationControl enum + /// @required/@optional + unsigned DeclImplementation : 2; + + // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum + /// in, inout, etc. + unsigned objcDeclQualifier : 6; + + /// \brief Indicates whether this method has a related result type. + unsigned RelatedResultType : 1; + + /// \brief Whether the locations of the selector identifiers are in a + /// "standard" position, a enum SelectorLocationsKind. + unsigned SelLocsKind : 2; + + // Result type of this method. + QualType MethodDeclType; + + // Type source information for the result type. + TypeSourceInfo *ResultTInfo; + + /// \brief Array of ParmVarDecls for the formal parameters of this method + /// and optionally followed by selector locations. + void *ParamsAndSelLocs; + unsigned NumParams; + + /// List of attributes for this method declaration. + SourceLocation EndLoc; // the location of the ';' or '}'. + + // The following are only used for method definitions, null otherwise. + // FIXME: space savings opportunity, consider a sub-class. + Stmt *Body; + + /// SelfDecl - Decl for the implicit self parameter. This is lazily + /// constructed by createImplicitParams. + ImplicitParamDecl *SelfDecl; + /// CmdDecl - Decl for the implicit _cmd parameter. This is lazily + /// constructed by createImplicitParams. + ImplicitParamDecl *CmdDecl; + + SelectorLocationsKind getSelLocsKind() const { + return (SelectorLocationsKind)SelLocsKind; + } + bool hasStandardSelLocs() const { + return getSelLocsKind() != SelLoc_NonStandard; + } + + /// \brief Get a pointer to the stored selector identifiers locations array. + /// No locations will be stored if HasStandardSelLocs is true. + SourceLocation *getStoredSelLocs() { + return reinterpret_cast(getParams() + NumParams); + } + const SourceLocation *getStoredSelLocs() const { + return reinterpret_cast(getParams() + NumParams); + } + + /// \brief Get a pointer to the stored selector identifiers locations array. + /// No locations will be stored if HasStandardSelLocs is true. + ParmVarDecl **getParams() { + return reinterpret_cast(ParamsAndSelLocs); + } + const ParmVarDecl *const *getParams() const { + return reinterpret_cast(ParamsAndSelLocs); + } + + /// \brief Get the number of stored selector identifiers locations. + /// No locations will be stored if HasStandardSelLocs is true. + unsigned getNumStoredSelLocs() const { + if (hasStandardSelLocs()) + return 0; + return getNumSelectorLocs(); + } + + void setParamsAndSelLocs(ASTContext &C, + ArrayRef Params, + ArrayRef SelLocs); + + ObjCMethodDecl(SourceLocation beginLoc, SourceLocation endLoc, + Selector SelInfo, QualType T, + TypeSourceInfo *ResultTInfo, + DeclContext *contextDecl, + bool isInstance = true, + bool isVariadic = false, + bool isSynthesized = false, + bool isImplicitlyDeclared = false, + bool isDefined = false, + ImplementationControl impControl = None, + bool HasRelatedResultType = false) + : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo), + DeclContext(ObjCMethod), Family(InvalidObjCMethodFamily), + IsInstance(isInstance), IsVariadic(isVariadic), + IsSynthesized(isSynthesized), + IsDefined(isDefined), IsRedeclaration(0), HasRedeclaration(0), + DeclImplementation(impControl), objcDeclQualifier(OBJC_TQ_None), + RelatedResultType(HasRelatedResultType), + SelLocsKind(SelLoc_StandardNoSpace), + MethodDeclType(T), ResultTInfo(ResultTInfo), + ParamsAndSelLocs(0), NumParams(0), + EndLoc(endLoc), Body(0), SelfDecl(0), CmdDecl(0) { + setImplicit(isImplicitlyDeclared); + } + + /// \brief A definition will return its interface declaration. + /// An interface declaration will return its definition. + /// Otherwise it will return itself. + virtual ObjCMethodDecl *getNextRedeclaration(); + +public: + static ObjCMethodDecl *Create(ASTContext &C, + SourceLocation beginLoc, + SourceLocation endLoc, + Selector SelInfo, + QualType T, + TypeSourceInfo *ResultTInfo, + DeclContext *contextDecl, + bool isInstance = true, + bool isVariadic = false, + bool isSynthesized = false, + bool isImplicitlyDeclared = false, + bool isDefined = false, + ImplementationControl impControl = None, + bool HasRelatedResultType = false); + + static ObjCMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + virtual ObjCMethodDecl *getCanonicalDecl(); + const ObjCMethodDecl *getCanonicalDecl() const { + return const_cast(this)->getCanonicalDecl(); + } + + ObjCDeclQualifier getObjCDeclQualifier() const { + return ObjCDeclQualifier(objcDeclQualifier); + } + void setObjCDeclQualifier(ObjCDeclQualifier QV) { objcDeclQualifier = QV; } + + /// \brief Determine whether this method has a result type that is related + /// to the message receiver's type. + bool hasRelatedResultType() const { return RelatedResultType; } + + /// \brief Note whether this method has a related result type. + void SetRelatedResultType(bool RRT = true) { RelatedResultType = RRT; } + + /// \brief True if this is a method redeclaration in the same interface. + bool isRedeclaration() const { return IsRedeclaration; } + void setAsRedeclaration(const ObjCMethodDecl *PrevMethod); + + // Location information, modeled after the Stmt API. + SourceLocation getLocStart() const LLVM_READONLY { return getLocation(); } + SourceLocation getLocEnd() const LLVM_READONLY { return EndLoc; } + void setEndLoc(SourceLocation Loc) { EndLoc = Loc; } + virtual SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(getLocation(), EndLoc); + } + + SourceLocation getSelectorStartLoc() const { + if (isImplicit()) + return getLocStart(); + return getSelectorLoc(0); + } + SourceLocation getSelectorLoc(unsigned Index) const { + assert(Index < getNumSelectorLocs() && "Index out of range!"); + if (hasStandardSelLocs()) + return getStandardSelectorLoc(Index, getSelector(), + getSelLocsKind() == SelLoc_StandardWithSpace, + llvm::makeArrayRef(const_cast(getParams()), + NumParams), + EndLoc); + return getStoredSelLocs()[Index]; + } + + void getSelectorLocs(SmallVectorImpl &SelLocs) const; + + unsigned getNumSelectorLocs() const { + if (isImplicit()) + return 0; + Selector Sel = getSelector(); + if (Sel.isUnarySelector()) + return 1; + return Sel.getNumArgs(); + } + + ObjCInterfaceDecl *getClassInterface(); + const ObjCInterfaceDecl *getClassInterface() const { + return const_cast(this)->getClassInterface(); + } + + Selector getSelector() const { return getDeclName().getObjCSelector(); } + + QualType getResultType() const { return MethodDeclType; } + void setResultType(QualType T) { MethodDeclType = T; } + + /// \brief Determine the type of an expression that sends a message to this + /// function. + QualType getSendResultType() const { + return getResultType().getNonLValueExprType(getASTContext()); + } + + TypeSourceInfo *getResultTypeSourceInfo() const { return ResultTInfo; } + void setResultTypeSourceInfo(TypeSourceInfo *TInfo) { ResultTInfo = TInfo; } + + // Iterator access to formal parameters. + unsigned param_size() const { return NumParams; } + typedef const ParmVarDecl *const *param_const_iterator; + typedef ParmVarDecl *const *param_iterator; + param_const_iterator param_begin() const { return getParams(); } + param_const_iterator param_end() const { return getParams() + NumParams; } + param_iterator param_begin() { return getParams(); } + param_iterator param_end() { return getParams() + NumParams; } + // This method returns and of the parameters which are part of the selector + // name mangling requirements. + param_const_iterator sel_param_end() const { + return param_begin() + getSelector().getNumArgs(); + } + + /// \brief Sets the method's parameters and selector source locations. + /// If the method is implicit (not coming from source) \arg SelLocs is + /// ignored. + void setMethodParams(ASTContext &C, + ArrayRef Params, + ArrayRef SelLocs = + ArrayRef()); + + // Iterator access to parameter types. + typedef std::const_mem_fun_t deref_fun; + typedef llvm::mapped_iterator + arg_type_iterator; + + arg_type_iterator arg_type_begin() const { + return llvm::map_iterator(param_begin(), deref_fun(&ParmVarDecl::getType)); + } + arg_type_iterator arg_type_end() const { + return llvm::map_iterator(param_end(), deref_fun(&ParmVarDecl::getType)); + } + + /// createImplicitParams - Used to lazily create the self and cmd + /// implict parameters. This must be called prior to using getSelfDecl() + /// or getCmdDecl(). The call is ignored if the implicit paramters + /// have already been created. + void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID); + + ImplicitParamDecl * getSelfDecl() const { return SelfDecl; } + void setSelfDecl(ImplicitParamDecl *SD) { SelfDecl = SD; } + ImplicitParamDecl * getCmdDecl() const { return CmdDecl; } + void setCmdDecl(ImplicitParamDecl *CD) { CmdDecl = CD; } + + /// Determines the family of this method. + ObjCMethodFamily getMethodFamily() const; + + bool isInstanceMethod() const { return IsInstance; } + void setInstanceMethod(bool isInst) { IsInstance = isInst; } + bool isVariadic() const { return IsVariadic; } + void setVariadic(bool isVar) { IsVariadic = isVar; } + + bool isClassMethod() const { return !IsInstance; } + + bool isSynthesized() const { return IsSynthesized; } + void setSynthesized(bool isSynth) { IsSynthesized = isSynth; } + + bool isDefined() const { return IsDefined; } + void setDefined(bool isDefined) { IsDefined = isDefined; } + + // Related to protocols declared in @protocol + void setDeclImplementation(ImplementationControl ic) { + DeclImplementation = ic; + } + ImplementationControl getImplementationControl() const { + return ImplementationControl(DeclImplementation); + } + + virtual Stmt *getBody() const { + return (Stmt*) Body; + } + CompoundStmt *getCompoundBody() { return (CompoundStmt*)Body; } + void setBody(Stmt *B) { Body = B; } + + /// \brief Returns whether this specific method is a definition. + bool isThisDeclarationADefinition() const { return Body; } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCMethodDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCMethod; } + static DeclContext *castToDeclContext(const ObjCMethodDecl *D) { + return static_cast(const_cast(D)); + } + static ObjCMethodDecl *castFromDeclContext(const DeclContext *DC) { + return static_cast(const_cast(DC)); + } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// ObjCContainerDecl - Represents a container for method declarations. +/// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl, +/// ObjCProtocolDecl, and ObjCImplDecl. +/// +class ObjCContainerDecl : public NamedDecl, public DeclContext { + virtual void anchor(); + + SourceLocation AtStart; + + // These two locations in the range mark the end of the method container. + // The first points to the '@' token, and the second to the 'end' token. + SourceRange AtEnd; +public: + + ObjCContainerDecl(Kind DK, DeclContext *DC, + IdentifierInfo *Id, SourceLocation nameLoc, + SourceLocation atStartLoc) + : NamedDecl(DK, DC, nameLoc, Id), DeclContext(DK), AtStart(atStartLoc) {} + + // Iterator access to properties. + typedef specific_decl_iterator prop_iterator; + prop_iterator prop_begin() const { + return prop_iterator(decls_begin()); + } + prop_iterator prop_end() const { + return prop_iterator(decls_end()); + } + + // Iterator access to instance/class methods. + typedef specific_decl_iterator method_iterator; + method_iterator meth_begin() const { + return method_iterator(decls_begin()); + } + method_iterator meth_end() const { + return method_iterator(decls_end()); + } + + typedef filtered_decl_iterator + instmeth_iterator; + instmeth_iterator instmeth_begin() const { + return instmeth_iterator(decls_begin()); + } + instmeth_iterator instmeth_end() const { + return instmeth_iterator(decls_end()); + } + + typedef filtered_decl_iterator + classmeth_iterator; + classmeth_iterator classmeth_begin() const { + return classmeth_iterator(decls_begin()); + } + classmeth_iterator classmeth_end() const { + return classmeth_iterator(decls_end()); + } + + // Get the local instance/class method declared in this interface. + ObjCMethodDecl *getMethod(Selector Sel, bool isInstance) const; + ObjCMethodDecl *getInstanceMethod(Selector Sel) const { + return getMethod(Sel, true/*isInstance*/); + } + ObjCMethodDecl *getClassMethod(Selector Sel) const { + return getMethod(Sel, false/*isInstance*/); + } + ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const; + + ObjCPropertyDecl *FindPropertyDeclaration(IdentifierInfo *PropertyId) const; + + SourceLocation getAtStartLoc() const { return AtStart; } + void setAtStartLoc(SourceLocation Loc) { AtStart = Loc; } + + // Marks the end of the container. + SourceRange getAtEndRange() const { + return AtEnd; + } + void setAtEndRange(SourceRange atEnd) { + AtEnd = atEnd; + } + + virtual SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(AtStart, getAtEndRange().getEnd()); + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCContainerDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstObjCContainer && + K <= lastObjCContainer; + } + + static DeclContext *castToDeclContext(const ObjCContainerDecl *D) { + return static_cast(const_cast(D)); + } + static ObjCContainerDecl *castFromDeclContext(const DeclContext *DC) { + return static_cast(const_cast(DC)); + } +}; + +/// ObjCInterfaceDecl - Represents an ObjC class declaration. For example: +/// +/// // MostPrimitive declares no super class (not particularly useful). +/// @interface MostPrimitive +/// // no instance variables or methods. +/// @end +/// +/// // NSResponder inherits from NSObject & implements NSCoding (a protocol). +/// @interface NSResponder : NSObject +/// { // instance variables are represented by ObjCIvarDecl. +/// id nextResponder; // nextResponder instance variable. +/// } +/// - (NSResponder *)nextResponder; // return a pointer to NSResponder. +/// - (void)mouseMoved:(NSEvent *)theEvent; // return void, takes a pointer +/// @end // to an NSEvent. +/// +/// Unlike C/C++, forward class declarations are accomplished with @class. +/// Unlike C/C++, @class allows for a list of classes to be forward declared. +/// Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes +/// typically inherit from NSObject (an exception is NSProxy). +/// +class ObjCInterfaceDecl : public ObjCContainerDecl + , public Redeclarable { + virtual void anchor(); + + /// TypeForDecl - This indicates the Type object that represents this + /// TypeDecl. It is a cache maintained by ASTContext::getObjCInterfaceType + mutable const Type *TypeForDecl; + friend class ASTContext; + + struct DefinitionData { + /// \brief The definition of this class, for quick access from any + /// declaration. + ObjCInterfaceDecl *Definition; + + /// Class's super class. + ObjCInterfaceDecl *SuperClass; + + /// Protocols referenced in the @interface declaration + ObjCProtocolList ReferencedProtocols; + + /// Protocols reference in both the @interface and class extensions. + ObjCList AllReferencedProtocols; + + /// \brief List of categories and class extensions defined for this class. + /// + /// Categories are stored as a linked list in the AST, since the categories + /// and class extensions come long after the initial interface declaration, + /// and we avoid dynamically-resized arrays in the AST wherever possible. + ObjCCategoryDecl *CategoryList; + + /// IvarList - List of all ivars defined by this class; including class + /// extensions and implementation. This list is built lazily. + ObjCIvarDecl *IvarList; + + /// \brief Indicates that the contents of this Objective-C class will be + /// completed by the external AST source when required. + mutable bool ExternallyCompleted : 1; + + /// \brief The location of the superclass, if any. + SourceLocation SuperClassLoc; + + /// \brief The location of the last location in this declaration, before + /// the properties/methods. For example, this will be the '>', '}', or + /// identifier, + SourceLocation EndLoc; + + DefinitionData() : Definition(), SuperClass(), CategoryList(), IvarList(), + ExternallyCompleted() { } + }; + + ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, + SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl, + bool isInternal); + + void LoadExternalDefinition() const; + + /// \brief Contains a pointer to the data associated with this class, + /// which will be NULL if this class has not yet been defined. + DefinitionData *Data; + + DefinitionData &data() const { + assert(Data != 0 && "Declaration has no definition!"); + return *Data; + } + + /// \brief Allocate the definition data for this class. + void allocateDefinitionData(); + + typedef Redeclarable redeclarable_base; + virtual ObjCInterfaceDecl *getNextRedeclaration() { + return RedeclLink.getNext(); + } + virtual ObjCInterfaceDecl *getPreviousDeclImpl() { + return getPreviousDecl(); + } + virtual ObjCInterfaceDecl *getMostRecentDeclImpl() { + return getMostRecentDecl(); + } + +public: + static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC, + SourceLocation atLoc, + IdentifierInfo *Id, + ObjCInterfaceDecl *PrevDecl, + SourceLocation ClassLoc = SourceLocation(), + bool isInternal = false); + + static ObjCInterfaceDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + virtual SourceRange getSourceRange() const LLVM_READONLY { + if (isThisDeclarationADefinition()) + return ObjCContainerDecl::getSourceRange(); + + return SourceRange(getAtStartLoc(), getLocation()); + } + + /// \brief Indicate that this Objective-C class is complete, but that + /// the external AST source will be responsible for filling in its contents + /// when a complete class is required. + void setExternallyCompleted(); + + const ObjCProtocolList &getReferencedProtocols() const { + assert(hasDefinition() && "Caller did not check for forward reference!"); + if (data().ExternallyCompleted) + LoadExternalDefinition(); + + return data().ReferencedProtocols; + } + + ObjCImplementationDecl *getImplementation() const; + void setImplementation(ObjCImplementationDecl *ImplD); + + ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const; + + // Get the local instance/class method declared in a category. + ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const; + ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const; + ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const { + return isInstance ? getInstanceMethod(Sel) + : getClassMethod(Sel); + } + + typedef ObjCProtocolList::iterator protocol_iterator; + + protocol_iterator protocol_begin() const { + // FIXME: Should make sure no callers ever do this. + if (!hasDefinition()) + return protocol_iterator(); + + if (data().ExternallyCompleted) + LoadExternalDefinition(); + + return data().ReferencedProtocols.begin(); + } + protocol_iterator protocol_end() const { + // FIXME: Should make sure no callers ever do this. + if (!hasDefinition()) + return protocol_iterator(); + + if (data().ExternallyCompleted) + LoadExternalDefinition(); + + return data().ReferencedProtocols.end(); + } + + typedef ObjCProtocolList::loc_iterator protocol_loc_iterator; + + protocol_loc_iterator protocol_loc_begin() const { + // FIXME: Should make sure no callers ever do this. + if (!hasDefinition()) + return protocol_loc_iterator(); + + if (data().ExternallyCompleted) + LoadExternalDefinition(); + + return data().ReferencedProtocols.loc_begin(); + } + + protocol_loc_iterator protocol_loc_end() const { + // FIXME: Should make sure no callers ever do this. + if (!hasDefinition()) + return protocol_loc_iterator(); + + if (data().ExternallyCompleted) + LoadExternalDefinition(); + + return data().ReferencedProtocols.loc_end(); + } + + typedef ObjCList::iterator all_protocol_iterator; + + all_protocol_iterator all_referenced_protocol_begin() const { + // FIXME: Should make sure no callers ever do this. + if (!hasDefinition()) + return all_protocol_iterator(); + + if (data().ExternallyCompleted) + LoadExternalDefinition(); + + return data().AllReferencedProtocols.empty() + ? protocol_begin() + : data().AllReferencedProtocols.begin(); + } + all_protocol_iterator all_referenced_protocol_end() const { + // FIXME: Should make sure no callers ever do this. + if (!hasDefinition()) + return all_protocol_iterator(); + + if (data().ExternallyCompleted) + LoadExternalDefinition(); + + return data().AllReferencedProtocols.empty() + ? protocol_end() + : data().AllReferencedProtocols.end(); + } + + typedef specific_decl_iterator ivar_iterator; + + ivar_iterator ivar_begin() const { + if (const ObjCInterfaceDecl *Def = getDefinition()) + return ivar_iterator(Def->decls_begin()); + + // FIXME: Should make sure no callers ever do this. + return ivar_iterator(); + } + ivar_iterator ivar_end() const { + if (const ObjCInterfaceDecl *Def = getDefinition()) + return ivar_iterator(Def->decls_end()); + + // FIXME: Should make sure no callers ever do this. + return ivar_iterator(); + } + + unsigned ivar_size() const { + return std::distance(ivar_begin(), ivar_end()); + } + + bool ivar_empty() const { return ivar_begin() == ivar_end(); } + + ObjCIvarDecl *all_declared_ivar_begin(); + const ObjCIvarDecl *all_declared_ivar_begin() const { + // Even though this modifies IvarList, it's conceptually const: + // the ivar chain is essentially a cached property of ObjCInterfaceDecl. + return const_cast(this)->all_declared_ivar_begin(); + } + void setIvarList(ObjCIvarDecl *ivar) { data().IvarList = ivar; } + + /// setProtocolList - Set the list of protocols that this interface + /// implements. + void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num, + const SourceLocation *Locs, ASTContext &C) { + data().ReferencedProtocols.set(List, Num, Locs, C); + } + + /// mergeClassExtensionProtocolList - Merge class extension's protocol list + /// into the protocol list for this class. + void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List, + unsigned Num, + ASTContext &C); + + /// \brief Determine whether this particular declaration of this class is + /// actually also a definition. + bool isThisDeclarationADefinition() const { + return Data && Data->Definition == this; + } + + /// \brief Determine whether this class has been defined. + bool hasDefinition() const { return Data; } + + /// \brief Retrieve the definition of this class, or NULL if this class + /// has been forward-declared (with @class) but not yet defined (with + /// @interface). + ObjCInterfaceDecl *getDefinition() { + return hasDefinition()? Data->Definition : 0; + } + + /// \brief Retrieve the definition of this class, or NULL if this class + /// has been forward-declared (with @class) but not yet defined (with + /// @interface). + const ObjCInterfaceDecl *getDefinition() const { + return hasDefinition()? Data->Definition : 0; + } + + /// \brief Starts the definition of this Objective-C class, taking it from + /// a forward declaration (@class) to a definition (@interface). + void startDefinition(); + + ObjCInterfaceDecl *getSuperClass() const { + // FIXME: Should make sure no callers ever do this. + if (!hasDefinition()) + return 0; + + if (data().ExternallyCompleted) + LoadExternalDefinition(); + + return data().SuperClass; + } + + void setSuperClass(ObjCInterfaceDecl * superCls) { + data().SuperClass = + (superCls && superCls->hasDefinition()) ? superCls->getDefinition() + : superCls; + } + + ObjCCategoryDecl* getCategoryList() const { + // FIXME: Should make sure no callers ever do this. + if (!hasDefinition()) + return 0; + + if (data().ExternallyCompleted) + LoadExternalDefinition(); + + return data().CategoryList; + } + + void setCategoryList(ObjCCategoryDecl *category) { + data().CategoryList = category; + } + + ObjCCategoryDecl* getFirstClassExtension() const; + + ObjCPropertyDecl + *FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId) const; + + /// isSuperClassOf - Return true if this class is the specified class or is a + /// super class of the specified interface class. + bool isSuperClassOf(const ObjCInterfaceDecl *I) const { + // If RHS is derived from LHS it is OK; else it is not OK. + while (I != NULL) { + if (declaresSameEntity(this, I)) + return true; + + I = I->getSuperClass(); + } + return false; + } + + /// isArcWeakrefUnavailable - Checks for a class or one of its super classes + /// to be incompatible with __weak references. Returns true if it is. + bool isArcWeakrefUnavailable() const { + const ObjCInterfaceDecl *Class = this; + while (Class) { + if (Class->hasAttr()) + return true; + Class = Class->getSuperClass(); + } + return false; + } + + /// isObjCRequiresPropertyDefs - Checks that a class or one of its super + /// classes must not be auto-synthesized. Returns class decl. if it must not be; + /// 0, otherwise. + const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const { + const ObjCInterfaceDecl *Class = this; + while (Class) { + if (Class->hasAttr()) + return Class; + Class = Class->getSuperClass(); + } + return 0; + } + + ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName, + ObjCInterfaceDecl *&ClassDeclared); + ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) { + ObjCInterfaceDecl *ClassDeclared; + return lookupInstanceVariable(IVarName, ClassDeclared); + } + + // Lookup a method. First, we search locally. If a method isn't + // found, we search referenced protocols and class categories. + ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance, + bool shallowCategoryLookup= false) const; + ObjCMethodDecl *lookupInstanceMethod(Selector Sel, + bool shallowCategoryLookup = false) const { + return lookupMethod(Sel, true/*isInstance*/, shallowCategoryLookup); + } + ObjCMethodDecl *lookupClassMethod(Selector Sel, + bool shallowCategoryLookup = false) const { + return lookupMethod(Sel, false/*isInstance*/, shallowCategoryLookup); + } + ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName); + + // Lookup a method in the classes implementation hierarchy. + ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel, bool Instance=true); + + SourceLocation getEndOfDefinitionLoc() const { + if (!hasDefinition()) + return getLocation(); + + return data().EndLoc; + } + + void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; } + + void setSuperClassLoc(SourceLocation Loc) { data().SuperClassLoc = Loc; } + SourceLocation getSuperClassLoc() const { return data().SuperClassLoc; } + + /// isImplicitInterfaceDecl - check that this is an implicitly declared + /// ObjCInterfaceDecl node. This is for legacy objective-c @implementation + /// declaration without an @interface declaration. + bool isImplicitInterfaceDecl() const { + return hasDefinition() ? Data->Definition->isImplicit() : isImplicit(); + } + + /// ClassImplementsProtocol - Checks that 'lProto' protocol + /// has been implemented in IDecl class, its super class or categories (if + /// lookupCategory is true). + bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, + bool lookupCategory, + bool RHSIsQualifiedID = false); + + typedef redeclarable_base::redecl_iterator redecl_iterator; + using redeclarable_base::redecls_begin; + using redeclarable_base::redecls_end; + using redeclarable_base::getPreviousDecl; + using redeclarable_base::getMostRecentDecl; + + /// Retrieves the canonical declaration of this Objective-C class. + ObjCInterfaceDecl *getCanonicalDecl() { + return getFirstDeclaration(); + } + const ObjCInterfaceDecl *getCanonicalDecl() const { + return getFirstDeclaration(); + } + + // Low-level accessor + const Type *getTypeForDecl() const { return TypeForDecl; } + void setTypeForDecl(const Type *TD) const { TypeForDecl = TD; } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCInterfaceDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCInterface; } + + friend class ASTReader; + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC +/// instance variables are identical to C. The only exception is Objective-C +/// supports C++ style access control. For example: +/// +/// @interface IvarExample : NSObject +/// { +/// id defaultToProtected; +/// @public: +/// id canBePublic; // same as C++. +/// @protected: +/// id canBeProtected; // same as C++. +/// @package: +/// id canBePackage; // framework visibility (not available in C++). +/// } +/// +class ObjCIvarDecl : public FieldDecl { + virtual void anchor(); + +public: + enum AccessControl { + None, Private, Protected, Public, Package + }; + +private: + ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW, + bool synthesized) + : FieldDecl(ObjCIvar, DC, StartLoc, IdLoc, Id, T, TInfo, BW, + /*Mutable=*/false, /*HasInit=*/false), + NextIvar(0), DeclAccess(ac), Synthesized(synthesized) {} + +public: + static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, QualType T, + TypeSourceInfo *TInfo, + AccessControl ac, Expr *BW = NULL, + bool synthesized=false); + + static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + /// \brief Return the class interface that this ivar is logically contained + /// in; this is either the interface where the ivar was declared, or the + /// interface the ivar is conceptually a part of in the case of synthesized + /// ivars. + const ObjCInterfaceDecl *getContainingInterface() const; + + ObjCIvarDecl *getNextIvar() { return NextIvar; } + const ObjCIvarDecl *getNextIvar() const { return NextIvar; } + void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; } + + void setAccessControl(AccessControl ac) { DeclAccess = ac; } + + AccessControl getAccessControl() const { return AccessControl(DeclAccess); } + + AccessControl getCanonicalAccessControl() const { + return DeclAccess == None ? Protected : AccessControl(DeclAccess); + } + + void setSynthesize(bool synth) { Synthesized = synth; } + bool getSynthesize() const { return Synthesized; } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCIvarDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCIvar; } +private: + /// NextIvar - Next Ivar in the list of ivars declared in class; class's + /// extensions and class's implementation + ObjCIvarDecl *NextIvar; + + // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum + unsigned DeclAccess : 3; + unsigned Synthesized : 1; +}; + + +/// ObjCAtDefsFieldDecl - Represents a field declaration created by an +/// @defs(...). +class ObjCAtDefsFieldDecl : public FieldDecl { + virtual void anchor(); + ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + QualType T, Expr *BW) + : FieldDecl(ObjCAtDefsField, DC, StartLoc, IdLoc, Id, T, + /*TInfo=*/0, // FIXME: Do ObjCAtDefs have declarators ? + BW, /*Mutable=*/false, /*HasInit=*/false) {} + +public: + static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + QualType T, Expr *BW); + + static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCAtDefsFieldDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCAtDefsField; } +}; + +/// ObjCProtocolDecl - Represents a protocol declaration. ObjC protocols +/// declare a pure abstract type (i.e no instance variables are permitted). +/// Protocols originally drew inspiration from C++ pure virtual functions (a C++ +/// feature with nice semantics and lousy syntax:-). Here is an example: +/// +/// @protocol NSDraggingInfo +/// - (NSWindow *)draggingDestinationWindow; +/// - (NSImage *)draggedImage; +/// @end +/// +/// This says that NSDraggingInfo requires two methods and requires everything +/// that the two "referenced protocols" 'refproto1' and 'refproto2' require as +/// well. +/// +/// @interface ImplementsNSDraggingInfo : NSObject +/// @end +/// +/// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and +/// protocols are in distinct namespaces. For example, Cocoa defines both +/// an NSObject protocol and class (which isn't allowed in Java). As a result, +/// protocols are referenced using angle brackets as follows: +/// +/// id anyObjectThatImplementsNSDraggingInfo; +/// +class ObjCProtocolDecl : public ObjCContainerDecl, + public Redeclarable { + virtual void anchor(); + + struct DefinitionData { + // \brief The declaration that defines this protocol. + ObjCProtocolDecl *Definition; + + /// \brief Referenced protocols + ObjCProtocolList ReferencedProtocols; + }; + + DefinitionData *Data; + + DefinitionData &data() const { + assert(Data && "Objective-C protocol has no definition!"); + return *Data; + } + + ObjCProtocolDecl(DeclContext *DC, IdentifierInfo *Id, + SourceLocation nameLoc, SourceLocation atStartLoc, + ObjCProtocolDecl *PrevDecl); + + void allocateDefinitionData(); + + typedef Redeclarable redeclarable_base; + virtual ObjCProtocolDecl *getNextRedeclaration() { + return RedeclLink.getNext(); + } + virtual ObjCProtocolDecl *getPreviousDeclImpl() { + return getPreviousDecl(); + } + virtual ObjCProtocolDecl *getMostRecentDeclImpl() { + return getMostRecentDecl(); + } + +public: + static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC, + IdentifierInfo *Id, + SourceLocation nameLoc, + SourceLocation atStartLoc, + ObjCProtocolDecl *PrevDecl); + + static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + const ObjCProtocolList &getReferencedProtocols() const { + assert(hasDefinition() && "No definition available!"); + return data().ReferencedProtocols; + } + typedef ObjCProtocolList::iterator protocol_iterator; + protocol_iterator protocol_begin() const { + if (!hasDefinition()) + return protocol_iterator(); + + return data().ReferencedProtocols.begin(); + } + protocol_iterator protocol_end() const { + if (!hasDefinition()) + return protocol_iterator(); + + return data().ReferencedProtocols.end(); + } + typedef ObjCProtocolList::loc_iterator protocol_loc_iterator; + protocol_loc_iterator protocol_loc_begin() const { + if (!hasDefinition()) + return protocol_loc_iterator(); + + return data().ReferencedProtocols.loc_begin(); + } + protocol_loc_iterator protocol_loc_end() const { + if (!hasDefinition()) + return protocol_loc_iterator(); + + return data().ReferencedProtocols.loc_end(); + } + unsigned protocol_size() const { + if (!hasDefinition()) + return 0; + + return data().ReferencedProtocols.size(); + } + + /// setProtocolList - Set the list of protocols that this interface + /// implements. + void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num, + const SourceLocation *Locs, ASTContext &C) { + assert(Data && "Protocol is not defined"); + data().ReferencedProtocols.set(List, Num, Locs, C); + } + + ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName); + + // Lookup a method. First, we search locally. If a method isn't + // found, we search referenced protocols and class categories. + ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const; + ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const { + return lookupMethod(Sel, true/*isInstance*/); + } + ObjCMethodDecl *lookupClassMethod(Selector Sel) const { + return lookupMethod(Sel, false/*isInstance*/); + } + + /// \brief Determine whether this protocol has a definition. + bool hasDefinition() const { return Data != 0; } + + /// \brief Retrieve the definition of this protocol, if any. + ObjCProtocolDecl *getDefinition() { + return Data? Data->Definition : 0; + } + + /// \brief Retrieve the definition of this protocol, if any. + const ObjCProtocolDecl *getDefinition() const { + return Data? Data->Definition : 0; + } + + /// \brief Determine whether this particular declaration is also the + /// definition. + bool isThisDeclarationADefinition() const { + return getDefinition() == this; + } + + /// \brief Starts the definition of this Objective-C protocol. + void startDefinition(); + + virtual SourceRange getSourceRange() const LLVM_READONLY { + if (isThisDeclarationADefinition()) + return ObjCContainerDecl::getSourceRange(); + + return SourceRange(getAtStartLoc(), getLocation()); + } + + typedef redeclarable_base::redecl_iterator redecl_iterator; + using redeclarable_base::redecls_begin; + using redeclarable_base::redecls_end; + using redeclarable_base::getPreviousDecl; + using redeclarable_base::getMostRecentDecl; + + /// Retrieves the canonical declaration of this Objective-C protocol. + ObjCProtocolDecl *getCanonicalDecl() { + return getFirstDeclaration(); + } + const ObjCProtocolDecl *getCanonicalDecl() const { + return getFirstDeclaration(); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCProtocolDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCProtocol; } + + friend class ASTReader; + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +/// ObjCCategoryDecl - Represents a category declaration. A category allows +/// you to add methods to an existing class (without subclassing or modifying +/// the original class interface or implementation:-). Categories don't allow +/// you to add instance data. The following example adds "myMethod" to all +/// NSView's within a process: +/// +/// @interface NSView (MyViewMethods) +/// - myMethod; +/// @end +/// +/// Categories also allow you to split the implementation of a class across +/// several files (a feature more naturally supported in C++). +/// +/// Categories were originally inspired by dynamic languages such as Common +/// Lisp and Smalltalk. More traditional class-based languages (C++, Java) +/// don't support this level of dynamism, which is both powerful and dangerous. +/// +class ObjCCategoryDecl : public ObjCContainerDecl { + virtual void anchor(); + + /// Interface belonging to this category + ObjCInterfaceDecl *ClassInterface; + + /// referenced protocols in this category. + ObjCProtocolList ReferencedProtocols; + + /// Next category belonging to this class. + /// FIXME: this should not be a singly-linked list. Move storage elsewhere. + ObjCCategoryDecl *NextClassCategory; + + /// true of class extension has at least one bitfield ivar. + bool HasSynthBitfield : 1; + + /// \brief The location of the category name in this declaration. + SourceLocation CategoryNameLoc; + + /// class extension may have private ivars. + SourceLocation IvarLBraceLoc; + SourceLocation IvarRBraceLoc; + + ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc, + SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc, + IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, + SourceLocation IvarLBraceLoc=SourceLocation(), + SourceLocation IvarRBraceLoc=SourceLocation()) + : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc), + ClassInterface(IDecl), NextClassCategory(0), HasSynthBitfield(false), + CategoryNameLoc(CategoryNameLoc), + IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) { + } +public: + + static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation AtLoc, + SourceLocation ClassNameLoc, + SourceLocation CategoryNameLoc, + IdentifierInfo *Id, + ObjCInterfaceDecl *IDecl, + SourceLocation IvarLBraceLoc=SourceLocation(), + SourceLocation IvarRBraceLoc=SourceLocation()); + static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + ObjCInterfaceDecl *getClassInterface() { return ClassInterface; } + const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; } + + ObjCCategoryImplDecl *getImplementation() const; + void setImplementation(ObjCCategoryImplDecl *ImplD); + + /// setProtocolList - Set the list of protocols that this interface + /// implements. + void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num, + const SourceLocation *Locs, ASTContext &C) { + ReferencedProtocols.set(List, Num, Locs, C); + } + + const ObjCProtocolList &getReferencedProtocols() const { + return ReferencedProtocols; + } + + typedef ObjCProtocolList::iterator protocol_iterator; + protocol_iterator protocol_begin() const {return ReferencedProtocols.begin();} + protocol_iterator protocol_end() const { return ReferencedProtocols.end(); } + unsigned protocol_size() const { return ReferencedProtocols.size(); } + typedef ObjCProtocolList::loc_iterator protocol_loc_iterator; + protocol_loc_iterator protocol_loc_begin() const { + return ReferencedProtocols.loc_begin(); + } + protocol_loc_iterator protocol_loc_end() const { + return ReferencedProtocols.loc_end(); + } + + ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; } + + bool IsClassExtension() const { return getIdentifier() == 0; } + const ObjCCategoryDecl *getNextClassExtension() const; + + bool hasSynthBitfield() const { return HasSynthBitfield; } + void setHasSynthBitfield (bool val) { HasSynthBitfield = val; } + + typedef specific_decl_iterator ivar_iterator; + ivar_iterator ivar_begin() const { + return ivar_iterator(decls_begin()); + } + ivar_iterator ivar_end() const { + return ivar_iterator(decls_end()); + } + unsigned ivar_size() const { + return std::distance(ivar_begin(), ivar_end()); + } + bool ivar_empty() const { + return ivar_begin() == ivar_end(); + } + + SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; } + void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; } + + void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; } + SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; } + void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; } + SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCCategoryDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCCategory; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +class ObjCImplDecl : public ObjCContainerDecl { + virtual void anchor(); + + /// Class interface for this class/category implementation + ObjCInterfaceDecl *ClassInterface; + +protected: + ObjCImplDecl(Kind DK, DeclContext *DC, + ObjCInterfaceDecl *classInterface, + SourceLocation nameLoc, SourceLocation atStartLoc) + : ObjCContainerDecl(DK, DC, + classInterface? classInterface->getIdentifier() : 0, + nameLoc, atStartLoc), + ClassInterface(classInterface) {} + +public: + const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; } + ObjCInterfaceDecl *getClassInterface() { return ClassInterface; } + void setClassInterface(ObjCInterfaceDecl *IFace); + + void addInstanceMethod(ObjCMethodDecl *method) { + // FIXME: Context should be set correctly before we get here. + method->setLexicalDeclContext(this); + addDecl(method); + } + void addClassMethod(ObjCMethodDecl *method) { + // FIXME: Context should be set correctly before we get here. + method->setLexicalDeclContext(this); + addDecl(method); + } + + void addPropertyImplementation(ObjCPropertyImplDecl *property); + + ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId) const; + ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const; + + // Iterator access to properties. + typedef specific_decl_iterator propimpl_iterator; + propimpl_iterator propimpl_begin() const { + return propimpl_iterator(decls_begin()); + } + propimpl_iterator propimpl_end() const { + return propimpl_iterator(decls_end()); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCImplDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstObjCImpl && K <= lastObjCImpl; + } +}; + +/// ObjCCategoryImplDecl - An object of this class encapsulates a category +/// @implementation declaration. If a category class has declaration of a +/// property, its implementation must be specified in the category's +/// @implementation declaration. Example: +/// @interface I @end +/// @interface I(CATEGORY) +/// @property int p1, d1; +/// @end +/// @implementation I(CATEGORY) +/// @dynamic p1,d1; +/// @end +/// +/// ObjCCategoryImplDecl +class ObjCCategoryImplDecl : public ObjCImplDecl { + virtual void anchor(); + + // Category name + IdentifierInfo *Id; + + // Category name location + SourceLocation CategoryNameLoc; + + ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id, + ObjCInterfaceDecl *classInterface, + SourceLocation nameLoc, SourceLocation atStartLoc, + SourceLocation CategoryNameLoc) + : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, nameLoc, atStartLoc), + Id(Id), CategoryNameLoc(CategoryNameLoc) {} +public: + static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC, + IdentifierInfo *Id, + ObjCInterfaceDecl *classInterface, + SourceLocation nameLoc, + SourceLocation atStartLoc, + SourceLocation CategoryNameLoc); + static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + /// getIdentifier - Get the identifier that names the category + /// interface associated with this implementation. + /// FIXME: This is a bad API, we are overriding the NamedDecl::getIdentifier() + /// to mean something different. For example: + /// ((NamedDecl *)SomeCategoryImplDecl)->getIdentifier() + /// returns the class interface name, whereas + /// ((ObjCCategoryImplDecl *)SomeCategoryImplDecl)->getIdentifier() + /// returns the category name. + IdentifierInfo *getIdentifier() const { + return Id; + } + void setIdentifier(IdentifierInfo *II) { Id = II; } + + ObjCCategoryDecl *getCategoryDecl() const; + + SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; } + + /// getName - Get the name of identifier for the class interface associated + /// with this implementation as a StringRef. + // + // FIXME: This is a bad API, we are overriding the NamedDecl::getName, to mean + // something different. + StringRef getName() const { + return Id ? Id->getNameStart() : ""; + } + + /// getNameAsCString - Get the name of identifier for the class + /// interface associated with this implementation as a C string + /// (const char*). + // + // FIXME: Deprecated, move clients to getName(). + const char *getNameAsCString() const { + return Id ? Id->getNameStart() : ""; + } + + /// @brief Get the name of the class associated with this interface. + // + // FIXME: Deprecated, move clients to getName(). + std::string getNameAsString() const { + return getName(); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCCategoryImplDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCCategoryImpl;} + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID); + +/// ObjCImplementationDecl - Represents a class definition - this is where +/// method definitions are specified. For example: +/// +/// @code +/// @implementation MyClass +/// - (void)myMethod { /* do something */ } +/// @end +/// @endcode +/// +/// Typically, instance variables are specified in the class interface, +/// *not* in the implementation. Nevertheless (for legacy reasons), we +/// allow instance variables to be specified in the implementation. When +/// specified, they need to be *identical* to the interface. +/// +class ObjCImplementationDecl : public ObjCImplDecl { + virtual void anchor(); + /// Implementation Class's super class. + ObjCInterfaceDecl *SuperClass; + /// @implementation may have private ivars. + SourceLocation IvarLBraceLoc; + SourceLocation IvarRBraceLoc; + + /// Support for ivar initialization. + /// IvarInitializers - The arguments used to initialize the ivars + CXXCtorInitializer **IvarInitializers; + unsigned NumIvarInitializers; + + /// true if class has a .cxx_[construct,destruct] method. + bool HasCXXStructors : 1; + + /// true of class extension has at least one bitfield ivar. + bool HasSynthBitfield : 1; + + ObjCImplementationDecl(DeclContext *DC, + ObjCInterfaceDecl *classInterface, + ObjCInterfaceDecl *superDecl, + SourceLocation nameLoc, SourceLocation atStartLoc, + SourceLocation IvarLBraceLoc=SourceLocation(), + SourceLocation IvarRBraceLoc=SourceLocation()) + : ObjCImplDecl(ObjCImplementation, DC, classInterface, nameLoc, atStartLoc), + SuperClass(superDecl), IvarLBraceLoc(IvarLBraceLoc), + IvarRBraceLoc(IvarRBraceLoc), + IvarInitializers(0), NumIvarInitializers(0), + HasCXXStructors(false), HasSynthBitfield(false){} +public: + static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC, + ObjCInterfaceDecl *classInterface, + ObjCInterfaceDecl *superDecl, + SourceLocation nameLoc, + SourceLocation atStartLoc, + SourceLocation IvarLBraceLoc=SourceLocation(), + SourceLocation IvarRBraceLoc=SourceLocation()); + + static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + /// init_iterator - Iterates through the ivar initializer list. + typedef CXXCtorInitializer **init_iterator; + + /// init_const_iterator - Iterates through the ivar initializer list. + typedef CXXCtorInitializer * const * init_const_iterator; + + /// init_begin() - Retrieve an iterator to the first initializer. + init_iterator init_begin() { return IvarInitializers; } + /// begin() - Retrieve an iterator to the first initializer. + init_const_iterator init_begin() const { return IvarInitializers; } + + /// init_end() - Retrieve an iterator past the last initializer. + init_iterator init_end() { + return IvarInitializers + NumIvarInitializers; + } + /// end() - Retrieve an iterator past the last initializer. + init_const_iterator init_end() const { + return IvarInitializers + NumIvarInitializers; + } + /// getNumArgs - Number of ivars which must be initialized. + unsigned getNumIvarInitializers() const { + return NumIvarInitializers; + } + + void setNumIvarInitializers(unsigned numNumIvarInitializers) { + NumIvarInitializers = numNumIvarInitializers; + } + + void setIvarInitializers(ASTContext &C, + CXXCtorInitializer ** initializers, + unsigned numInitializers); + + bool hasCXXStructors() const { return HasCXXStructors; } + void setHasCXXStructors(bool val) { HasCXXStructors = val; } + + bool hasSynthBitfield() const { return HasSynthBitfield; } + void setHasSynthBitfield (bool val) { HasSynthBitfield = val; } + + /// getIdentifier - Get the identifier that names the class + /// interface associated with this implementation. + IdentifierInfo *getIdentifier() const { + return getClassInterface()->getIdentifier(); + } + + /// getName - Get the name of identifier for the class interface associated + /// with this implementation as a StringRef. + // + // FIXME: This is a bad API, we are overriding the NamedDecl::getName, to mean + // something different. + StringRef getName() const { + assert(getIdentifier() && "Name is not a simple identifier"); + return getIdentifier()->getName(); + } + + /// getNameAsCString - Get the name of identifier for the class + /// interface associated with this implementation as a C string + /// (const char*). + // + // FIXME: Move to StringRef API. + const char *getNameAsCString() const { + return getName().data(); + } + + /// @brief Get the name of the class associated with this interface. + // + // FIXME: Move to StringRef API. + std::string getNameAsString() const { + return getName(); + } + + const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; } + ObjCInterfaceDecl *getSuperClass() { return SuperClass; } + + void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; } + + void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; } + SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; } + void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; } + SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; } + + typedef specific_decl_iterator ivar_iterator; + ivar_iterator ivar_begin() const { + return ivar_iterator(decls_begin()); + } + ivar_iterator ivar_end() const { + return ivar_iterator(decls_end()); + } + unsigned ivar_size() const { + return std::distance(ivar_begin(), ivar_end()); + } + bool ivar_empty() const { + return ivar_begin() == ivar_end(); + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCImplementationDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCImplementation; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID); + +/// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is +/// declared as @compatibility_alias alias class. +class ObjCCompatibleAliasDecl : public NamedDecl { + virtual void anchor(); + /// Class that this is an alias of. + ObjCInterfaceDecl *AliasedClass; + + ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, + ObjCInterfaceDecl* aliasedClass) + : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {} +public: + static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, IdentifierInfo *Id, + ObjCInterfaceDecl* aliasedClass); + + static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C, + unsigned ID); + + const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; } + ObjCInterfaceDecl *getClassInterface() { return AliasedClass; } + void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCCompatibleAliasDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; } + +}; + +/// ObjCPropertyDecl - Represents one property declaration in an interface. +/// For example: +/// @property (assign, readwrite) int MyProperty; +/// +class ObjCPropertyDecl : public NamedDecl { + virtual void anchor(); +public: + enum PropertyAttributeKind { + OBJC_PR_noattr = 0x00, + OBJC_PR_readonly = 0x01, + OBJC_PR_getter = 0x02, + OBJC_PR_assign = 0x04, + OBJC_PR_readwrite = 0x08, + OBJC_PR_retain = 0x10, + OBJC_PR_copy = 0x20, + OBJC_PR_nonatomic = 0x40, + OBJC_PR_setter = 0x80, + OBJC_PR_atomic = 0x100, + OBJC_PR_weak = 0x200, + OBJC_PR_strong = 0x400, + OBJC_PR_unsafe_unretained = 0x800 + // Adding a property should change NumPropertyAttrsBits + }; + + enum { + /// \brief Number of bits fitting all the property attributes. + NumPropertyAttrsBits = 12 + }; + + enum SetterKind { Assign, Retain, Copy, Weak }; + enum PropertyControl { None, Required, Optional }; +private: + SourceLocation AtLoc; // location of @property + SourceLocation LParenLoc; // location of '(' starting attribute list or null. + TypeSourceInfo *DeclType; + unsigned PropertyAttributes : NumPropertyAttrsBits; + unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits; + // @required/@optional + unsigned PropertyImplementation : 2; + + Selector GetterName; // getter name of NULL if no getter + Selector SetterName; // setter name of NULL if no setter + + ObjCMethodDecl *GetterMethodDecl; // Declaration of getter instance method + ObjCMethodDecl *SetterMethodDecl; // Declaration of setter instance method + ObjCIvarDecl *PropertyIvarDecl; // Synthesize ivar for this property + + ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, + SourceLocation AtLocation, SourceLocation LParenLocation, + TypeSourceInfo *T) + : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation), + LParenLoc(LParenLocation), DeclType(T), + PropertyAttributes(OBJC_PR_noattr), + PropertyAttributesAsWritten(OBJC_PR_noattr), + PropertyImplementation(None), + GetterName(Selector()), + SetterName(Selector()), + GetterMethodDecl(0), SetterMethodDecl(0) , PropertyIvarDecl(0) {} +public: + static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, + IdentifierInfo *Id, SourceLocation AtLocation, + SourceLocation LParenLocation, + TypeSourceInfo *T, + PropertyControl propControl = None); + + static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + SourceLocation getAtLoc() const { return AtLoc; } + void setAtLoc(SourceLocation L) { AtLoc = L; } + + SourceLocation getLParenLoc() const { return LParenLoc; } + void setLParenLoc(SourceLocation L) { LParenLoc = L; } + + TypeSourceInfo *getTypeSourceInfo() const { return DeclType; } + QualType getType() const { return DeclType->getType(); } + void setType(TypeSourceInfo *T) { DeclType = T; } + + PropertyAttributeKind getPropertyAttributes() const { + return PropertyAttributeKind(PropertyAttributes); + } + void setPropertyAttributes(PropertyAttributeKind PRVal) { + PropertyAttributes |= PRVal; + } + + PropertyAttributeKind getPropertyAttributesAsWritten() const { + return PropertyAttributeKind(PropertyAttributesAsWritten); + } + + bool hasWrittenStorageAttribute() const { + return PropertyAttributesAsWritten & (OBJC_PR_assign | OBJC_PR_copy | + OBJC_PR_unsafe_unretained | OBJC_PR_retain | OBJC_PR_strong | + OBJC_PR_weak); + } + + void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) { + PropertyAttributesAsWritten = PRVal; + } + + void makeitReadWriteAttribute(void) { + PropertyAttributes &= ~OBJC_PR_readonly; + PropertyAttributes |= OBJC_PR_readwrite; + } + + // Helper methods for accessing attributes. + + /// isReadOnly - Return true iff the property has a setter. + bool isReadOnly() const { + return (PropertyAttributes & OBJC_PR_readonly); + } + + /// isAtomic - Return true if the property is atomic. + bool isAtomic() const { + return (PropertyAttributes & OBJC_PR_atomic); + } + + /// isRetaining - Return true if the property retains its value. + bool isRetaining() const { + return (PropertyAttributes & + (OBJC_PR_retain | OBJC_PR_strong | OBJC_PR_copy)); + } + + /// getSetterKind - Return the method used for doing assignment in + /// the property setter. This is only valid if the property has been + /// defined to have a setter. + SetterKind getSetterKind() const { + if (PropertyAttributes & OBJC_PR_strong) + return getType()->isBlockPointerType() ? Copy : Retain; + if (PropertyAttributes & OBJC_PR_retain) + return Retain; + if (PropertyAttributes & OBJC_PR_copy) + return Copy; + if (PropertyAttributes & OBJC_PR_weak) + return Weak; + return Assign; + } + + Selector getGetterName() const { return GetterName; } + void setGetterName(Selector Sel) { GetterName = Sel; } + + Selector getSetterName() const { return SetterName; } + void setSetterName(Selector Sel) { SetterName = Sel; } + + ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; } + void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; } + + ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; } + void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; } + + // Related to @optional/@required declared in @protocol + void setPropertyImplementation(PropertyControl pc) { + PropertyImplementation = pc; + } + PropertyControl getPropertyImplementation() const { + return PropertyControl(PropertyImplementation); + } + + void setPropertyIvarDecl(ObjCIvarDecl *Ivar) { + PropertyIvarDecl = Ivar; + } + ObjCIvarDecl *getPropertyIvarDecl() const { + return PropertyIvarDecl; + } + + virtual SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(AtLoc, getLocation()); + } + + /// Lookup a property by name in the specified DeclContext. + static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC, + IdentifierInfo *propertyID); + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCPropertyDecl *D) { return true; } + static bool classofKind(Kind K) { return K == ObjCProperty; } +}; + +/// ObjCPropertyImplDecl - Represents implementation declaration of a property +/// in a class or category implementation block. For example: +/// @synthesize prop1 = ivar1; +/// +class ObjCPropertyImplDecl : public Decl { +public: + enum Kind { + Synthesize, + Dynamic + }; +private: + SourceLocation AtLoc; // location of @synthesize or @dynamic + + /// \brief For @synthesize, the location of the ivar, if it was written in + /// the source code. + /// + /// \code + /// @synthesize int a = b + /// \endcode + SourceLocation IvarLoc; + + /// Property declaration being implemented + ObjCPropertyDecl *PropertyDecl; + + /// Null for @dynamic. Required for @synthesize. + ObjCIvarDecl *PropertyIvarDecl; + + /// Null for @dynamic. Non-null if property must be copy-constructed in getter + Expr *GetterCXXConstructor; + + /// Null for @dynamic. Non-null if property has assignment operator to call + /// in Setter synthesis. + Expr *SetterCXXAssignment; + + ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L, + ObjCPropertyDecl *property, + Kind PK, + ObjCIvarDecl *ivarDecl, + SourceLocation ivarLoc) + : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc), + IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl), + GetterCXXConstructor(0), SetterCXXAssignment(0) { + assert (PK == Dynamic || PropertyIvarDecl); + } + +public: + static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation atLoc, SourceLocation L, + ObjCPropertyDecl *property, + Kind PK, + ObjCIvarDecl *ivarDecl, + SourceLocation ivarLoc); + + static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + virtual SourceRange getSourceRange() const LLVM_READONLY; + + SourceLocation getLocStart() const LLVM_READONLY { return AtLoc; } + void setAtLoc(SourceLocation Loc) { AtLoc = Loc; } + + ObjCPropertyDecl *getPropertyDecl() const { + return PropertyDecl; + } + void setPropertyDecl(ObjCPropertyDecl *Prop) { PropertyDecl = Prop; } + + Kind getPropertyImplementation() const { + return PropertyIvarDecl ? Synthesize : Dynamic; + } + + ObjCIvarDecl *getPropertyIvarDecl() const { + return PropertyIvarDecl; + } + SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; } + + void setPropertyIvarDecl(ObjCIvarDecl *Ivar, + SourceLocation IvarLoc) { + PropertyIvarDecl = Ivar; + this->IvarLoc = IvarLoc; + } + + Expr *getGetterCXXConstructor() const { + return GetterCXXConstructor; + } + void setGetterCXXConstructor(Expr *getterCXXConstructor) { + GetterCXXConstructor = getterCXXConstructor; + } + + Expr *getSetterCXXAssignment() const { + return SetterCXXAssignment; + } + void setSetterCXXAssignment(Expr *setterCXXAssignment) { + SetterCXXAssignment = setterCXXAssignment; + } + + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const ObjCPropertyImplDecl *D) { return true; } + static bool classofKind(Decl::Kind K) { return K == ObjCPropertyImpl; } + + friend class ASTDeclReader; +}; + +} // end namespace clang +#endif diff --git a/cpp/llvm/tools/clang/include/clang/AST/DeclTemplate.h b/cpp/llvm/tools/clang/include/clang/AST/DeclTemplate.h new file mode 100644 index 00000000..36549eab --- /dev/null +++ b/cpp/llvm/tools/clang/include/clang/AST/DeclTemplate.h @@ -0,0 +1,2106 @@ +//===-- DeclTemplate.h - Classes for representing C++ templates -*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the C++ template declaration subclasses. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_DECLTEMPLATE_H +#define LLVM_CLANG_AST_DECLTEMPLATE_H + +#include "clang/AST/DeclCXX.h" +#include "clang/AST/Redeclarable.h" +#include "clang/AST/TemplateBase.h" +#include "llvm/ADT/PointerUnion.h" +#include "llvm/Support/Compiler.h" +#include + +namespace clang { + +class TemplateParameterList; +class TemplateDecl; +class RedeclarableTemplateDecl; +class FunctionTemplateDecl; +class ClassTemplateDecl; +class ClassTemplatePartialSpecializationDecl; +class TemplateTypeParmDecl; +class NonTypeTemplateParmDecl; +class TemplateTemplateParmDecl; +class TypeAliasTemplateDecl; + +/// \brief Stores a template parameter of any kind. +typedef llvm::PointerUnion3 TemplateParameter; + +/// TemplateParameterList - Stores a list of template parameters for a +/// TemplateDecl and its derived classes. +class TemplateParameterList { + /// The location of the 'template' keyword. + SourceLocation TemplateLoc; + + /// The locations of the '<' and '>' angle brackets. + SourceLocation LAngleLoc, RAngleLoc; + + /// The number of template parameters in this template + /// parameter list. + unsigned NumParams; + +protected: + TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc, + NamedDecl **Params, unsigned NumParams, + SourceLocation RAngleLoc); + +public: + static TemplateParameterList *Create(const ASTContext &C, + SourceLocation TemplateLoc, + SourceLocation LAngleLoc, + NamedDecl **Params, + unsigned NumParams, + SourceLocation RAngleLoc); + + /// iterator - Iterates through the template parameters in this list. + typedef NamedDecl** iterator; + + /// const_iterator - Iterates through the template parameters in this list. + typedef NamedDecl* const* const_iterator; + + iterator begin() { return reinterpret_cast(this + 1); } + const_iterator begin() const { + return reinterpret_cast(this + 1); + } + iterator end() { return begin() + NumParams; } + const_iterator end() const { return begin() + NumParams; } + + unsigned size() const { return NumParams; } + + NamedDecl* getParam(unsigned Idx) { + assert(Idx < size() && "Template parameter index out-of-range"); + return begin()[Idx]; + } + + const NamedDecl* getParam(unsigned Idx) const { + assert(Idx < size() && "Template parameter index out-of-range"); + return begin()[Idx]; + } + + /// \brief Returns the minimum number of arguments needed to form a + /// template specialization. This may be fewer than the number of + /// template parameters, if some of the parameters have default + /// arguments or if there is a parameter pack. + unsigned getMinRequiredArguments() const; + + /// \brief Get the depth of this template parameter list in the set of + /// template parameter lists. + /// + /// The first template parameter list in a declaration will have depth 0, + /// the second template parameter list will have depth 1, etc. + unsigned getDepth() const; + + SourceLocation getTemplateLoc() const { return TemplateLoc; } + SourceLocation getLAngleLoc() const { return LAngleLoc; } + SourceLocation getRAngleLoc() const { return RAngleLoc; } + + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(TemplateLoc, RAngleLoc); + } +}; + +/// FixedSizeTemplateParameterList - Stores a list of template parameters for a +/// TemplateDecl and its derived classes. Suitable for creating on the stack. +template +class FixedSizeTemplateParameterList : public TemplateParameterList { + NamedDecl *Params[N]; + +public: + FixedSizeTemplateParameterList(SourceLocation TemplateLoc, + SourceLocation LAngleLoc, + NamedDecl **Params, SourceLocation RAngleLoc) : + TemplateParameterList(TemplateLoc, LAngleLoc, Params, N, RAngleLoc) { + } +}; + +/// \brief A template argument list. +class TemplateArgumentList { + /// \brief The template argument list. + /// + /// The integer value will be non-zero to indicate that this + /// template argument list does own the pointer. + llvm::PointerIntPair Arguments; + + /// \brief The number of template arguments in this template + /// argument list. + unsigned NumArguments; + + TemplateArgumentList(const TemplateArgumentList &Other); // DO NOT IMPL + void operator=(const TemplateArgumentList &Other); // DO NOT IMPL + + TemplateArgumentList(const TemplateArgument *Args, unsigned NumArgs, + bool Owned) + : Arguments(Args, Owned), NumArguments(NumArgs) { } + +public: + /// \brief Type used to indicate that the template argument list itself is a + /// stack object. It does not own its template arguments. + enum OnStackType { OnStack }; + + /// \brief Create a new template argument list that copies the given set of + /// template arguments. + static TemplateArgumentList *CreateCopy(ASTContext &Context, + const TemplateArgument *Args, + unsigned NumArgs); + + /// \brief Construct a new, temporary template argument list on the stack. + /// + /// The template argument list does not own the template arguments + /// provided. + explicit TemplateArgumentList(OnStackType, + const TemplateArgument *Args, unsigned NumArgs) + : Arguments(Args, false), NumArguments(NumArgs) { } + + /// \brief Produces a shallow copy of the given template argument list. + /// + /// This operation assumes that the input argument list outlives it. + /// This takes the list as a pointer to avoid looking like a copy + /// constructor, since this really really isn't safe to use that + /// way. + explicit TemplateArgumentList(const TemplateArgumentList *Other) + : Arguments(Other->data(), false), NumArguments(Other->size()) { } + + /// \brief Retrieve the template argument at a given index. + const TemplateArgument &get(unsigned Idx) const { + assert(Idx < NumArguments && "Invalid template argument index"); + return data()[Idx]; + } + + /// \brief Retrieve the template argument at a given index. + const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); } + + /// \brief Retrieve the number of template arguments in this + /// template argument list. + unsigned size() const { return NumArguments; } + + /// \brief Retrieve a pointer to the template argument list. + const TemplateArgument *data() const { + return Arguments.getPointer(); + } +}; + +//===----------------------------------------------------------------------===// +// Kinds of Templates +//===----------------------------------------------------------------------===// + +/// TemplateDecl - The base class of all kinds of template declarations (e.g., +/// class, function, etc.). The TemplateDecl class stores the list of template +/// parameters and a reference to the templated scoped declaration: the +/// underlying AST node. +class TemplateDecl : public NamedDecl { + virtual void anchor(); +protected: + // This is probably never used. + TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, + DeclarationName Name) + : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(0) { } + + // Construct a template decl with the given name and parameters. + // Used when there is not templated element (tt-params, alias?). + TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, + DeclarationName Name, TemplateParameterList *Params) + : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(Params) { } + + // Construct a template decl with name, parameters, and templated element. + TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, + DeclarationName Name, TemplateParameterList *Params, + NamedDecl *Decl) + : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl), + TemplateParams(Params) { } +public: + /// Get the list of template parameters + TemplateParameterList *getTemplateParameters() const { + return TemplateParams; + } + + /// Get the underlying, templated declaration. + NamedDecl *getTemplatedDecl() const { return TemplatedDecl; } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const TemplateDecl *D) { return true; } + static bool classof(const RedeclarableTemplateDecl *D) { return true; } + static bool classof(const FunctionTemplateDecl *D) { return true; } + static bool classof(const ClassTemplateDecl *D) { return true; } + static bool classof(const TemplateTemplateParmDecl *D) { return true; } + static bool classof(const TypeAliasTemplateDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstTemplate && K <= lastTemplate; + } + + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(TemplateParams->getTemplateLoc(), + TemplatedDecl->getSourceRange().getEnd()); + } + +protected: + NamedDecl *TemplatedDecl; + TemplateParameterList* TemplateParams; + +public: + /// \brief Initialize the underlying templated declaration and + /// template parameters. + void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) { + assert(TemplatedDecl == 0 && "TemplatedDecl already set!"); + assert(TemplateParams == 0 && "TemplateParams already set!"); + TemplatedDecl = templatedDecl; + TemplateParams = templateParams; + } +}; + +/// \brief Provides information about a function template specialization, +/// which is a FunctionDecl that has been explicitly specialization or +/// instantiated from a function template. +class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode { + FunctionTemplateSpecializationInfo(FunctionDecl *FD, + FunctionTemplateDecl *Template, + TemplateSpecializationKind TSK, + const TemplateArgumentList *TemplateArgs, + const ASTTemplateArgumentListInfo *TemplateArgsAsWritten, + SourceLocation POI) + : Function(FD), + Template(Template, TSK - 1), + TemplateArguments(TemplateArgs), + TemplateArgumentsAsWritten(TemplateArgsAsWritten), + PointOfInstantiation(POI) { } + +public: + static FunctionTemplateSpecializationInfo * + Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template, + TemplateSpecializationKind TSK, + const TemplateArgumentList *TemplateArgs, + const TemplateArgumentListInfo *TemplateArgsAsWritten, + SourceLocation POI); + + /// \brief The function template specialization that this structure + /// describes. + FunctionDecl *Function; + + /// \brief The function template from which this function template + /// specialization was generated. + /// + /// The two bits are contain the top 4 values of TemplateSpecializationKind. + llvm::PointerIntPair Template; + + /// \brief The template arguments used to produce the function template + /// specialization from the function template. + const TemplateArgumentList *TemplateArguments; + + /// \brief The template arguments as written in the sources, if provided. + const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten; + + /// \brief The point at which this function template specialization was + /// first instantiated. + SourceLocation PointOfInstantiation; + + /// \brief Retrieve the template from which this function was specialized. + FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); } + + /// \brief Determine what kind of template specialization this is. + TemplateSpecializationKind getTemplateSpecializationKind() const { + return (TemplateSpecializationKind)(Template.getInt() + 1); + } + + bool isExplicitSpecialization() const { + return getTemplateSpecializationKind() == TSK_ExplicitSpecialization; + } + + /// \brief Set the template specialization kind. + void setTemplateSpecializationKind(TemplateSpecializationKind TSK) { + assert(TSK != TSK_Undeclared && + "Cannot encode TSK_Undeclared for a function template specialization"); + Template.setInt(TSK - 1); + } + + /// \brief Retrieve the first point of instantiation of this function + /// template specialization. + /// + /// The point of instantiation may be an invalid source location if this + /// function has yet to be instantiated. + SourceLocation getPointOfInstantiation() const { + return PointOfInstantiation; + } + + /// \brief Set the (first) point of instantiation of this function template + /// specialization. + void setPointOfInstantiation(SourceLocation POI) { + PointOfInstantiation = POI; + } + + void Profile(llvm::FoldingSetNodeID &ID) { + Profile(ID, TemplateArguments->data(), + TemplateArguments->size(), + Function->getASTContext()); + } + + static void + Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs, + unsigned NumTemplateArgs, ASTContext &Context) { + ID.AddInteger(NumTemplateArgs); + for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg) + TemplateArgs[Arg].Profile(ID, Context); + } +}; + +/// \brief Provides information a specialization of a member of a class +/// template, which may be a member function, static data member, +/// member class or member enumeration. +class MemberSpecializationInfo { + // The member declaration from which this member was instantiated, and the + // manner in which the instantiation occurred (in the lower two bits). + llvm::PointerIntPair MemberAndTSK; + + // The point at which this member was first instantiated. + SourceLocation PointOfInstantiation; + +public: + explicit + MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK, + SourceLocation POI = SourceLocation()) + : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) { + assert(TSK != TSK_Undeclared && + "Cannot encode undeclared template specializations for members"); + } + + /// \brief Retrieve the member declaration from which this member was + /// instantiated. + NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); } + + /// \brief Determine what kind of template specialization this is. + TemplateSpecializationKind getTemplateSpecializationKind() const { + return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1); + } + + /// \brief Set the template specialization kind. + void setTemplateSpecializationKind(TemplateSpecializationKind TSK) { + assert(TSK != TSK_Undeclared && + "Cannot encode undeclared template specializations for members"); + MemberAndTSK.setInt(TSK - 1); + } + + /// \brief Retrieve the first point of instantiation of this member. + /// If the point of instantiation is an invalid location, then this member + /// has not yet been instantiated. + SourceLocation getPointOfInstantiation() const { + return PointOfInstantiation; + } + + /// \brief Set the first point of instantiation. + void setPointOfInstantiation(SourceLocation POI) { + PointOfInstantiation = POI; + } +}; + +/// \brief Provides information about a dependent function-template +/// specialization declaration. Since explicit function template +/// specialization and instantiation declarations can only appear in +/// namespace scope, and you can only specialize a member of a +/// fully-specialized class, the only way to get one of these is in +/// a friend declaration like the following: +/// +/// template void foo(T); +/// template class A { +/// friend void foo<>(T); +/// }; +class DependentFunctionTemplateSpecializationInfo { + union { + // Force sizeof to be a multiple of sizeof(void*) so that the + // trailing data is aligned. + void *Aligner; + + struct { + /// The number of potential template candidates. + unsigned NumTemplates; + + /// The number of template arguments. + unsigned NumArgs; + } d; + }; + + /// The locations of the left and right angle brackets. + SourceRange AngleLocs; + + FunctionTemplateDecl * const *getTemplates() const { + return reinterpret_cast(this+1); + } + +public: + DependentFunctionTemplateSpecializationInfo( + const UnresolvedSetImpl &Templates, + const TemplateArgumentListInfo &TemplateArgs); + + /// \brief Returns the number of function templates that this might + /// be a specialization of. + unsigned getNumTemplates() const { + return d.NumTemplates; + } + + /// \brief Returns the i'th template candidate. + FunctionTemplateDecl *getTemplate(unsigned I) const { + assert(I < getNumTemplates() && "template index out of range"); + return getTemplates()[I]; + } + + /// \brief Returns the explicit template arguments that were given. + const TemplateArgumentLoc *getTemplateArgs() const { + return reinterpret_cast( + &getTemplates()[getNumTemplates()]); + } + + /// \brief Returns the number of explicit template arguments that were given. + unsigned getNumTemplateArgs() const { + return d.NumArgs; + } + + /// \brief Returns the nth template argument. + const TemplateArgumentLoc &getTemplateArg(unsigned I) const { + assert(I < getNumTemplateArgs() && "template arg index out of range"); + return getTemplateArgs()[I]; + } + + SourceLocation getLAngleLoc() const { + return AngleLocs.getBegin(); + } + + SourceLocation getRAngleLoc() const { + return AngleLocs.getEnd(); + } +}; + +/// Declaration of a redeclarable template. +class RedeclarableTemplateDecl : public TemplateDecl, + public Redeclarable +{ + typedef Redeclarable redeclarable_base; + virtual RedeclarableTemplateDecl *getNextRedeclaration() { + return RedeclLink.getNext(); + } + virtual RedeclarableTemplateDecl *getPreviousDeclImpl() { + return getPreviousDecl(); + } + virtual RedeclarableTemplateDecl *getMostRecentDeclImpl() { + return getMostRecentDecl(); + } + +protected: + template struct SpecEntryTraits { + typedef EntryType DeclType; + + static DeclType *getMostRecentDecl(EntryType *D) { + return D->getMostRecentDecl(); + } + }; + + template , + typename _DeclType = typename _SETraits::DeclType> + class SpecIterator : public std::iterator { + typedef _SETraits SETraits; + typedef _DeclType DeclType; + + typedef typename llvm::FoldingSet::iterator SetIteratorType; + + SetIteratorType SetIter; + + public: + SpecIterator() : SetIter() {} + SpecIterator(SetIteratorType SetIter) : SetIter(SetIter) {} + + DeclType *operator*() const { + return SETraits::getMostRecentDecl(&*SetIter); + } + DeclType *operator->() const { return **this; } + + SpecIterator &operator++() { ++SetIter; return *this; } + SpecIterator operator++(int) { + SpecIterator tmp(*this); + ++(*this); + return tmp; + } + + bool operator==(SpecIterator Other) const { + return SetIter == Other.SetIter; + } + bool operator!=(SpecIterator Other) const { + return SetIter != Other.SetIter; + } + }; + + template + SpecIterator makeSpecIterator(llvm::FoldingSet &Specs, + bool isEnd) { + return SpecIterator(isEnd ? Specs.end() : Specs.begin()); + } + + template typename SpecEntryTraits::DeclType* + findSpecializationImpl(llvm::FoldingSet &Specs, + const TemplateArgument *Args, unsigned NumArgs, + void *&InsertPos); + + struct CommonBase { + CommonBase() : InstantiatedFromMember(0, false) { } + + /// \brief The template from which this was most + /// directly instantiated (or null). + /// + /// The boolean value indicates whether this template + /// was explicitly specialized. + llvm::PointerIntPair + InstantiatedFromMember; + }; + + /// \brief Pointer to the common data shared by all declarations of this + /// template. + CommonBase *Common; + + /// \brief Retrieves the "common" pointer shared by all (re-)declarations of + /// the same template. Calling this routine may implicitly allocate memory + /// for the common pointer. + CommonBase *getCommonPtr(); + + virtual CommonBase *newCommon(ASTContext &C) = 0; + + // Construct a template decl with name, parameters, and templated element. + RedeclarableTemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, + DeclarationName Name, TemplateParameterList *Params, + NamedDecl *Decl) + : TemplateDecl(DK, DC, L, Name, Params, Decl), Common() { } + +public: + template friend class RedeclarableTemplate; + + /// Retrieves the canonical declaration of this template. + RedeclarableTemplateDecl *getCanonicalDecl() { return getFirstDeclaration(); } + const RedeclarableTemplateDecl *getCanonicalDecl() const { + return getFirstDeclaration(); + } + + /// \brief Determines whether this template was a specialization of a + /// member template. + /// + /// In the following example, the function template \c X::f and the + /// member template \c X::Inner are member specializations. + /// + /// \code + /// template + /// struct X { + /// template void f(T, U); + /// template struct Inner; + /// }; + /// + /// template<> template + /// void X::f(int, T); + /// template<> template + /// struct X::Inner { /* ... */ }; + /// \endcode + bool isMemberSpecialization() { + return getCommonPtr()->InstantiatedFromMember.getInt(); + } + + /// \brief Note that this member template is a specialization. + void setMemberSpecialization() { + assert(getCommonPtr()->InstantiatedFromMember.getPointer() && + "Only member templates can be member template specializations"); + getCommonPtr()->InstantiatedFromMember.setInt(true); + } + + /// \brief Retrieve the member template from which this template was + /// instantiated, or NULL if this template was not instantiated from a + /// member template. + /// + /// A template is instantiated from a member template when the member + /// template itself is part of a class template (or member thereof). For + /// example, given + /// + /// \code + /// template + /// struct X { + /// template void f(T, U); + /// }; + /// + /// void test(X x) { + /// x.f(1, 'a'); + /// }; + /// \endcode + /// + /// \c X::f is a FunctionTemplateDecl that describes the function + /// template + /// + /// \code + /// template void X::f(int, U); + /// \endcode + /// + /// which was itself created during the instantiation of \c X. Calling + /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will + /// retrieve the FunctionTemplateDecl for the original template "f" within + /// the class template \c X, i.e., + /// + /// \code + /// template + /// template + /// void X::f(T, U); + /// \endcode + RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() { + return getCommonPtr()->InstantiatedFromMember.getPointer(); + } + + void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) { + assert(!getCommonPtr()->InstantiatedFromMember.getPointer()); + getCommonPtr()->InstantiatedFromMember.setPointer(TD); + } + + typedef redeclarable_base::redecl_iterator redecl_iterator; + using redeclarable_base::redecls_begin; + using redeclarable_base::redecls_end; + using redeclarable_base::getPreviousDecl; + using redeclarable_base::getMostRecentDecl; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const RedeclarableTemplateDecl *D) { return true; } + static bool classof(const FunctionTemplateDecl *D) { return true; } + static bool classof(const ClassTemplateDecl *D) { return true; } + static bool classof(const TypeAliasTemplateDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate; + } + + friend class ASTReader; + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +template <> struct RedeclarableTemplateDecl:: +SpecEntryTraits { + typedef FunctionDecl DeclType; + + static DeclType * + getMostRecentDecl(FunctionTemplateSpecializationInfo *I) { + return I->Function->getMostRecentDecl(); + } +}; + +/// Declaration of a template function. +class FunctionTemplateDecl : public RedeclarableTemplateDecl { + static void DeallocateCommon(void *Ptr); + +protected: + /// \brief Data that is common to all of the declarations of a given + /// function template. + struct Common : CommonBase { + Common() : InjectedArgs(0) { } + + /// \brief The function template specializations for this function + /// template, including explicit specializations and instantiations. + llvm::FoldingSet Specializations; + + /// \brief The set of "injected" template arguments used within this + /// function template. + /// + /// This pointer refers to the template arguments (there are as + /// many template arguments as template parameaters) for the function + /// template, and is allocated lazily, since most function templates do not + /// require the use of this information. + TemplateArgument *InjectedArgs; + }; + + FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name, + TemplateParameterList *Params, NamedDecl *Decl) + : RedeclarableTemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl) { } + + CommonBase *newCommon(ASTContext &C); + + Common *getCommonPtr() { + return static_cast(RedeclarableTemplateDecl::getCommonPtr()); + } + + friend class FunctionDecl; + + /// \brief Retrieve the set of function template specializations of this + /// function template. + llvm::FoldingSet &getSpecializations() { + return getCommonPtr()->Specializations; + } + + /// \brief Add a specialization of this function template. + /// + /// \param InsertPos Insert position in the FoldingSet, must have been + /// retrieved by an earlier call to findSpecialization(). + void addSpecialization(FunctionTemplateSpecializationInfo* Info, + void *InsertPos); + +public: + /// Get the underlying function declaration of the template. + FunctionDecl *getTemplatedDecl() const { + return static_cast(TemplatedDecl); + } + + /// Returns whether this template declaration defines the primary + /// pattern. + bool isThisDeclarationADefinition() const { + return getTemplatedDecl()->isThisDeclarationADefinition(); + } + + /// \brief Return the specialization with the provided arguments if it exists, + /// otherwise return the insertion point. + FunctionDecl *findSpecialization(const TemplateArgument *Args, + unsigned NumArgs, void *&InsertPos); + + FunctionTemplateDecl *getCanonicalDecl() { + return cast( + RedeclarableTemplateDecl::getCanonicalDecl()); + } + const FunctionTemplateDecl *getCanonicalDecl() const { + return cast( + RedeclarableTemplateDecl::getCanonicalDecl()); + } + + /// \brief Retrieve the previous declaration of this function template, or + /// NULL if no such declaration exists. + FunctionTemplateDecl *getPreviousDecl() { + return cast_or_null( + RedeclarableTemplateDecl::getPreviousDecl()); + } + + /// \brief Retrieve the previous declaration of this function template, or + /// NULL if no such declaration exists. + const FunctionTemplateDecl *getPreviousDecl() const { + return cast_or_null( + RedeclarableTemplateDecl::getPreviousDecl()); + } + + FunctionTemplateDecl *getInstantiatedFromMemberTemplate() { + return cast_or_null( + RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate()); + } + + typedef SpecIterator spec_iterator; + + spec_iterator spec_begin() { + return makeSpecIterator(getSpecializations(), false); + } + + spec_iterator spec_end() { + return makeSpecIterator(getSpecializations(), true); + } + + /// \brief Retrieve the "injected" template arguments that correspond to the + /// template parameters of this function template. + /// + /// Although the C++ standard has no notion of the "injected" template + /// arguments for a function template, the notion is convenient when + /// we need to perform substitutions inside the definition of a function + /// template. + std::pair getInjectedTemplateArgs(); + + /// \brief Create a function template node. + static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, + DeclarationName Name, + TemplateParameterList *Params, + NamedDecl *Decl); + + /// \brief Create an empty function template node. + static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID); + + // Implement isa/cast/dyncast support + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const FunctionTemplateDecl *D) { return true; } + static bool classofKind(Kind K) { return K == FunctionTemplate; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +//===----------------------------------------------------------------------===// +// Kinds of Template Parameters +//===----------------------------------------------------------------------===// + +/// The TemplateParmPosition class defines the position of a template parameter +/// within a template parameter list. Because template parameter can be listed +/// sequentially for out-of-line template members, each template parameter is +/// given a Depth - the nesting of template parameter scopes - and a Position - +/// the occurrence within the parameter list. +/// This class is inheritedly privately by different kinds of template +/// parameters and is not part of the Decl hierarchy. Just a facility. +class TemplateParmPosition { +protected: + // FIXME: This should probably never be called, but it's here as + TemplateParmPosition() + : Depth(0), Position(0) + { /* llvm_unreachable("Cannot create positionless template parameter"); */ } + + TemplateParmPosition(unsigned D, unsigned P) + : Depth(D), Position(P) + { } + + // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for + // position? Maybe? + unsigned Depth; + unsigned Position; + +public: + /// Get the nesting depth of the template parameter. + unsigned getDepth() const { return Depth; } + void setDepth(unsigned D) { Depth = D; } + + /// Get the position of the template parameter within its parameter list. + unsigned getPosition() const { return Position; } + void setPosition(unsigned P) { Position = P; } + + /// Get the index of the template parameter within its parameter list. + unsigned getIndex() const { return Position; } +}; + +/// TemplateTypeParmDecl - Declaration of a template type parameter, +/// e.g., "T" in +/// @code +/// template class vector; +/// @endcode +class TemplateTypeParmDecl : public TypeDecl { + /// \brief Whether this template type parameter was declaration with + /// the 'typename' keyword. If false, it was declared with the + /// 'class' keyword. + bool Typename : 1; + + /// \brief Whether this template type parameter inherited its + /// default argument. + bool InheritedDefault : 1; + + /// \brief The default template argument, if any. + TypeSourceInfo *DefaultArgument; + + TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc, + SourceLocation IdLoc, IdentifierInfo *Id, + bool Typename) + : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename), + InheritedDefault(false), DefaultArgument() { } + + /// Sema creates these on the stack during auto type deduction. + friend class Sema; + +public: + static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC, + SourceLocation KeyLoc, + SourceLocation NameLoc, + unsigned D, unsigned P, + IdentifierInfo *Id, bool Typename, + bool ParameterPack); + static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, + unsigned ID); + + /// \brief Whether this template type parameter was declared with + /// the 'typename' keyword. If not, it was declared with the 'class' + /// keyword. + bool wasDeclaredWithTypename() const { return Typename; } + + /// \brief Determine whether this template parameter has a default + /// argument. + bool hasDefaultArgument() const { return DefaultArgument != 0; } + + /// \brief Retrieve the default argument, if any. + QualType getDefaultArgument() const { return DefaultArgument->getType(); } + + /// \brief Retrieves the default argument's source information, if any. + TypeSourceInfo *getDefaultArgumentInfo() const { return DefaultArgument; } + + /// \brief Retrieves the location of the default argument declaration. + SourceLocation getDefaultArgumentLoc() const; + + /// \brief Determines whether the default argument was inherited + /// from a previous declaration of this template. + bool defaultArgumentWasInherited() const { return InheritedDefault; } + + /// \brief Set the default argument for this template parameter, and + /// whether that default argument was inherited from another + /// declaration. + void setDefaultArgument(TypeSourceInfo *DefArg, bool Inherited) { + DefaultArgument = DefArg; + InheritedDefault = Inherited; + } + + /// \brief Removes the default argument of this template parameter. + void removeDefaultArgument() { + DefaultArgument = 0; + InheritedDefault = false; + } + + /// \brief Set whether this template type parameter was declared with + /// the 'typename' or 'class' keyword. + void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; } + + /// \brief Retrieve the depth of the template parameter. + unsigned getDepth() const; + + /// \brief Retrieve the index of the template parameter. + unsigned getIndex() const; + + /// \brief Returns whether this is a parameter pack. + bool isParameterPack() const; + + SourceRange getSourceRange() const LLVM_READONLY; + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const TemplateTypeParmDecl *D) { return true; } + static bool classofKind(Kind K) { return K == TemplateTypeParm; } +}; + +/// NonTypeTemplateParmDecl - Declares a non-type template parameter, +/// e.g., "Size" in +/// @code +/// template class array { }; +/// @endcode +class NonTypeTemplateParmDecl + : public DeclaratorDecl, protected TemplateParmPosition { + /// \brief The default template argument, if any, and whether or not + /// it was inherited. + llvm::PointerIntPair DefaultArgumentAndInherited; + + // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index + // down here to save memory. + + /// \brief Whether this non-type template parameter is a parameter pack. + bool ParameterPack; + + /// \brief Whether this non-type template parameter is an "expanded" + /// parameter pack, meaning that its type is a pack expansion and we + /// already know the set of types that expansion expands to. + bool ExpandedParameterPack; + + /// \brief The number of types in an expanded parameter pack. + unsigned NumExpandedTypes; + + NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, unsigned D, unsigned P, + IdentifierInfo *Id, QualType T, + bool ParameterPack, TypeSourceInfo *TInfo) + : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc), + TemplateParmPosition(D, P), DefaultArgumentAndInherited(0, false), + ParameterPack(ParameterPack), ExpandedParameterPack(false), + NumExpandedTypes(0) + { } + + NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, unsigned D, unsigned P, + IdentifierInfo *Id, QualType T, + TypeSourceInfo *TInfo, + const QualType *ExpandedTypes, + unsigned NumExpandedTypes, + TypeSourceInfo **ExpandedTInfos); + + friend class ASTDeclReader; + +public: + static NonTypeTemplateParmDecl * + Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, + QualType T, bool ParameterPack, TypeSourceInfo *TInfo); + + static NonTypeTemplateParmDecl * + Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, + QualType T, TypeSourceInfo *TInfo, + const QualType *ExpandedTypes, unsigned NumExpandedTypes, + TypeSourceInfo **ExpandedTInfos); + + static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, + unsigned ID); + static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, + unsigned ID, + unsigned NumExpandedTypes); + + using TemplateParmPosition::getDepth; + using TemplateParmPosition::setDepth; + using TemplateParmPosition::getPosition; + using TemplateParmPosition::setPosition; + using TemplateParmPosition::getIndex; + + SourceRange getSourceRange() const LLVM_READONLY; + + /// \brief Determine whether this template parameter has a default + /// argument. + bool hasDefaultArgument() const { + return DefaultArgumentAndInherited.getPointer() != 0; + } + + /// \brief Retrieve the default argument, if any. + Expr *getDefaultArgument() const { + return DefaultArgumentAndInherited.getPointer(); + } + + /// \brief Retrieve the location of the default argument, if any. + SourceLocation getDefaultArgumentLoc() const; + + /// \brief Determines whether the default argument was inherited + /// from a previous declaration of this template. + bool defaultArgumentWasInherited() const { + return DefaultArgumentAndInherited.getInt(); + } + + /// \brief Set the default argument for this template parameter, and + /// whether that default argument was inherited from another + /// declaration. + void setDefaultArgument(Expr *DefArg, bool Inherited) { + DefaultArgumentAndInherited.setPointer(DefArg); + DefaultArgumentAndInherited.setInt(Inherited); + } + + /// \brief Removes the default argument of this template parameter. + void removeDefaultArgument() { + DefaultArgumentAndInherited.setPointer(0); + DefaultArgumentAndInherited.setInt(false); + } + + /// \brief Whether this parameter is a non-type template parameter pack. + /// + /// If the parameter is a parameter pack, the type may be a + /// \c PackExpansionType. In the following example, the \c Dims parameter + /// is a parameter pack (whose type is 'unsigned'). + /// + /// \code + /// template struct multi_array; + /// \endcode + bool isParameterPack() const { return ParameterPack; } + + /// \brief Whether this parameter is a non-type template parameter pack + /// that has different types at different positions. + /// + /// A parameter pack is an expanded parameter pack when the original + /// parameter pack's type was itself a pack expansion, and that expansion + /// has already been expanded. For example, given: + /// + /// \code + /// template + /// struct X { + /// template + /// struct Y { /* ... */ }; + /// }; + /// \endcode + /// + /// The parameter pack \c Values has a \c PackExpansionType as its type, + /// which expands \c Types. When \c Types is supplied with template arguments + /// by instantiating \c X, the instantiation of \c Values becomes an + /// expanded parameter pack. For example, instantiating + /// \c X results in \c Values being an expanded parameter + /// pack with expansion types \c int and \c unsigned int. + /// + /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions + /// return the expansion types. + bool isExpandedParameterPack() const { return ExpandedParameterPack; } + + /// \brief Retrieves the number of expansion types in an expanded parameter + /// pack. + unsigned getNumExpansionTypes() const { + assert(ExpandedParameterPack && "Not an expansion parameter pack"); + return NumExpandedTypes; + } + + /// \brief Retrieve a particular expansion type within an expanded parameter + /// pack. + QualType getExpansionType(unsigned I) const { + assert(I < NumExpandedTypes && "Out-of-range expansion type index"); + void * const *TypesAndInfos = reinterpret_cast(this + 1); + return QualType::getFromOpaquePtr(TypesAndInfos[2*I]); + } + + /// \brief Retrieve a particular expansion type source info within an + /// expanded parameter pack. + TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const { + assert(I < NumExpandedTypes && "Out-of-range expansion type index"); + void * const *TypesAndInfos = reinterpret_cast(this + 1); + return static_cast(TypesAndInfos[2*I+1]); + } + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const NonTypeTemplateParmDecl *D) { return true; } + static bool classofKind(Kind K) { return K == NonTypeTemplateParm; } +}; + +/// TemplateTemplateParmDecl - Declares a template template parameter, +/// e.g., "T" in +/// @code +/// template