PSARC/2013/188 Clang/LLVM
authorStefan Teleman <stefan.teleman@oracle.com>
Wed, 10 Feb 2016 11:54:12 -0800
changeset 5434 9f55c805ce9d
parent 5428 3c05d530e67e
child 5435 cdf2fdc8edc0
PSARC/2013/188 Clang/LLVM 15777690 clang/llvm compiler infrastructure in Solaris 21851513 severe memory corruption in the LLVM command-line parsing module 22031298 toxic bugs in LLVM ilist/plist end up eliminating entire MachineBasicBlocks 22065707 LLVM SPARC assembler generator emits wrong ELF Section flags 22346218 LLVM's assembler printer on SPARC needs a lot of work 21870061 partial template specializations in CommandLine.h are buggy 21874261 the Google Test Harness doesn't know how to count threads in Solaris 21697459 memory corruption in LLVM IR Code Generator 21341968 llc on SPARC should not need to be passed -march=sparc or -march=sparcv9 21870103 TableGen makes incorrect assumptions about anonymous namespace instantiation 21870087 naming convention for the InputFile key is inconsistent across LLVM utilities 21870099 128 bytes for a filesystem path is definitely not enough 21870067 lli makes incorrect assumptions about anonymous namespace instantiation order 21870065 llc makes incorrect assumptions about anonymous namespace instantiation order 21870283 llvm::sys::Process::GetArgumentVector should overload for std::vector 21874221 clang C++ does not properly initialize the C++ Standard Library's iostreams
components/llvm/Makefile
components/llvm/clang-build.p5m
components/llvm/clang.p5m
components/llvm/cxa_finalize/Makefile
components/llvm/cxa_finalize/cxa_finalize.c
components/llvm/cxa_finalize/cxa_finalize.h
components/llvm/llvm-build.p5m
components/llvm/llvm.license
components/llvm/llvm.p5m
components/llvm/patches/000-AutoRegen.sh.patch
components/llvm/patches/001-Makefile.config.in.patch
components/llvm/patches/002-Makefile.patch
components/llvm/patches/003-Makefile.rules.patch
components/llvm/patches/004-configure.ac.patch
components/llvm/patches/005-Makefile.patch
components/llvm/patches/006-clang-D10272.patch
components/llvm/patches/007-TemplateBase.patch
components/llvm/patches/008-DeclTemplate.patch
components/llvm/patches/009-InitPreprocessor.patch
components/llvm/patches/010-linker-mapfiles.patch
components/llvm/patches/011-gxx-abi-version.patch
components/llvm/patches/012-TypeLocBuilder.cpp.patch
components/llvm/patches/013-llvm-alignments.patch
components/llvm/patches/014-clang-gcc-toolchain.patch
components/llvm/patches/015-llvm-clang-memory-corruption.patch
components/llvm/patches/016-llvm-21851513-memory-corruption.patch
components/llvm/patches/017-lli-21870067.patch
components/llvm/patches/018-21870283-llvm-GetArgumentVector.patch
components/llvm/patches/019-21870099-clang.patch
components/llvm/patches/020-21874221-clang-llvm-sparc-assembler.patch
components/llvm/patches/021-llvm-ilist-iterator-22031298.patch
components/llvm/patches/022-google-test-harness-22643565.patch
components/llvm/patches/023-Makefile.config.in.patch
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Makefile	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,336 @@
+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+
+#
+# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+#
+export PARFAIT_BUILD=no
+COMPILER=gcc
+
+include ../../make-rules/shared-macros.mk
+
+COMPONENT_NAME=		llvm
+COMPONENT_VERSION=	3.6.2
+COMPONENT_PROJECT_URL=	http://llvm.org/
+COMPONENT_SRC=		$(COMPONENT_NAME)
+COMPONENT_BUGDB=	utility/llvm
+
+COMPONENT_SRC=		$(COMPONENT_NAME)-$(COMPONENT_VERSION)
+COMPONENT_SRC_NAME=	$(COMPONENT_SRC).src
+COMPONENT_ARCHIVE=	$(COMPONENT_SRC_NAME).tar.xz
+COMPONENT_ARCHIVE_HASH=	\
+    sha256:f60dc158bfda6822de167e87275848969f0558b3134892ff54fced87e4667b94
+COMPONENT_ARCHIVE_URL=	$(COMPONENT_PROJECT_URL)/releases/$(COMPONENT_VERSION)/$(COMPONENT_ARCHIVE)
+
+TPNO=			24358
+
+COMPONENT_NAME_1 =	clang
+COMPONENT_SRC_1 =	cfe-$(COMPONENT_VERSION).src
+COMPONENT_ARCHIVE_1 =	$(COMPONENT_SRC_1).tar.xz
+COMPONENT_ARCHIVE_HASH_1 = \
+	sha256:ae9180466a23acb426d12444d866b266ff2289b266064d362462e44f8d4699f3
+COMPONENT_ARCHIVE_URL_1 = $(COMPONENT_PROJECT_URL)/releases/$(COMPONENT_VERSION)/$(COMPONENT_ARCHIVE_1)
+
+COMPONENT_POST_UNPACK_ACTION = \
+       ( $(MV) $(COMPONENT_SRC_NAME) $(COMPONENT_SRC) )
+
+COMPONENT_POST_UNPACK_ACTION_1 = \
+	 ( $(RM) -rf $(COMPONENT_SRC)/tools/$(COMPONENT_NAME_1) ; \
+	 $(CP) -rp $(COMPONENT_SRC_1) \
+	    $(COMPONENT_SRC)/tools/$(COMPONENT_NAME_1) )
+
+COMPONENT_PRE_CONFIGURE_ACTION = \
+	 ( cd $(SOURCE_DIR) ; \
+	 $(CHMOD) 0755 ./autoconf/AutoRegen.sh ; \
+	 ./autoconf/AutoRegen.sh )
+
+COMPONENT_POST_BUILD_ACTION = \
+      if test -d $(COMPONENT_DIR)/cxa_finalize ; then \
+      $(GMAKE) -C $(COMPONENT_DIR)/cxa_finalize build ; \
+      fi
+
+COMPONENT_POST_INSTALL_ACTION = \
+	if test -d $(COMPONENT_DIR)/cxa_finalize ; then \
+	$(GMAKE) -C $(COMPONENT_DIR)/cxa_finalize install ; \
+	fi;
+
+include $(WS_MAKE_RULES)/prep.mk
+include $(WS_MAKE_RULES)/configure.mk
+include $(WS_MAKE_RULES)/ips.mk
+
+PATCH_LEVEL := 0
+DEBUG_BUILD := 0
+GCC_VERSION := 4.9
+
+# We need GCC version 4.9, and not another version.
+CC=/usr/gcc/$(GCC_VERSION)/bin/gcc
+CXX=/usr/gcc/$(GCC_VERSION)/bin/g++
+
+# We need the specific C++ runtime that clang/llvm was built and
+# linked with, and not some random and incompatible stuff from
+# /usr/lib.
+LLVM_RUNPATH_32 = /usr/gcc/$(GCC_VERSION)/lib
+LLVM_RUNPATH_64 = /usr/gcc/$(GCC_VERSION)/lib/$(MACH64)
+LLVM_RUNPATH = $(LLVM_RUNPATH_$(BITS))
+
+# -O0 for now. Ideally we want -O2.
+OFLAG="-O0"
+GFLAG=""
+
+ifeq ($(DEBUG_BUILD), 1)
+  OFLAG="-O0"
+  GFLAG="-g3"
+endif
+
+export PATH=/usr/gnu/bin:/usr/xpg4/bin:/usr/bin:/usr/perl5/5.16/bin
+
+# Because LLVM's install target doesn't install everything that
+# needs to be installed.
+EXTRA_INSTALL_BITS=llvm-lto arcmt-test c-arcmt-test c-index-test diagtool
+LLVM_BINDIR=$(BUILD_DIR_64)/Release/bin
+
+ifeq ($(DEBUG_BUILD), 1)
+  LLVM_BINDIR=$(BUILD_DIR_64)/Debug+Asserts+Checks/bin
+endif
+
+COMPONENT_POST_INSTALL_ACTION += \
+	list1='$(EXTRA_INSTALL_BITS)' ; for f in $$list1 ; do \
+	    $(INSTALL) --mode=755 $(LLVM_BINDIR)/$$f $(PROTOUSRBINDIR)/$$f ; \
+	done;
+
+# No ASLR for compilers.
+ASLR_MODE = $(ASLR_DISABLE)
+
+# GCC options used:
+# -ftree-vectorize | -fno-tree-vectorize:
+# Enable/disable loop vectorization in optimizations. For details:
+# https://gcc.gnu.org/projects/tree-ssa/vectorization.html
+# Disabled in debug builds, will be enabled in production/optimized
+# builds at some point in the future..
+#
+# -ftree-slp-vectorize | -fno-tree-slp-vectorize:
+# Enable/disable Basic Block tree vectorization.
+# Less aggressive vectorization than -ftree-vectorize, but useful
+# in case -ftree-slp-vectorize misses some vectorization opportunities.
+# Documentation at the same URL as above.
+# Disabled in debug builds, will be enabled in production/optimized
+# builds at some point in the future.
+#
+# -freorder-blocks | -fno-reorder-blocks
+# Enable/disable BasicBlock reordering as an optimization.
+# Disabled in debug builds, will be enabled in production/optimized
+# builds at some point in the future.
+# Documented here:
+# https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
+#
+# -ftoplevel-reorder | -fno-toplevel-reorder
+# Another BasiBlock depentent optimization option.
+# Disabled in debug builds, will be enabled in production/optimized
+# builds at some point in the future.
+# Documented here:
+# https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
+#
+# -fstack-protector-all:
+# Enable stack smashing (stack corruption) protection and detection.
+# This flag should always be used in conjunction with -Wstack-protector.
+# -Wstack-protector acts at compile-time, -fstack-protector-all acts
+# at runtime. -fstack-protector-all enables linking with libssp.so.
+# This flag carries significant runtime overhead, but is very useful.
+# Always enabled for now. May be removed in the future.
+#
+# -g3: Enable macro visibility in GDB. With just -g, debug builds will
+# not record the expanded values of macros. With -g3, the values of
+# expanded macros will be recorded, and macros will be observable in
+# GDB.
+#
+# -mno-unaligned-doubles:
+# Assume that the code does not make use of misaligned doubles on SPARC.
+# On SPARC, doubles must align on 8. This flag makes GCC assume that
+# there is no misaligned double use in the code, and GCC will not
+# attempt to correct such misaligned loads/stores. If, however, there
+# is such broken code when using this flag, the program will SIGBUS
+# at runtime. This is a very useful debugging flag.
+#
+# -mhard-float:
+# Use hardware floating-point operations when available. Compilers
+# generally make very little use of floating-point, but this is
+# a valuable/low-cost optimization for those rare cases where
+# floating-point operations are used. No-op for quad-floating-point
+# and UltraSPARC-1/2/3 because on those ISA's quad-floating-point
+# ops are always done in software. But quad-floating-point ops in a
+# compiler are virtually non-existent.
+#
+# -mptr32 | -mptr64:
+#  Tell GCC the size of a pointer on SPARC.
+#
+# -mimpure-text:
+# When used in addition to -shared on SPARC, this tells GCC to not pass
+# -z text to the linker when linking a shared object.
+# There is some suspicious interaction happening here between GCC/GAS
+# and the Sun linker. Technically, and in theory, this flag should not
+# be needed when compiling -fPIC. However, extensive documented use
+# and practice has shown that it is indeed needed. The disadvantage
+# of using this flag is that it triggers copy-on-write relocations.
+#
+# -mno-sse3 -mno-ssse3:
+# Do not use SSE3/SSSE3 instructions on Intel. These might not be
+# available. Building for Opteron - which implies SSE2 - is adequate
+# for performance purposes.
+
+CFLAGS = -m$(BITS) $(GFLAG) $(OFLAG) -pthread -std=c99 -fno-strict-aliasing
+CFLAGS += -fno-tree-slp-vectorize -fno-tree-vectorize
+CFLAGS += -fno-reorder-blocks -fno-toplevel-reorder
+CFLAGS += -Wall -Wcast-align -Wno-long-long -Woverflow
+CFLAGS += -Wstack-protector -fdata-sections -fstack-protector-all
+CFLAGS += -fkeep-static-consts -ffunction-sections
+CFLAGS += -Wl,-z -Wl,relax=common -Wl,-z -Wl,relax=secadj
+CFLAGS += -Wl,-z -Wl,relax=transtls -Wl,-R -Wl,$(LLVM_RUNPATH)
+CFLAGS.i386 += -mtune=opteron -mno-sse3 -mno-ssse3 -fno-common
+CFLAGS.sparc += -mtune=ultrasparc -mcpu=ultrasparc -mvis -mhard-float
+CFLAGS.sparc += -mptr$(BITS) -fdata-sections -falign-functions=8
+CFLAGS.sparc += -mno-unaligned-doubles -mimpure-text
+CFLAGS += $(CFLAGS.$(MACH))
+
+CXXFLAGS = -m$(BITS) $(GFLAG) $(OFLAG) -pthread -fno-strict-aliasing
+CXXFLAGS += -fexceptions -frtti -fstack-protector-all
+CXXFLAGS += -fno-tree-vectorize -fno-tree-slp-vectorize
+CXXFLAGS += -fno-reorder-blocks -fno-toplevel-reorder
+CXXFLAGS += -Wall -Wcast-align -Wno-long-long -Woverflow
+CXXFLAGS += -Wstack-protector -fkeep-static-consts
+CXXFLAGS += -std=c++11 -fdata-sections -ffunction-sections
+CXXFLAGS += -Wl,-z -Wl,relax=common -Wl,-z -Wl,relax=secadj
+CXXFLAGS += -Wl,-z -Wl,relax=transtls -Wl,-R -Wl,$(LLVM_RUNPATH)
+CXXFLAGS.sparc += -mptr$(BITS)
+CXXFLAGS += $(CFLAGS.$(MACH))
+
+CPPFLAGS = -D_GNU_SOURCE -DLLVM_SOLARIS -I/usr/gnu/include
+
+ifeq ($(DEBUG_BUILD), 1)
+  CPPFLAGS += -D_DEBUG
+endif
+
+CPPFLAGS += -D_REENTRANT -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64
+CPPFLAGS += -D_FILE_OFFSET_BITS=64 -D__EXTENSIONS__=1
+CPPFLAGS += -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS
+CPPFLAGS += -D__STDC_LIMIT_MACROS -DHAVE_POSIX_MEMALIGN
+CPPFLAGS += -D_GLIBCXX_FULLY_DYNAMIC_STRING=1
+CPPFLAGS.i386 = -DLLVM_INTEL
+CPPFLAGS.sparc = -DLLVM_SPARC
+CPPFLAGS += $(CPPFLAGS.$(MACH))
+
+LLVM_LIBDIR_32 = /usr/lib
+LLVM_LIBDIR_64 = /usr/lib/$(MACH64)
+LLVM_LIBDIR = $(LLVM_LIBDIR_$(BITS))
+
+LLVM_LIBEXECDIR_32 = /usr/libexec
+LLVM_LIBEXECDIR_64 = /usr/libexec/$(MACH64)
+LLVM_LIBEXECDIR = $(LLVM_LIBEXECDIR_$(BITS))
+
+CONFIGURE_SCRIPT = $(SOURCE_DIR)/configure
+CONFIGURE_OPTIONS += CC="$(CC)"
+CONFIGURE_OPTIONS += CXX="$(CXX)"
+CONFIGURE_OPTIONS += CFLAGS="$(CFLAGS)"
+CONFIGURE_OPTIONS += CPPFLAGS="$(CPPFLAGS)"
+CONFIGURE_OPTIONS += CXXFLAGS="$(CXXFLAGS)"
+CONFIGURE_OPTIONS += --libdir=$(LLVM_LIBDIR)
+CONFIGURE_OPTIONS += --libexecdir=$(LLVM_LIBEXECDIR)
+CONFIGURE_OPTIONS += --sharedstatedir=/tmp
+CONFIGURE_OPTIONS += --localstatedir=/var
+CONFIGURE_OPTIONS += --enable-compiler-version-checks=yes
+CONFIGURE_OPTIONS += --enable-clang-static-analyzer=yes
+
+ifeq ($(DEBUG_BUILD), 1)
+  CONFIGURE_OPTIONS += --enable-assertions=yes
+  CONFIGURE_OPTIONS += --enable-optimized=no
+  CONFIGURE_OPTIONS += --enable-expensive-checks=yes
+  CONFIGURE_OPTIONS += --enable-debug-runtime=yes
+  CONFIGURE_OPTIONS += --enable-debug-symbols=yes
+else
+  CONFIGURE_OPTIONS += --enable-assertions=no
+  CONFIGURE_OPTIONS += --enable-optimized=yes
+  CONFIGURE_OPTIONS += --enable-expensive-checks=no
+  CONFIGURE_OPTIONS += --enable-debug-runtime=no
+  CONFIGURE_OPTIONS += --enable-debug-symbols=no
+endif
+
+CONFIGURE_OPTIONS += --enable-keep-symbols=yes
+CONFIGURE_OPTIONS += --enable-jit=yes
+CONFIGURE_OPTIONS += --disable-docs
+CONFIGURE_OPTIONS += --disable-doxygen
+CONFIGURE_OPTIONS += --enable-threads=yes
+CONFIGURE_OPTIONS += --enable-pthreads=yes
+CONFIGURE_OPTIONS += --enable-shared=yes
+CONFIGURE_OPTIONS += --enable-zlib=yes
+CONFIGURE_OPTIONS += --enable-pic=yes
+CONFIGURE_OPTIONS += --enable-timestamps
+CONFIGURE_OPTIONS += --enable-backtraces
+CONFIGURE_OPTIONS += --enable-bindings=auto
+CONFIGURE_OPTIONS += --enable-libffi=yes
+CONFIGURE_OPTIONS += --enable-terminfo=yes
+CONFIGURE_OPTIONS += --enable-ltdl-install=no
+CONFIGURE_OPTIONS += --with-python=$(PYTHON)
+
+ifeq ($(MACH),sparc)
+  CONFIGURE_OPTIONS += --with-extra-ld-options='-lkstat'
+endif
+CONFIGURE_OPTIONS += --with-gcc-toolchain=/usr/gcc/$(GCC_VERSION)
+CONFIGURE_OPTIONS += --with-optimize-option="$(OFLAG) $(GFLAG)"
+
+# Enable the cross-compiler in 3.8.X.
+CONFIGURE_OPTIONS.i386 += --enable-targets="x86"
+CONFIGURE_OPTIONS.sparc += --enable-targets="sparc"
+CONFIGURE_OPTIONS += $(CONFIGURE_OPTIONS.$(MACH))
+
+# Put this here for now until the gpatch problems are resolved.
+COMPONENT_BUILD_ARGS += -j8
+
+# use bash(1) to run the install recipes otherwise clang header installation
+# fails
+COMPONENT_INSTALL_ARGS += SHELL=/bin/bash
+
+# common targets
+configure:	$(CONFIGURE_64)
+
+build:		$(BUILD_64)
+
+install:	$(INSTALL_64)
+
+# There are no master test results yet. TBDL in 3.8.X.
+test:
+	@echo "Tests not yet implemented (wait for 3.8.X)."
+
+system-test:    $(SYSTEM_TESTS_NOT_IMPLEMENTED)
+
+REQUIRED_PACKAGES += developer/gcc-4/gcc-common-49
+REQUIRED_PACKAGES += developer/gnu-binutils
+REQUIRED_PACKAGES += library/libedit
+REQUIRED_PACKAGES += library/libffi
+REQUIRED_PACKAGES += library/libxml2
+REQUIRED_PACKAGES += library/zlib
+REQUIRED_PACKAGES += runtime/python-27
+REQUIRED_PACKAGES += system/core-os
+REQUIRED_PACKAGES += system/header
+REQUIRED_PACKAGES += system/library
+REQUIRED_PACKAGES += system/library/gcc/gcc-c++-runtime-49
+REQUIRED_PACKAGES += system/library/gcc/gcc-gobjcc-runtime-49
+REQUIRED_PACKAGES += system/library/math
+REQUIRED_PACKAGES += system/linker
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/clang-build.p5m	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,501 @@
+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+
+#
+# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+#
+
+set name=pkg.fmri \
+    value=pkg:/developer/llvm/clang-build@$(IPS_COMPONENT_VERSION),$(BUILD_VERSION)
+set name=pkg.summary \
+    value="clang $(COMPONENT_VERSION) Development Files and Libraries"
+set name=com.oracle.info.description \
+    value="clang - The C/C++/Objective-C/Objective-C++ compiler based on the LLVM Compiler Infrastructure Framework - Development Files and Libraries"
+set name=com.oracle.info.tpno value=$(TPNO)
+set name=info.classification value=org.opensolaris.category.2008:Development/C \
+    value=org.opensolaris.category.2008:Development/C++ \
+    value=org.opensolaris.category.2008:Development/GNU \
+    value="org.opensolaris.category.2008:Development/Objective C"
+set name=info.source-url value=$(COMPONENT_ARCHIVE_URL)
+set name=info.upstream-url value=$(COMPONENT_PROJECT_URL)
+set name=org.opensolaris.arc-caseid value=PSARC/2013/188
+set name=org.opensolaris.consolidation value=$(CONSOLIDATION)
+file path=usr/bin/arcmt-test
+file path=usr/bin/c-arcmt-test
+file path=usr/bin/c-index-test
+file path=usr/bin/diagtool
+file path=usr/include/clang-c/BuildSystem.h
+file path=usr/include/clang-c/CXCompilationDatabase.h
+file path=usr/include/clang-c/CXErrorCode.h
+file path=usr/include/clang-c/CXString.h
+file path=usr/include/clang-c/Documentation.h
+file path=usr/include/clang-c/Index.h
+file path=usr/include/clang-c/Platform.h
+file path=usr/include/clang-c/module.modulemap
+file path=usr/include/clang/ARCMigrate/ARCMT.h
+file path=usr/include/clang/ARCMigrate/ARCMTActions.h
+file path=usr/include/clang/ARCMigrate/FileRemapper.h
+file path=usr/include/clang/AST/APValue.h
+file path=usr/include/clang/AST/AST.h
+file path=usr/include/clang/AST/ASTConsumer.h
+file path=usr/include/clang/AST/ASTContext.h
+file path=usr/include/clang/AST/ASTDiagnostic.h
+file path=usr/include/clang/AST/ASTFwd.h
+file path=usr/include/clang/AST/ASTImporter.h
+file path=usr/include/clang/AST/ASTLambda.h
+file path=usr/include/clang/AST/ASTMutationListener.h
+file path=usr/include/clang/AST/ASTTypeTraits.h
+file path=usr/include/clang/AST/ASTUnresolvedSet.h
+file path=usr/include/clang/AST/ASTVector.h
+file path=usr/include/clang/AST/Attr.h
+file path=usr/include/clang/AST/AttrDump.inc
+file path=usr/include/clang/AST/AttrImpl.inc
+file path=usr/include/clang/AST/AttrIterator.h
+file path=usr/include/clang/AST/AttrVisitor.inc
+file path=usr/include/clang/AST/Attrs.inc
+file path=usr/include/clang/AST/BaseSubobject.h
+file path=usr/include/clang/AST/BuiltinTypes.def
+file path=usr/include/clang/AST/CXXInheritance.h
+file path=usr/include/clang/AST/CanonicalType.h
+file path=usr/include/clang/AST/CharUnits.h
+file path=usr/include/clang/AST/Comment.h
+file path=usr/include/clang/AST/CommentBriefParser.h
+file path=usr/include/clang/AST/CommentCommandInfo.inc
+file path=usr/include/clang/AST/CommentCommandList.inc
+file path=usr/include/clang/AST/CommentCommandTraits.h
+file path=usr/include/clang/AST/CommentDiagnostic.h
+file path=usr/include/clang/AST/CommentHTMLNamedCharacterReferences.inc
+file path=usr/include/clang/AST/CommentHTMLTags.inc
+file path=usr/include/clang/AST/CommentHTMLTagsProperties.inc
+file path=usr/include/clang/AST/CommentLexer.h
+file path=usr/include/clang/AST/CommentNodes.inc
+file path=usr/include/clang/AST/CommentParser.h
+file path=usr/include/clang/AST/CommentSema.h
+file path=usr/include/clang/AST/CommentVisitor.h
+file path=usr/include/clang/AST/DataRecursiveASTVisitor.h
+file path=usr/include/clang/AST/Decl.h
+file path=usr/include/clang/AST/DeclAccessPair.h
+file path=usr/include/clang/AST/DeclBase.h
+file path=usr/include/clang/AST/DeclCXX.h
+file path=usr/include/clang/AST/DeclContextInternals.h
+file path=usr/include/clang/AST/DeclFriend.h
+file path=usr/include/clang/AST/DeclGroup.h
+file path=usr/include/clang/AST/DeclLookups.h
+file path=usr/include/clang/AST/DeclNodes.inc
+file path=usr/include/clang/AST/DeclObjC.h
+file path=usr/include/clang/AST/DeclOpenMP.h
+file path=usr/include/clang/AST/DeclTemplate.h
+file path=usr/include/clang/AST/DeclVisitor.h
+file path=usr/include/clang/AST/DeclarationName.h
+file path=usr/include/clang/AST/DependentDiagnostic.h
+file path=usr/include/clang/AST/EvaluatedExprVisitor.h
+file path=usr/include/clang/AST/Expr.h
+file path=usr/include/clang/AST/ExprCXX.h
+file path=usr/include/clang/AST/ExprObjC.h
+file path=usr/include/clang/AST/ExternalASTSource.h
+file path=usr/include/clang/AST/GlobalDecl.h
+file path=usr/include/clang/AST/LambdaCapture.h
+file path=usr/include/clang/AST/Mangle.h
+file path=usr/include/clang/AST/MangleNumberingContext.h
+file path=usr/include/clang/AST/NSAPI.h
+file path=usr/include/clang/AST/NestedNameSpecifier.h
+file path=usr/include/clang/AST/OpenMPClause.h
+file path=usr/include/clang/AST/OperationKinds.h
+file path=usr/include/clang/AST/ParentMap.h
+file path=usr/include/clang/AST/PrettyPrinter.h
+file path=usr/include/clang/AST/RawCommentList.h
+file path=usr/include/clang/AST/RecordLayout.h
+file path=usr/include/clang/AST/RecursiveASTVisitor.h
+file path=usr/include/clang/AST/Redeclarable.h
+file path=usr/include/clang/AST/SelectorLocationsKind.h
+file path=usr/include/clang/AST/Stmt.h
+file path=usr/include/clang/AST/StmtCXX.h
+file path=usr/include/clang/AST/StmtGraphTraits.h
+file path=usr/include/clang/AST/StmtIterator.h
+file path=usr/include/clang/AST/StmtNodes.inc
+file path=usr/include/clang/AST/StmtObjC.h
+file path=usr/include/clang/AST/StmtOpenMP.h
+file path=usr/include/clang/AST/StmtVisitor.h
+file path=usr/include/clang/AST/TemplateBase.h
+file path=usr/include/clang/AST/TemplateName.h
+file path=usr/include/clang/AST/Type.h
+file path=usr/include/clang/AST/TypeLoc.h
+file path=usr/include/clang/AST/TypeLocNodes.def
+file path=usr/include/clang/AST/TypeLocVisitor.h
+file path=usr/include/clang/AST/TypeNodes.def
+file path=usr/include/clang/AST/TypeOrdering.h
+file path=usr/include/clang/AST/TypeVisitor.h
+file path=usr/include/clang/AST/UnresolvedSet.h
+file path=usr/include/clang/AST/VTTBuilder.h
+file path=usr/include/clang/AST/VTableBuilder.h
+file path=usr/include/clang/ASTMatchers/ASTMatchFinder.h
+file path=usr/include/clang/ASTMatchers/ASTMatchers.h
+file path=usr/include/clang/ASTMatchers/ASTMatchersInternal.h
+file path=usr/include/clang/ASTMatchers/ASTMatchersMacros.h
+file path=usr/include/clang/ASTMatchers/Dynamic/Diagnostics.h
+file path=usr/include/clang/ASTMatchers/Dynamic/Parser.h
+file path=usr/include/clang/ASTMatchers/Dynamic/Registry.h
+file path=usr/include/clang/ASTMatchers/Dynamic/VariantValue.h
+file path=usr/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h
+file path=usr/include/clang/Analysis/Analyses/Consumed.h
+file path=usr/include/clang/Analysis/Analyses/Dominators.h
+file path=usr/include/clang/Analysis/Analyses/FormatString.h
+file path=usr/include/clang/Analysis/Analyses/LiveVariables.h
+file path=usr/include/clang/Analysis/Analyses/PostOrderCFGView.h
+file path=usr/include/clang/Analysis/Analyses/PseudoConstantAnalysis.h
+file path=usr/include/clang/Analysis/Analyses/ReachableCode.h
+file path=usr/include/clang/Analysis/Analyses/ThreadSafety.h
+file path=usr/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
+file path=usr/include/clang/Analysis/Analyses/ThreadSafetyLogical.h
+file path=usr/include/clang/Analysis/Analyses/ThreadSafetyOps.def
+file path=usr/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
+file path=usr/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
+file path=usr/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
+file path=usr/include/clang/Analysis/Analyses/UninitializedValues.h
+file path=usr/include/clang/Analysis/AnalysisContext.h
+file path=usr/include/clang/Analysis/AnalysisDiagnostic.h
+file path=usr/include/clang/Analysis/CFG.h
+file path=usr/include/clang/Analysis/CFGStmtMap.h
+file path=usr/include/clang/Analysis/CallGraph.h
+file path=usr/include/clang/Analysis/CodeInjector.h
+file path=usr/include/clang/Analysis/DomainSpecific/CocoaConventions.h
+file path=usr/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h
+file path=usr/include/clang/Analysis/FlowSensitive/DataflowValues.h
+file path=usr/include/clang/Analysis/ProgramPoint.h
+file path=usr/include/clang/Analysis/Support/BumpVector.h
+file path=usr/include/clang/Basic/ABI.h
+file path=usr/include/clang/Basic/AddressSpaces.h
+file path=usr/include/clang/Basic/AllDiagnostics.h
+file path=usr/include/clang/Basic/AttrHasAttributeImpl.inc
+file path=usr/include/clang/Basic/AttrKinds.h
+file path=usr/include/clang/Basic/AttrList.inc
+file path=usr/include/clang/Basic/Attributes.h
+file path=usr/include/clang/Basic/Builtins.def
+file path=usr/include/clang/Basic/Builtins.h
+file path=usr/include/clang/Basic/BuiltinsAArch64.def
+file path=usr/include/clang/Basic/BuiltinsARM.def
+file path=usr/include/clang/Basic/BuiltinsHexagon.def
+file path=usr/include/clang/Basic/BuiltinsLe64.def
+file path=usr/include/clang/Basic/BuiltinsMips.def
+file path=usr/include/clang/Basic/BuiltinsNEON.def
+file path=usr/include/clang/Basic/BuiltinsNVPTX.def
+file path=usr/include/clang/Basic/BuiltinsPPC.def
+file path=usr/include/clang/Basic/BuiltinsR600.def
+file path=usr/include/clang/Basic/BuiltinsX86.def
+file path=usr/include/clang/Basic/BuiltinsXCore.def
+file path=usr/include/clang/Basic/CapturedStmt.h
+file path=usr/include/clang/Basic/CharInfo.h
+file path=usr/include/clang/Basic/CommentOptions.h
+file path=usr/include/clang/Basic/Diagnostic.h
+file path=usr/include/clang/Basic/DiagnosticASTKinds.inc
+file path=usr/include/clang/Basic/DiagnosticAnalysisKinds.inc
+file path=usr/include/clang/Basic/DiagnosticCategories.h
+file path=usr/include/clang/Basic/DiagnosticCommentKinds.inc
+file path=usr/include/clang/Basic/DiagnosticCommonKinds.inc
+file path=usr/include/clang/Basic/DiagnosticDriverKinds.inc
+file path=usr/include/clang/Basic/DiagnosticFrontendKinds.inc
+file path=usr/include/clang/Basic/DiagnosticGroups.inc
+file path=usr/include/clang/Basic/DiagnosticIDs.h
+file path=usr/include/clang/Basic/DiagnosticIndexName.inc
+file path=usr/include/clang/Basic/DiagnosticLexKinds.inc
+file path=usr/include/clang/Basic/DiagnosticOptions.def
+file path=usr/include/clang/Basic/DiagnosticOptions.h
+file path=usr/include/clang/Basic/DiagnosticParseKinds.inc
+file path=usr/include/clang/Basic/DiagnosticSemaKinds.inc
+file path=usr/include/clang/Basic/DiagnosticSerializationKinds.inc
+file path=usr/include/clang/Basic/ExceptionSpecificationType.h
+file path=usr/include/clang/Basic/ExpressionTraits.h
+file path=usr/include/clang/Basic/FileManager.h
+file path=usr/include/clang/Basic/FileSystemOptions.h
+file path=usr/include/clang/Basic/FileSystemStatCache.h
+file path=usr/include/clang/Basic/IdentifierTable.h
+file path=usr/include/clang/Basic/LLVM.h
+file path=usr/include/clang/Basic/Lambda.h
+file path=usr/include/clang/Basic/LangOptions.def
+file path=usr/include/clang/Basic/LangOptions.h
+file path=usr/include/clang/Basic/Linkage.h
+file path=usr/include/clang/Basic/MacroBuilder.h
+file path=usr/include/clang/Basic/Module.h
+file path=usr/include/clang/Basic/ObjCRuntime.h
+file path=usr/include/clang/Basic/OpenCLExtensions.def
+file path=usr/include/clang/Basic/OpenMPKinds.def
+file path=usr/include/clang/Basic/OpenMPKinds.h
+file path=usr/include/clang/Basic/OperatorKinds.def
+file path=usr/include/clang/Basic/OperatorKinds.h
+file path=usr/include/clang/Basic/OperatorPrecedence.h
+file path=usr/include/clang/Basic/PartialDiagnostic.h
+file path=usr/include/clang/Basic/PlistSupport.h
+file path=usr/include/clang/Basic/PrettyStackTrace.h
+file path=usr/include/clang/Basic/SanitizerBlacklist.h
+file path=usr/include/clang/Basic/Sanitizers.def
+file path=usr/include/clang/Basic/Sanitizers.h
+file path=usr/include/clang/Basic/SourceLocation.h
+file path=usr/include/clang/Basic/SourceManager.h
+file path=usr/include/clang/Basic/SourceManagerInternals.h
+file path=usr/include/clang/Basic/Specifiers.h
+file path=usr/include/clang/Basic/TargetBuiltins.h
+file path=usr/include/clang/Basic/TargetCXXABI.h
+file path=usr/include/clang/Basic/TargetInfo.h
+file path=usr/include/clang/Basic/TargetOptions.h
+file path=usr/include/clang/Basic/TemplateKinds.h
+file path=usr/include/clang/Basic/TokenKinds.def
+file path=usr/include/clang/Basic/TokenKinds.h
+file path=usr/include/clang/Basic/TypeTraits.h
+file path=usr/include/clang/Basic/Version.h
+file path=usr/include/clang/Basic/Version.inc
+file path=usr/include/clang/Basic/VersionTuple.h
+file path=usr/include/clang/Basic/VirtualFileSystem.h
+file path=usr/include/clang/Basic/Visibility.h
+file path=usr/include/clang/Basic/arm_neon.inc
+file path=usr/include/clang/CodeGen/BackendUtil.h
+file path=usr/include/clang/CodeGen/CGFunctionInfo.h
+file path=usr/include/clang/CodeGen/CodeGenABITypes.h
+file path=usr/include/clang/CodeGen/CodeGenAction.h
+file path=usr/include/clang/CodeGen/ModuleBuilder.h
+file path=usr/include/clang/Config/config.h
+file path=usr/include/clang/Driver/Action.h
+file path=usr/include/clang/Driver/Compilation.h
+file path=usr/include/clang/Driver/Driver.h
+file path=usr/include/clang/Driver/DriverDiagnostic.h
+file path=usr/include/clang/Driver/Job.h
+file path=usr/include/clang/Driver/Multilib.h
+file path=usr/include/clang/Driver/Options.h
+file path=usr/include/clang/Driver/Options.inc
+file path=usr/include/clang/Driver/Phases.h
+file path=usr/include/clang/Driver/SanitizerArgs.h
+file path=usr/include/clang/Driver/Tool.h
+file path=usr/include/clang/Driver/ToolChain.h
+file path=usr/include/clang/Driver/Types.def
+file path=usr/include/clang/Driver/Types.h
+file path=usr/include/clang/Driver/Util.h
+file path=usr/include/clang/Edit/Commit.h
+file path=usr/include/clang/Edit/EditedSource.h
+file path=usr/include/clang/Edit/EditsReceiver.h
+file path=usr/include/clang/Edit/FileOffset.h
+file path=usr/include/clang/Edit/Rewriters.h
+file path=usr/include/clang/Format/Format.h
+file path=usr/include/clang/Frontend/ASTConsumers.h
+file path=usr/include/clang/Frontend/ASTUnit.h
+file path=usr/include/clang/Frontend/ChainedDiagnosticConsumer.h
+file path=usr/include/clang/Frontend/CodeGenOptions.def
+file path=usr/include/clang/Frontend/CodeGenOptions.h
+file path=usr/include/clang/Frontend/CommandLineSourceLoc.h
+file path=usr/include/clang/Frontend/CompilerInstance.h
+file path=usr/include/clang/Frontend/CompilerInvocation.h
+file path=usr/include/clang/Frontend/DependencyOutputOptions.h
+file path=usr/include/clang/Frontend/DiagnosticRenderer.h
+file path=usr/include/clang/Frontend/FrontendAction.h
+file path=usr/include/clang/Frontend/FrontendActions.h
+file path=usr/include/clang/Frontend/FrontendDiagnostic.h
+file path=usr/include/clang/Frontend/FrontendOptions.h
+file path=usr/include/clang/Frontend/FrontendPluginRegistry.h
+file path=usr/include/clang/Frontend/LangStandard.h
+file path=usr/include/clang/Frontend/LangStandards.def
+file path=usr/include/clang/Frontend/LayoutOverrideSource.h
+file path=usr/include/clang/Frontend/LogDiagnosticPrinter.h
+file path=usr/include/clang/Frontend/MigratorOptions.h
+file path=usr/include/clang/Frontend/MultiplexConsumer.h
+file path=usr/include/clang/Frontend/PreprocessorOutputOptions.h
+file path=usr/include/clang/Frontend/SerializedDiagnosticPrinter.h
+file path=usr/include/clang/Frontend/SerializedDiagnosticReader.h
+file path=usr/include/clang/Frontend/SerializedDiagnostics.h
+file path=usr/include/clang/Frontend/TextDiagnostic.h
+file path=usr/include/clang/Frontend/TextDiagnosticBuffer.h
+file path=usr/include/clang/Frontend/TextDiagnosticPrinter.h
+file path=usr/include/clang/Frontend/Utils.h
+file path=usr/include/clang/Frontend/VerifyDiagnosticConsumer.h
+file path=usr/include/clang/FrontendTool/Utils.h
+file path=usr/include/clang/Index/CommentToXML.h
+file path=usr/include/clang/Index/USRGeneration.h
+file path=usr/include/clang/Lex/CodeCompletionHandler.h
+file path=usr/include/clang/Lex/DirectoryLookup.h
+file path=usr/include/clang/Lex/ExternalPreprocessorSource.h
+file path=usr/include/clang/Lex/HeaderMap.h
+file path=usr/include/clang/Lex/HeaderSearch.h
+file path=usr/include/clang/Lex/HeaderSearchOptions.h
+file path=usr/include/clang/Lex/LexDiagnostic.h
+file path=usr/include/clang/Lex/Lexer.h
+file path=usr/include/clang/Lex/LiteralSupport.h
+file path=usr/include/clang/Lex/MacroArgs.h
+file path=usr/include/clang/Lex/MacroInfo.h
+file path=usr/include/clang/Lex/ModuleLoader.h
+file path=usr/include/clang/Lex/ModuleMap.h
+file path=usr/include/clang/Lex/MultipleIncludeOpt.h
+file path=usr/include/clang/Lex/PPCallbacks.h
+file path=usr/include/clang/Lex/PPConditionalDirectiveRecord.h
+file path=usr/include/clang/Lex/PTHLexer.h
+file path=usr/include/clang/Lex/PTHManager.h
+file path=usr/include/clang/Lex/Pragma.h
+file path=usr/include/clang/Lex/PreprocessingRecord.h
+file path=usr/include/clang/Lex/Preprocessor.h
+file path=usr/include/clang/Lex/PreprocessorLexer.h
+file path=usr/include/clang/Lex/PreprocessorOptions.h
+file path=usr/include/clang/Lex/ScratchBuffer.h
+file path=usr/include/clang/Lex/Token.h
+file path=usr/include/clang/Lex/TokenConcatenation.h
+file path=usr/include/clang/Lex/TokenLexer.h
+file path=usr/include/clang/Parse/AttrParserStringSwitches.inc
+file path=usr/include/clang/Parse/ParseAST.h
+file path=usr/include/clang/Parse/ParseDiagnostic.h
+file path=usr/include/clang/Parse/Parser.h
+file path=usr/include/clang/Rewrite/Core/DeltaTree.h
+file path=usr/include/clang/Rewrite/Core/HTMLRewrite.h
+file path=usr/include/clang/Rewrite/Core/RewriteRope.h
+file path=usr/include/clang/Rewrite/Core/Rewriter.h
+file path=usr/include/clang/Rewrite/Core/TokenRewriter.h
+file path=usr/include/clang/Rewrite/Frontend/ASTConsumers.h
+file path=usr/include/clang/Rewrite/Frontend/FixItRewriter.h
+file path=usr/include/clang/Rewrite/Frontend/FrontendActions.h
+file path=usr/include/clang/Rewrite/Frontend/Rewriters.h
+file path=usr/include/clang/Sema/AnalysisBasedWarnings.h
+file path=usr/include/clang/Sema/AttrParsedAttrImpl.inc
+file path=usr/include/clang/Sema/AttrParsedAttrKinds.inc
+file path=usr/include/clang/Sema/AttrParsedAttrList.inc
+file path=usr/include/clang/Sema/AttrSpellingListIndex.inc
+file path=usr/include/clang/Sema/AttrTemplateInstantiate.inc
+file path=usr/include/clang/Sema/AttributeList.h
+file path=usr/include/clang/Sema/CXXFieldCollector.h
+file path=usr/include/clang/Sema/CodeCompleteConsumer.h
+file path=usr/include/clang/Sema/CodeCompleteOptions.h
+file path=usr/include/clang/Sema/DeclSpec.h
+file path=usr/include/clang/Sema/DelayedDiagnostic.h
+file path=usr/include/clang/Sema/Designator.h
+file path=usr/include/clang/Sema/ExternalSemaSource.h
+file path=usr/include/clang/Sema/IdentifierResolver.h
+file path=usr/include/clang/Sema/Initialization.h
+file path=usr/include/clang/Sema/LocInfoType.h
+file path=usr/include/clang/Sema/Lookup.h
+file path=usr/include/clang/Sema/LoopHint.h
+file path=usr/include/clang/Sema/MultiplexExternalSemaSource.h
+file path=usr/include/clang/Sema/ObjCMethodList.h
+file path=usr/include/clang/Sema/Overload.h
+file path=usr/include/clang/Sema/Ownership.h
+file path=usr/include/clang/Sema/ParsedTemplate.h
+file path=usr/include/clang/Sema/PrettyDeclStackTrace.h
+file path=usr/include/clang/Sema/Scope.h
+file path=usr/include/clang/Sema/ScopeInfo.h
+file path=usr/include/clang/Sema/Sema.h
+file path=usr/include/clang/Sema/SemaConsumer.h
+file path=usr/include/clang/Sema/SemaDiagnostic.h
+file path=usr/include/clang/Sema/SemaFixItUtils.h
+file path=usr/include/clang/Sema/SemaInternal.h
+file path=usr/include/clang/Sema/SemaLambda.h
+file path=usr/include/clang/Sema/Template.h
+file path=usr/include/clang/Sema/TemplateDeduction.h
+file path=usr/include/clang/Sema/TypoCorrection.h
+file path=usr/include/clang/Sema/Weak.h
+file path=usr/include/clang/Serialization/ASTBitCodes.h
+file path=usr/include/clang/Serialization/ASTDeserializationListener.h
+file path=usr/include/clang/Serialization/ASTReader.h
+file path=usr/include/clang/Serialization/ASTWriter.h
+file path=usr/include/clang/Serialization/AttrPCHRead.inc
+file path=usr/include/clang/Serialization/AttrPCHWrite.inc
+file path=usr/include/clang/Serialization/ContinuousRangeMap.h
+file path=usr/include/clang/Serialization/GlobalModuleIndex.h
+file path=usr/include/clang/Serialization/Module.h
+file path=usr/include/clang/Serialization/ModuleManager.h
+file path=usr/include/clang/Serialization/SerializationDiagnostic.h
+file path=usr/include/clang/StaticAnalyzer/Checkers/ClangCheckers.h
+file path=usr/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h
+file path=usr/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h
+file path=usr/include/clang/StaticAnalyzer/Core/Analyses.def
+file path=usr/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
+file path=usr/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+file path=usr/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h
+file path=usr/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
+file path=usr/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h
+file path=usr/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
+file path=usr/include/clang/StaticAnalyzer/Core/Checker.h
+file path=usr/include/clang/StaticAnalyzer/Core/CheckerManager.h
+file path=usr/include/clang/StaticAnalyzer/Core/CheckerOptInfo.h
+file path=usr/include/clang/StaticAnalyzer/Core/CheckerRegistry.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h
+file path=usr/include/clang/StaticAnalyzer/Frontend/AnalysisConsumer.h
+file path=usr/include/clang/StaticAnalyzer/Frontend/CheckerRegistration.h
+file path=usr/include/clang/StaticAnalyzer/Frontend/FrontendActions.h
+file path=usr/include/clang/StaticAnalyzer/Frontend/ModelConsumer.h
+file path=usr/include/clang/Tooling/ArgumentsAdjusters.h
+file path=usr/include/clang/Tooling/CommonOptionsParser.h
+file path=usr/include/clang/Tooling/CompilationDatabase.h
+file path=usr/include/clang/Tooling/CompilationDatabasePluginRegistry.h
+file path=usr/include/clang/Tooling/Core/Replacement.h
+file path=usr/include/clang/Tooling/FileMatchTrie.h
+file path=usr/include/clang/Tooling/JSONCompilationDatabase.h
+file path=usr/include/clang/Tooling/Refactoring.h
+file path=usr/include/clang/Tooling/RefactoringCallbacks.h
+file path=usr/include/clang/Tooling/ReplacementsYaml.h
+file path=usr/include/clang/Tooling/Tooling.h
+file path=usr/lib/$(MACH64)/libclang.a
+file path=usr/lib/$(MACH64)/libclangARCMigrate.a
+file path=usr/lib/$(MACH64)/libclangAST.a
+file path=usr/lib/$(MACH64)/libclangASTMatchers.a
+file path=usr/lib/$(MACH64)/libclangAnalysis.a
+file path=usr/lib/$(MACH64)/libclangBasic.a
+file path=usr/lib/$(MACH64)/libclangCodeGen.a
+file path=usr/lib/$(MACH64)/libclangDriver.a
+file path=usr/lib/$(MACH64)/libclangDynamicASTMatchers.a
+file path=usr/lib/$(MACH64)/libclangEdit.a
+file path=usr/lib/$(MACH64)/libclangFormat.a
+file path=usr/lib/$(MACH64)/libclangFrontend.a
+file path=usr/lib/$(MACH64)/libclangFrontendTool.a
+file path=usr/lib/$(MACH64)/libclangIndex.a
+file path=usr/lib/$(MACH64)/libclangLex.a
+file path=usr/lib/$(MACH64)/libclangParse.a
+file path=usr/lib/$(MACH64)/libclangRewrite.a
+file path=usr/lib/$(MACH64)/libclangRewriteFrontend.a
+file path=usr/lib/$(MACH64)/libclangSema.a
+file path=usr/lib/$(MACH64)/libclangSerialization.a
+file path=usr/lib/$(MACH64)/libclangStaticAnalyzerCheckers.a
+file path=usr/lib/$(MACH64)/libclangStaticAnalyzerCore.a
+file path=usr/lib/$(MACH64)/libclangStaticAnalyzerFrontend.a
+file path=usr/lib/$(MACH64)/libclangTooling.a
+file path=usr/lib/$(MACH64)/libclangToolingCore.a
+license llvm.license license="University of Illinois/NCSA"
+depend type=require fmri=pkg:/developer/llvm/llvm-build
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/clang.p5m	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,107 @@
+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+
+#
+# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+#
+
+set name=pkg.fmri \
+    value=pkg:/developer/llvm/clang@$(IPS_COMPONENT_VERSION),$(BUILD_VERSION)
+set name=pkg.summary \
+    value="clang $(COMPONENT_VERSION) runtime - The clang LLVM Compiler"
+set name=com.oracle.info.description \
+    value="clang - The C/C++/Objective-C/Objective-C++ compiler based on the LLVM Compiler Infrastructure Framework"
+set name=com.oracle.info.tpno value=$(TPNO)
+set name=info.classification value=org.opensolaris.category.2008:Development/C \
+    value=org.opensolaris.category.2008:Development/C++ \
+    value=org.opensolaris.category.2008:Development/GNU \
+    value="org.opensolaris.category.2008:Development/Objective C"
+set name=info.source-url value=$(COMPONENT_ARCHIVE_URL)
+set name=info.upstream-url value=$(COMPONENT_PROJECT_URL)
+set name=org.opensolaris.arc-caseid value=PSARC/2013/188
+set name=org.opensolaris.consolidation value=$(CONSOLIDATION)
+file path=usr/bin/clang
+hardlink path=usr/bin/clang++ target=clang
+file path=usr/bin/clang-check
+file path=usr/bin/clang-format
+file path=usr/bin/clang-tblgen
+file path=usr/lib/$(MACH64)/libclang.so
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/Intrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/__stddef_max_align_t.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/__wmmintrin_aes.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/__wmmintrin_pclmul.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/adxintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/altivec.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/ammintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/arm_acle.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/arm_neon.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx2intrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512bwintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512erintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512fintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512vlbwintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512vlintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avxintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/bmi2intrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/bmiintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/cpuid.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/emmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/f16cintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/float.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/fma4intrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/fmaintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/ia32intrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/immintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/iso646.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/limits.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/lzcntintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/mm3dnow.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/mm_malloc.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/mmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/module.modulemap
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/nmmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/pmmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/popcntintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/prfchwintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/rdseedintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/rtmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/shaintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/smmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/stdalign.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/stdarg.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/stdatomic.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/stdbool.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/stddef.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/stdint.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/stdnoreturn.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/tbmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/tgmath.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/tmmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/unwind.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/vadefs.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/varargs.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/wmmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/x86intrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/xmmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/xopintrin.h
+license llvm.license license="University of Illinois/NCSA"
+depend type=require fmri=pkg:/system/header
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/cxa_finalize/Makefile	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,128 @@
+#
+## CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+#
+
+COMPILER=gcc
+
+include ../../../make-rules/shared-macros.mk
+
+include $(WS_MAKE_RULES)/prep.mk
+include $(WS_MAKE_RULES)/configure.mk
+include $(WS_MAKE_RULES)/ips.mk
+
+COMPONENT_DIR := $(shell pwd)/..
+
+COMPONENT_PRE_BUILD_ACTION = \
+     ( $(MKDIR) build/$(MACH) ; \
+     $(MKDIR) build/$(MACH64) )
+
+OBJECTS = cxa_finalize-32.o cxa_finalize-64.o \
+	  cxa_finalize_pic-32.o cxa_finalize_pic-64.o
+
+include $(WS_MAKE_RULES)/prep.mk
+
+RELEASE_LIST=Debug+Asserts+Checks Debug+Asserts Debug Release+Debug Release Unoptimized
+
+CFLAGS = -g -O2 -std=c99 -Wall -Wextra -Wcast-align
+ARCH = $(shell uname -p)
+
+ifeq ($(ARCH),sparc)
+  CFLAGS += -mtune=ultrasparc -mcpu=ultrasparc -mvis
+endif
+
+ifeq ($(ARCH),i386)
+  CFLAGS += -mtune=opteron -march=opteron
+endif
+
+all:: $(OBJECTS)
+
+cxa_finalize-32.o: cxa_finalize.c
+	$(CC) -m32 $(CFLAGS) -c $< -o $@
+
+cxa_finalize_pic-32.o: cxa_finalize.c
+	$(CC) -m32 $(CFLAGS) -fPIC -c $< -o $@
+
+cxa_finalize-64.o: cxa_finalize.c
+	$(CC) -m64 $(CFLAGS) -c $< -o $@
+
+cxa_finalize_pic-64.o: cxa_finalize.c
+	$(CC) -m64 $(CFLAGS) -fPIC -c $< -o $@
+
+cxa_atexit-32.o: cxa_atexit.c
+	$(CC) -m32 $(CFLAGS) -c $< -o $@
+
+cxa_atexit-64.o: cxa_atexit.c
+	$(CC) -m64 $(CFLAGS) -c $< -o $@
+
+clean::
+	rm -f $(OBJECTS)
+
+check::	build
+	$(MKDIR) build/$(MACH)
+	$(MKDIR) build/$(MACH64)
+
+build: all
+
+install: build
+	$(MKDIR) $(PROTOUSRLIBDIR)/clang
+	$(MKDIR) $(PROTOUSRLIBDIR)/clang/$(MACH64)
+	$(CP) cxa_finalize-32.o \
+	  $(PROTOUSRLIBDIR)/clang/cxa_finalize.o
+	$(CP) cxa_finalize_pic-32.o \
+	  $(PROTOUSRLIBDIR)/clang/cxa_finalize_pic.o
+	$(CP) cxa_finalize-64.o \
+	  $(PROTOUSRLIBDIR)/clang/$(MACH64)/cxa_finalize.o
+	$(CP) cxa_finalize_pic-64.o \
+	  $(PROTOUSRLIBDIR)/clang/$(MACH64)/cxa_finalize_pic.o
+	list='$(RELEASE_LIST)'; for f in $$list; do \
+	     if test -d $(BUILD_DIR_32)/$$f/lib ; then \
+	     echo "Installing cxa_finalize in $(BUILD_DIR_32)/$$f/lib..." ; \
+	     $(MKDIR)  $(BUILD_DIR_32)/$$f/lib/$(MACH64) ; \
+	     $(CP) cxa_finalize-32.o \
+	     $(BUILD_DIR_32)/$$f/lib/cxa_finalize.o ; \
+	     $(CP) cxa_finalize_pic-32.o \
+	     $(BUILD_DIR_32)/$$f/lib/cxa_finalize_pic.o ; \
+	     $(CP) cxa_finalize-64.o \
+	     $(BUILD_DIR_32)/$$f/lib/$(MACH64)/cxa_finalize.o ; \
+	     $(CP) cxa_finalize_pic-64.o \
+	     $(BUILD_DIR_32)/$$f/lib/$(MACH64)/cxa_finalize_pic.o ; \
+	     fi ; \
+	     if test -d $(BUILD_DIR_64)/$$f/lib ; then \
+	     echo "Installing cxa_finalize in $(BUILD_DIR_64)/$$f/lib..." ; \
+	     $(MKDIR)  $(BUILD_DIR_64)/$$f/lib/$(MACH64) ; \
+	     $(CP) cxa_finalize-32.o \
+	     $(BUILD_DIR_64)/$$f/lib/cxa_finalize.o ; \
+	     $(CP) cxa_finalize_pic-32.o \
+	     $(BUILD_DIR_64)/$$f/lib/cxa_finalize_pic.o ; \
+	     $(CP) cxa_finalize-64.o \
+	     $(BUILD_DIR_64)/$$f/lib/$(MACH64)/cxa_finalize.o ; \
+	     $(CP) cxa_finalize_pic-64.o \
+	     $(BUILD_DIR_64)/$$f/lib/$(MACH64)/cxa_finalize_pic.o ; \
+	     fi ; \
+	     done
+
+test:
+	echo "No tests."
+
+system-test:
+	echo "No system tests."
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/cxa_finalize/cxa_finalize.c	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,280 @@
+/*
+ * CDDL HEADER START
+ *
+ * The contents of this file are subject to the terms of the
+ * Common Development and Distribution License (the "License").
+ * You may not use this file except in compliance with the License.
+ *
+ * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+ * or http://www.opensolaris.org/os/licensing.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ *
+ * When distributing Covered Code, include this CDDL HEADER in each
+ * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+ * If applicable, add the following below this CDDL HEADER, with the
+ * fields enclosed by brackets "[]" replaced with your own identifying
+ * information: Portions Copyright [yyyy] [name of copyright owner]
+ *
+ * CDDL HEADER END
+ *
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ */
+
+/* A Solaris implementation of the Itanium C++ ABI __cxa_atexit
+ * and __cxa_finalize functions.
+ */
+
+#include <stdlib.h>
+#include <pthread.h>
+
+#include "cxa_finalize.h"
+
+#define __CXA_FUNC_CALLBACK 0
+#define __CXA_FUNC_DONE     1
+#define __CXA_ATEXIT_CHUNK  64
+
+#define __DSO_TYPE_DESTRUCTOR 1
+#define __DSO_TYPE_DLCLOSE    2
+
+#define __DSO_SCOPE_LOCAL  4
+#define __DSO_SCOPE_GLOBAL 8
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct __cxxabi_atexit {
+  void (*cxa_func)(void*);
+  uint32_t type;
+  uint32_t dso_type;
+  uint32_t dso_scope;
+  void* arg;
+  void* dso;
+} cxxabi_atexit;
+
+typedef struct __cxxabi_atexit_list {
+  uint32_t size;
+  uint32_t nelem;
+  cxxabi_atexit* list;
+} cxxabi_atexit_list;
+
+__attribute__((__visibility__("hidden")))
+extern void* __dso_handle;
+
+static cxxabi_atexit_list _list;
+static pthread_mutex_t _mtx = PTHREAD_MUTEX_INITIALIZER;
+static uint32_t _registered = 0;
+static uint32_t _initialized = 0;
+
+static int __register_with_atexit(const cxxabi_atexit* cxa);
+static int __init_cxxabi_list(cxxabi_atexit** list);
+static int __resize_cxxabi_list(const cxxabi_atexit* oldlist, uint32_t nelem,
+                                cxxabi_atexit** newlist, uint32_t newsize);
+void __cxa_atexit_callback(void);
+static void __attribute__((destructor)) __do_cleanup(void);
+
+int __init_cxxabi_list(cxxabi_atexit** list) {
+  cxxabi_atexit* __p =
+    (cxxabi_atexit *) malloc (__CXA_ATEXIT_CHUNK * sizeof(cxxabi_atexit));
+
+  if (__p == NULL)
+    return -1;
+
+  *list = __p;
+  return 0;
+}
+
+int __resize_cxxabi_list(const cxxabi_atexit* oldlist, uint32_t nelem,
+                         cxxabi_atexit** newlist, uint32_t newsize) {
+  register cxxabi_atexit* __p =
+    (cxxabi_atexit *) malloc (newsize * sizeof(cxxabi_atexit));
+
+  if (__p == NULL)
+    return -1;
+
+  const cxxabi_atexit* __l = oldlist;
+
+  for (uint32_t i = 0; i < nelem; ++i)
+    *(__p + i) = *(__l + i);
+
+  *newlist = __p;
+
+  return 0;
+}
+
+int __register_with_atexit(const cxxabi_atexit* cxa) {
+  int ret = 0;
+
+  if (cxa == NULL)
+    return -1;
+
+  pthread_mutex_lock(&_mtx);
+
+  if (_initialized == 0) {
+    _list.nelem = 0;
+
+    ret = __init_cxxabi_list(&_list.list);
+
+    if (ret == -1) {
+      pthread_mutex_unlock(&_mtx);
+      return ret;
+    }
+
+    _list.size = __CXA_ATEXIT_CHUNK;
+    _initialized = 1;
+  }
+
+  if (_list.nelem == _list.size) {
+    uint32_t newsize = _list.size * 2;
+    cxxabi_atexit* __p;
+
+    ret = __resize_cxxabi_list(_list.list, _list.nelem, &__p, newsize);
+
+    if (ret == -1) {
+      free (_list.list);
+      _list.list = NULL;
+      _list.size = 0;
+      _list.nelem = 0;
+      pthread_mutex_unlock(&_mtx);
+      return ret;
+    }
+
+    _list.list = __p;
+    _list.size = newsize;
+  }
+
+  if (_registered == 0) {
+    ret = atexit(__cxa_atexit_callback);
+    _registered = (ret == 0);
+  }
+
+  if (_registered != 1) {
+    free (_list.list);
+    _list.list = NULL;
+    _list.size = 0;
+    _list.nelem = 0;
+    pthread_mutex_unlock(&_mtx);
+    return ret;
+  }
+
+  register cxxabi_atexit* __p = _list.list + _list.nelem;
+  *__p = *cxa;
+  ++_list.nelem;
+
+  pthread_mutex_unlock(&_mtx);
+  return ret;
+}
+
+void __cxa_atexit_callback(void) {
+  cxxabi_atexit* __e = _list.list + (_list.nelem - 1);
+  cxxabi_atexit* __p = __e;
+
+  if (__p == NULL)
+    return;
+
+  /* destroy local scope objects first */
+  for (int i = _list.nelem; i > 0; --i) {
+    if ((__p->type == __CXA_FUNC_CALLBACK) && 
+        (__p->dso_scope == __DSO_SCOPE_LOCAL)) {
+      __p->type = __CXA_FUNC_DONE;
+      __p->cxa_func(__p->arg);
+    }
+    --__p;
+  }
+
+  __p = __e;
+
+  /* destroy global scope objects last */
+  for (int i = _list.nelem; i > 0; --i) {
+    if ((__p->type == __CXA_FUNC_CALLBACK) &&
+        (__p->dso_scope == __DSO_SCOPE_GLOBAL)) {
+      __p->type = __CXA_FUNC_DONE;
+      __p->cxa_func(__p->arg);
+    }
+    --__p;
+  }
+}
+
+int __cxa_atexit(void (*destructor)(void*), void* arg, void* dso) {
+  cxxabi_atexit cxa;
+
+  cxa.type = __CXA_FUNC_CALLBACK;
+
+  /* get dso_type from dso object itself */
+  cxa.dso_type = __DSO_TYPE_DESTRUCTOR;
+
+  /* get dso scope from dso object */
+  cxa.dso_scope = __DSO_SCOPE_GLOBAL;
+  cxa.cxa_func = destructor;
+  cxa.arg = arg;
+  cxa.dso = dso;
+
+  return __register_with_atexit(&cxa);
+}
+
+int __cxa_finalize(void* dso) {
+  uint32_t i;
+  pthread_mutex_lock(&_mtx);
+
+  if (_initialized == 0) {
+    pthread_mutex_unlock(&_mtx);
+    return -1;
+  }
+
+  cxxabi_atexit* __p = _list.list;
+  pthread_mutex_unlock(&_mtx);
+
+  if (__p == NULL)
+    return -1;
+
+  if (dso == NULL) {
+    __p = _list.list + (_list.nelem - 1);
+
+    pthread_mutex_lock(&_mtx);
+
+    for (i = _list.nelem; i > 0; --i) {
+      if (__p->type == __CXA_FUNC_DONE) {
+        --__p;
+        continue;
+      }
+
+      uint32_t __type = __p->type;
+      __p->type = __CXA_FUNC_DONE;
+      pthread_mutex_unlock(&_mtx);
+
+      if (__type == __CXA_FUNC_CALLBACK)
+        __p->cxa_func(__p->arg);
+
+      --__p;
+      pthread_mutex_lock(&_mtx);
+    }
+
+    pthread_mutex_unlock(&_mtx);
+  } else {
+    i = 0;
+    do {
+      if (__p->dso == dso) {
+        pthread_mutex_lock(&_mtx);
+        uint32_t __type = __p->type;
+        __p->type = __CXA_FUNC_DONE;
+        pthread_mutex_unlock(&_mtx);
+
+        if (__type == __CXA_FUNC_CALLBACK)
+          __p->cxa_func(__p->arg);
+      }
+      ++__p; ++i;
+    } while (i < _list.nelem);
+  }
+
+  return 0;
+}
+
+void __attribute__((destructor)) __do_cleanup(void) {
+  __cxa_finalize(__dso_handle);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/cxa_finalize/cxa_finalize.h	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,49 @@
+/*
+ * CDDL HEADER START
+ *
+ * The contents of this file are subject to the terms of the
+ * Common Development and Distribution License (the "License").
+ * You may not use this file except in compliance with the License.
+ *
+ * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+ * or http://www.opensolaris.org/os/licensing.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ *
+ * When distributing Covered Code, include this CDDL HEADER in each
+ * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+ * If applicable, add the following below this CDDL HEADER, with the
+ * fields enclosed by brackets "[]" replaced with your own identifying
+ * information: Portions Copyright [yyyy] [name of copyright owner]
+ *
+ * CDDL HEADER END
+ *
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ */
+
+/* A Solaris implementation of the Itanium C++ ABI __cxa_atexit
+ * and __cxa_finalize functions.
+ */
+
+#ifndef _CXA_FINALIZE_H
+#define _CXA_FINALIZE_H
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int
+__attribute__((visibility("hidden")))
+__cxa_atexit(void (*destructor)(void*), void* arg, void* dso);
+
+extern int __attribute__((visibility("hidden")))
+__cxa_finalize(void* dso);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _CXA_FINALIZE_H */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/llvm-build.p5m	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,745 @@
+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+
+#
+# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+#
+
+set name=pkg.fmri \
+    value=pkg:/developer/llvm/llvm-build@$(IPS_COMPONENT_VERSION),$(BUILD_VERSION)
+set name=pkg.summary \
+    value="LLVM $(COMPONENT_VERSION) Development Files and Libraries"
+set name=com.oracle.info.description \
+    value="LLVM - The Low Level Virtual Machine Compiler Infrastructure Framework - Development Files and Libraries"
+set name=com.oracle.info.tpno value=$(TPNO)
+set name=info.classification value=org.opensolaris.category.2008:Development/C \
+    value=org.opensolaris.category.2008:Development/C++ \
+    value=org.opensolaris.category.2008:Development/GNU \
+    value="org.opensolaris.category.2008:Development/Objective C"
+set name=info.source-url value=$(COMPONENT_ARCHIVE_URL)
+set name=info.upstream-url value=$(COMPONENT_PROJECT_URL)
+set name=org.opensolaris.arc-caseid value=PSARC/2013/188
+set name=org.opensolaris.consolidation value=$(CONSOLIDATION)
+file path=usr/include/llvm-c/Analysis.h
+file path=usr/include/llvm-c/BitReader.h
+file path=usr/include/llvm-c/BitWriter.h
+file path=usr/include/llvm-c/Core.h
+file path=usr/include/llvm-c/Disassembler.h
+file path=usr/include/llvm-c/ExecutionEngine.h
+file path=usr/include/llvm-c/IRReader.h
+file path=usr/include/llvm-c/Initialization.h
+file path=usr/include/llvm-c/LinkTimeOptimizer.h
+file path=usr/include/llvm-c/Linker.h
+file path=usr/include/llvm-c/Object.h
+file path=usr/include/llvm-c/Support.h
+file path=usr/include/llvm-c/Target.h
+file path=usr/include/llvm-c/TargetMachine.h
+file path=usr/include/llvm-c/Transforms/IPO.h
+file path=usr/include/llvm-c/Transforms/PassManagerBuilder.h
+file path=usr/include/llvm-c/Transforms/Scalar.h
+file path=usr/include/llvm-c/Transforms/Vectorize.h
+file path=usr/include/llvm-c/lto.h
+file path=usr/include/llvm/ADT/APFloat.h
+file path=usr/include/llvm/ADT/APInt.h
+file path=usr/include/llvm/ADT/APSInt.h
+file path=usr/include/llvm/ADT/ArrayRef.h
+file path=usr/include/llvm/ADT/BitVector.h
+file path=usr/include/llvm/ADT/DAGDeltaAlgorithm.h
+file path=usr/include/llvm/ADT/DeltaAlgorithm.h
+file path=usr/include/llvm/ADT/DenseMap.h
+file path=usr/include/llvm/ADT/DenseMapInfo.h
+file path=usr/include/llvm/ADT/DenseSet.h
+file path=usr/include/llvm/ADT/DepthFirstIterator.h
+file path=usr/include/llvm/ADT/EquivalenceClasses.h
+file path=usr/include/llvm/ADT/FoldingSet.h
+file path=usr/include/llvm/ADT/GraphTraits.h
+file path=usr/include/llvm/ADT/Hashing.h
+file path=usr/include/llvm/ADT/ImmutableList.h
+file path=usr/include/llvm/ADT/ImmutableMap.h
+file path=usr/include/llvm/ADT/ImmutableSet.h
+file path=usr/include/llvm/ADT/IndexedMap.h
+file path=usr/include/llvm/ADT/IntEqClasses.h
+file path=usr/include/llvm/ADT/IntervalMap.h
+file path=usr/include/llvm/ADT/IntrusiveRefCntPtr.h
+file path=usr/include/llvm/ADT/MapVector.h
+file path=usr/include/llvm/ADT/None.h
+file path=usr/include/llvm/ADT/Optional.h
+file path=usr/include/llvm/ADT/PackedVector.h
+file path=usr/include/llvm/ADT/PointerIntPair.h
+file path=usr/include/llvm/ADT/PointerUnion.h
+file path=usr/include/llvm/ADT/PostOrderIterator.h
+file path=usr/include/llvm/ADT/PriorityQueue.h
+file path=usr/include/llvm/ADT/SCCIterator.h
+file path=usr/include/llvm/ADT/STLExtras.h
+file path=usr/include/llvm/ADT/ScopedHashTable.h
+file path=usr/include/llvm/ADT/SetOperations.h
+file path=usr/include/llvm/ADT/SetVector.h
+file path=usr/include/llvm/ADT/SmallBitVector.h
+file path=usr/include/llvm/ADT/SmallPtrSet.h
+file path=usr/include/llvm/ADT/SmallSet.h
+file path=usr/include/llvm/ADT/SmallString.h
+file path=usr/include/llvm/ADT/SmallVector.h
+file path=usr/include/llvm/ADT/SparseBitVector.h
+file path=usr/include/llvm/ADT/SparseMultiSet.h
+file path=usr/include/llvm/ADT/SparseSet.h
+file path=usr/include/llvm/ADT/Statistic.h
+file path=usr/include/llvm/ADT/StringExtras.h
+file path=usr/include/llvm/ADT/StringMap.h
+file path=usr/include/llvm/ADT/StringRef.h
+file path=usr/include/llvm/ADT/StringSet.h
+file path=usr/include/llvm/ADT/StringSwitch.h
+file path=usr/include/llvm/ADT/TinyPtrVector.h
+file path=usr/include/llvm/ADT/Triple.h
+file path=usr/include/llvm/ADT/Twine.h
+file path=usr/include/llvm/ADT/UniqueVector.h
+file path=usr/include/llvm/ADT/VariadicFunction.h
+file path=usr/include/llvm/ADT/edit_distance.h
+file path=usr/include/llvm/ADT/ilist.h
+file path=usr/include/llvm/ADT/ilist_node.h
+file path=usr/include/llvm/ADT/iterator.h
+file path=usr/include/llvm/ADT/iterator_range.h
+file path=usr/include/llvm/Analysis/AliasAnalysis.h
+file path=usr/include/llvm/Analysis/AliasSetTracker.h
+file path=usr/include/llvm/Analysis/AssumptionCache.h
+file path=usr/include/llvm/Analysis/BlockFrequencyInfo.h
+file path=usr/include/llvm/Analysis/BlockFrequencyInfoImpl.h
+file path=usr/include/llvm/Analysis/BranchProbabilityInfo.h
+file path=usr/include/llvm/Analysis/CFG.h
+file path=usr/include/llvm/Analysis/CFGPrinter.h
+file path=usr/include/llvm/Analysis/CGSCCPassManager.h
+file path=usr/include/llvm/Analysis/CallGraph.h
+file path=usr/include/llvm/Analysis/CallGraphSCCPass.h
+file path=usr/include/llvm/Analysis/CallPrinter.h
+file path=usr/include/llvm/Analysis/CaptureTracking.h
+file path=usr/include/llvm/Analysis/CodeMetrics.h
+file path=usr/include/llvm/Analysis/ConstantFolding.h
+file path=usr/include/llvm/Analysis/ConstantsScanner.h
+file path=usr/include/llvm/Analysis/DOTGraphTraitsPass.h
+file path=usr/include/llvm/Analysis/DependenceAnalysis.h
+file path=usr/include/llvm/Analysis/DomPrinter.h
+file path=usr/include/llvm/Analysis/DominanceFrontier.h
+file path=usr/include/llvm/Analysis/DominanceFrontierImpl.h
+file path=usr/include/llvm/Analysis/FunctionTargetTransformInfo.h
+file path=usr/include/llvm/Analysis/IVUsers.h
+file path=usr/include/llvm/Analysis/InlineCost.h
+file path=usr/include/llvm/Analysis/InstructionSimplify.h
+file path=usr/include/llvm/Analysis/Interval.h
+file path=usr/include/llvm/Analysis/IntervalIterator.h
+file path=usr/include/llvm/Analysis/IntervalPartition.h
+file path=usr/include/llvm/Analysis/JumpInstrTableInfo.h
+file path=usr/include/llvm/Analysis/LazyCallGraph.h
+file path=usr/include/llvm/Analysis/LazyValueInfo.h
+file path=usr/include/llvm/Analysis/LibCallAliasAnalysis.h
+file path=usr/include/llvm/Analysis/LibCallSemantics.h
+file path=usr/include/llvm/Analysis/Lint.h
+file path=usr/include/llvm/Analysis/Loads.h
+file path=usr/include/llvm/Analysis/LoopInfo.h
+file path=usr/include/llvm/Analysis/LoopInfoImpl.h
+file path=usr/include/llvm/Analysis/LoopIterator.h
+file path=usr/include/llvm/Analysis/LoopPass.h
+file path=usr/include/llvm/Analysis/MemoryBuiltins.h
+file path=usr/include/llvm/Analysis/MemoryDependenceAnalysis.h
+file path=usr/include/llvm/Analysis/PHITransAddr.h
+file path=usr/include/llvm/Analysis/Passes.h
+file path=usr/include/llvm/Analysis/PostDominators.h
+file path=usr/include/llvm/Analysis/PtrUseVisitor.h
+file path=usr/include/llvm/Analysis/RegionInfo.h
+file path=usr/include/llvm/Analysis/RegionInfoImpl.h
+file path=usr/include/llvm/Analysis/RegionIterator.h
+file path=usr/include/llvm/Analysis/RegionPass.h
+file path=usr/include/llvm/Analysis/RegionPrinter.h
+file path=usr/include/llvm/Analysis/ScalarEvolution.h
+file path=usr/include/llvm/Analysis/ScalarEvolutionExpander.h
+file path=usr/include/llvm/Analysis/ScalarEvolutionExpressions.h
+file path=usr/include/llvm/Analysis/ScalarEvolutionNormalization.h
+file path=usr/include/llvm/Analysis/SparsePropagation.h
+file path=usr/include/llvm/Analysis/TargetFolder.h
+file path=usr/include/llvm/Analysis/TargetTransformInfo.h
+file path=usr/include/llvm/Analysis/Trace.h
+file path=usr/include/llvm/Analysis/ValueTracking.h
+file path=usr/include/llvm/AsmParser/Parser.h
+file path=usr/include/llvm/Bitcode/BitCodes.h
+file path=usr/include/llvm/Bitcode/BitcodeWriterPass.h
+file path=usr/include/llvm/Bitcode/BitstreamReader.h
+file path=usr/include/llvm/Bitcode/BitstreamWriter.h
+file path=usr/include/llvm/Bitcode/LLVMBitCodes.h
+file path=usr/include/llvm/Bitcode/ReaderWriter.h
+file path=usr/include/llvm/CodeGen/Analysis.h
+file path=usr/include/llvm/CodeGen/AsmPrinter.h
+file path=usr/include/llvm/CodeGen/CalcSpillWeights.h
+file path=usr/include/llvm/CodeGen/CallingConvLower.h
+file path=usr/include/llvm/CodeGen/CommandFlags.h
+file path=usr/include/llvm/CodeGen/DAGCombine.h
+file path=usr/include/llvm/CodeGen/DFAPacketizer.h
+file path=usr/include/llvm/CodeGen/DIE.h
+file path=usr/include/llvm/CodeGen/EdgeBundles.h
+file path=usr/include/llvm/CodeGen/FastISel.h
+file path=usr/include/llvm/CodeGen/ForwardControlFlowIntegrity.h
+file path=usr/include/llvm/CodeGen/FunctionLoweringInfo.h
+file path=usr/include/llvm/CodeGen/GCMetadata.h
+file path=usr/include/llvm/CodeGen/GCMetadataPrinter.h
+file path=usr/include/llvm/CodeGen/GCStrategy.h
+file path=usr/include/llvm/CodeGen/GCs.h
+file path=usr/include/llvm/CodeGen/ISDOpcodes.h
+file path=usr/include/llvm/CodeGen/IntrinsicLowering.h
+file path=usr/include/llvm/CodeGen/JumpInstrTables.h
+file path=usr/include/llvm/CodeGen/LatencyPriorityQueue.h
+file path=usr/include/llvm/CodeGen/LexicalScopes.h
+file path=usr/include/llvm/CodeGen/LinkAllAsmWriterComponents.h
+file path=usr/include/llvm/CodeGen/LinkAllCodegenComponents.h
+file path=usr/include/llvm/CodeGen/LiveInterval.h
+file path=usr/include/llvm/CodeGen/LiveIntervalAnalysis.h
+file path=usr/include/llvm/CodeGen/LiveIntervalUnion.h
+file path=usr/include/llvm/CodeGen/LivePhysRegs.h
+file path=usr/include/llvm/CodeGen/LiveRangeEdit.h
+file path=usr/include/llvm/CodeGen/LiveRegMatrix.h
+file path=usr/include/llvm/CodeGen/LiveStackAnalysis.h
+file path=usr/include/llvm/CodeGen/LiveVariables.h
+file path=usr/include/llvm/CodeGen/MachORelocation.h
+file path=usr/include/llvm/CodeGen/MachineBasicBlock.h
+file path=usr/include/llvm/CodeGen/MachineBlockFrequencyInfo.h
+file path=usr/include/llvm/CodeGen/MachineBranchProbabilityInfo.h
+file path=usr/include/llvm/CodeGen/MachineCombinerPattern.h
+file path=usr/include/llvm/CodeGen/MachineConstantPool.h
+file path=usr/include/llvm/CodeGen/MachineDominanceFrontier.h
+file path=usr/include/llvm/CodeGen/MachineDominators.h
+file path=usr/include/llvm/CodeGen/MachineFrameInfo.h
+file path=usr/include/llvm/CodeGen/MachineFunction.h
+file path=usr/include/llvm/CodeGen/MachineFunctionAnalysis.h
+file path=usr/include/llvm/CodeGen/MachineFunctionPass.h
+file path=usr/include/llvm/CodeGen/MachineInstr.h
+file path=usr/include/llvm/CodeGen/MachineInstrBuilder.h
+file path=usr/include/llvm/CodeGen/MachineInstrBundle.h
+file path=usr/include/llvm/CodeGen/MachineJumpTableInfo.h
+file path=usr/include/llvm/CodeGen/MachineLoopInfo.h
+file path=usr/include/llvm/CodeGen/MachineMemOperand.h
+file path=usr/include/llvm/CodeGen/MachineModuleInfo.h
+file path=usr/include/llvm/CodeGen/MachineModuleInfoImpls.h
+file path=usr/include/llvm/CodeGen/MachineOperand.h
+file path=usr/include/llvm/CodeGen/MachinePassRegistry.h
+file path=usr/include/llvm/CodeGen/MachinePostDominators.h
+file path=usr/include/llvm/CodeGen/MachineRegionInfo.h
+file path=usr/include/llvm/CodeGen/MachineRegisterInfo.h
+file path=usr/include/llvm/CodeGen/MachineSSAUpdater.h
+file path=usr/include/llvm/CodeGen/MachineScheduler.h
+file path=usr/include/llvm/CodeGen/MachineTraceMetrics.h
+file path=usr/include/llvm/CodeGen/MachineValueType.h
+file path=usr/include/llvm/CodeGen/PBQP/CostAllocator.h
+file path=usr/include/llvm/CodeGen/PBQP/Graph.h
+file path=usr/include/llvm/CodeGen/PBQP/Math.h
+file path=usr/include/llvm/CodeGen/PBQP/ReductionRules.h
+file path=usr/include/llvm/CodeGen/PBQP/Solution.h
+file path=usr/include/llvm/CodeGen/PBQPRAConstraint.h
+file path=usr/include/llvm/CodeGen/Passes.h
+file path=usr/include/llvm/CodeGen/PseudoSourceValue.h
+file path=usr/include/llvm/CodeGen/RegAllocPBQP.h
+file path=usr/include/llvm/CodeGen/RegAllocRegistry.h
+file path=usr/include/llvm/CodeGen/RegisterClassInfo.h
+file path=usr/include/llvm/CodeGen/RegisterPressure.h
+file path=usr/include/llvm/CodeGen/RegisterScavenging.h
+file path=usr/include/llvm/CodeGen/ResourcePriorityQueue.h
+file path=usr/include/llvm/CodeGen/RuntimeLibcalls.h
+file path=usr/include/llvm/CodeGen/ScheduleDAG.h
+file path=usr/include/llvm/CodeGen/ScheduleDAGInstrs.h
+file path=usr/include/llvm/CodeGen/ScheduleDFS.h
+file path=usr/include/llvm/CodeGen/ScheduleHazardRecognizer.h
+file path=usr/include/llvm/CodeGen/SchedulerRegistry.h
+file path=usr/include/llvm/CodeGen/ScoreboardHazardRecognizer.h
+file path=usr/include/llvm/CodeGen/SelectionDAG.h
+file path=usr/include/llvm/CodeGen/SelectionDAGISel.h
+file path=usr/include/llvm/CodeGen/SelectionDAGNodes.h
+file path=usr/include/llvm/CodeGen/SlotIndexes.h
+file path=usr/include/llvm/CodeGen/StackMapLivenessAnalysis.h
+file path=usr/include/llvm/CodeGen/StackMaps.h
+file path=usr/include/llvm/CodeGen/StackProtector.h
+file path=usr/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h
+file path=usr/include/llvm/CodeGen/TargetSchedule.h
+file path=usr/include/llvm/CodeGen/ValueTypes.h
+file path=usr/include/llvm/CodeGen/ValueTypes.td
+file path=usr/include/llvm/CodeGen/VirtRegMap.h
+file path=usr/include/llvm/Config/AsmParsers.def
+file path=usr/include/llvm/Config/AsmPrinters.def
+file path=usr/include/llvm/Config/Disassemblers.def
+file path=usr/include/llvm/Config/Targets.def
+file path=usr/include/llvm/Config/config.h
+file path=usr/include/llvm/Config/llvm-config.h
+file path=usr/include/llvm/DebugInfo/DIContext.h
+file path=usr/include/llvm/DebugInfo/DWARFAbbreviationDeclaration.h
+file path=usr/include/llvm/DebugInfo/DWARFAcceleratorTable.h
+file path=usr/include/llvm/DebugInfo/DWARFCompileUnit.h
+file path=usr/include/llvm/DebugInfo/DWARFContext.h
+file path=usr/include/llvm/DebugInfo/DWARFDebugAbbrev.h
+file path=usr/include/llvm/DebugInfo/DWARFDebugArangeSet.h
+file path=usr/include/llvm/DebugInfo/DWARFDebugAranges.h
+file path=usr/include/llvm/DebugInfo/DWARFDebugFrame.h
+file path=usr/include/llvm/DebugInfo/DWARFDebugInfoEntry.h
+file path=usr/include/llvm/DebugInfo/DWARFDebugLine.h
+file path=usr/include/llvm/DebugInfo/DWARFDebugLoc.h
+file path=usr/include/llvm/DebugInfo/DWARFDebugRangeList.h
+file path=usr/include/llvm/DebugInfo/DWARFFormValue.h
+file path=usr/include/llvm/DebugInfo/DWARFRelocMap.h
+file path=usr/include/llvm/DebugInfo/DWARFSection.h
+file path=usr/include/llvm/DebugInfo/DWARFTypeUnit.h
+file path=usr/include/llvm/DebugInfo/DWARFUnit.h
+file path=usr/include/llvm/ExecutionEngine/ExecutionEngine.h
+file path=usr/include/llvm/ExecutionEngine/GenericValue.h
+file path=usr/include/llvm/ExecutionEngine/Interpreter.h
+file path=usr/include/llvm/ExecutionEngine/JITEventListener.h
+file path=usr/include/llvm/ExecutionEngine/MCJIT.h
+file path=usr/include/llvm/ExecutionEngine/OProfileWrapper.h
+file path=usr/include/llvm/ExecutionEngine/ObjectCache.h
+file path=usr/include/llvm/ExecutionEngine/RTDyldMemoryManager.h
+file path=usr/include/llvm/ExecutionEngine/RuntimeDyld.h
+file path=usr/include/llvm/ExecutionEngine/RuntimeDyldChecker.h
+file path=usr/include/llvm/ExecutionEngine/SectionMemoryManager.h
+file path=usr/include/llvm/IR/Argument.h
+file path=usr/include/llvm/IR/AssemblyAnnotationWriter.h
+file path=usr/include/llvm/IR/Attributes.h
+file path=usr/include/llvm/IR/AutoUpgrade.h
+file path=usr/include/llvm/IR/BasicBlock.h
+file path=usr/include/llvm/IR/CFG.h
+file path=usr/include/llvm/IR/CallSite.h
+file path=usr/include/llvm/IR/CallingConv.h
+file path=usr/include/llvm/IR/Comdat.h
+file path=usr/include/llvm/IR/Constant.h
+file path=usr/include/llvm/IR/ConstantFolder.h
+file path=usr/include/llvm/IR/ConstantRange.h
+file path=usr/include/llvm/IR/Constants.h
+file path=usr/include/llvm/IR/DIBuilder.h
+file path=usr/include/llvm/IR/DataLayout.h
+file path=usr/include/llvm/IR/DebugInfo.h
+file path=usr/include/llvm/IR/DebugLoc.h
+file path=usr/include/llvm/IR/DerivedTypes.h
+file path=usr/include/llvm/IR/DiagnosticInfo.h
+file path=usr/include/llvm/IR/DiagnosticPrinter.h
+file path=usr/include/llvm/IR/Dominators.h
+file path=usr/include/llvm/IR/Function.h
+file path=usr/include/llvm/IR/GVMaterializer.h
+file path=usr/include/llvm/IR/GetElementPtrTypeIterator.h
+file path=usr/include/llvm/IR/GlobalAlias.h
+file path=usr/include/llvm/IR/GlobalObject.h
+file path=usr/include/llvm/IR/GlobalValue.h
+file path=usr/include/llvm/IR/GlobalVariable.h
+file path=usr/include/llvm/IR/IRBuilder.h
+file path=usr/include/llvm/IR/IRPrintingPasses.h
+file path=usr/include/llvm/IR/InlineAsm.h
+file path=usr/include/llvm/IR/InstIterator.h
+file path=usr/include/llvm/IR/InstVisitor.h
+file path=usr/include/llvm/IR/InstrTypes.h
+file path=usr/include/llvm/IR/Instruction.def
+file path=usr/include/llvm/IR/Instruction.h
+file path=usr/include/llvm/IR/Instructions.h
+file path=usr/include/llvm/IR/IntrinsicInst.h
+file path=usr/include/llvm/IR/Intrinsics.gen
+file path=usr/include/llvm/IR/Intrinsics.h
+file path=usr/include/llvm/IR/Intrinsics.td
+file path=usr/include/llvm/IR/IntrinsicsAArch64.td
+file path=usr/include/llvm/IR/IntrinsicsARM.td
+file path=usr/include/llvm/IR/IntrinsicsHexagon.td
+file path=usr/include/llvm/IR/IntrinsicsMips.td
+file path=usr/include/llvm/IR/IntrinsicsNVVM.td
+file path=usr/include/llvm/IR/IntrinsicsPowerPC.td
+file path=usr/include/llvm/IR/IntrinsicsR600.td
+file path=usr/include/llvm/IR/IntrinsicsX86.td
+file path=usr/include/llvm/IR/IntrinsicsXCore.td
+file path=usr/include/llvm/IR/LLVMContext.h
+file path=usr/include/llvm/IR/LegacyPassManager.h
+file path=usr/include/llvm/IR/LegacyPassManagers.h
+file path=usr/include/llvm/IR/LegacyPassNameParser.h
+file path=usr/include/llvm/IR/MDBuilder.h
+file path=usr/include/llvm/IR/Mangler.h
+file path=usr/include/llvm/IR/Metadata.def
+file path=usr/include/llvm/IR/Metadata.h
+file path=usr/include/llvm/IR/MetadataTracking.h
+file path=usr/include/llvm/IR/Module.h
+file path=usr/include/llvm/IR/NoFolder.h
+file path=usr/include/llvm/IR/OperandTraits.h
+file path=usr/include/llvm/IR/Operator.h
+file path=usr/include/llvm/IR/PassManager.h
+file path=usr/include/llvm/IR/PassManagerInternal.h
+file path=usr/include/llvm/IR/PatternMatch.h
+file path=usr/include/llvm/IR/PredIteratorCache.h
+file path=usr/include/llvm/IR/Statepoint.h
+file path=usr/include/llvm/IR/SymbolTableListTraits.h
+file path=usr/include/llvm/IR/TrackingMDRef.h
+file path=usr/include/llvm/IR/Type.h
+file path=usr/include/llvm/IR/TypeBuilder.h
+file path=usr/include/llvm/IR/TypeFinder.h
+file path=usr/include/llvm/IR/Use.h
+file path=usr/include/llvm/IR/UseListOrder.h
+file path=usr/include/llvm/IR/User.h
+file path=usr/include/llvm/IR/Value.h
+file path=usr/include/llvm/IR/ValueHandle.h
+file path=usr/include/llvm/IR/ValueMap.h
+file path=usr/include/llvm/IR/ValueSymbolTable.h
+file path=usr/include/llvm/IR/Verifier.h
+file path=usr/include/llvm/IRReader/IRReader.h
+file path=usr/include/llvm/InitializePasses.h
+file path=usr/include/llvm/LTO/LTOCodeGenerator.h
+file path=usr/include/llvm/LTO/LTOModule.h
+file path=usr/include/llvm/LineEditor/LineEditor.h
+file path=usr/include/llvm/LinkAllIR.h
+file path=usr/include/llvm/LinkAllPasses.h
+file path=usr/include/llvm/Linker/Linker.h
+file path=usr/include/llvm/MC/ConstantPools.h
+file path=usr/include/llvm/MC/MCAsmBackend.h
+file path=usr/include/llvm/MC/MCAsmInfo.h
+file path=usr/include/llvm/MC/MCAsmInfoCOFF.h
+file path=usr/include/llvm/MC/MCAsmInfoDarwin.h
+file path=usr/include/llvm/MC/MCAsmInfoELF.h
+file path=usr/include/llvm/MC/MCAsmLayout.h
+file path=usr/include/llvm/MC/MCAssembler.h
+file path=usr/include/llvm/MC/MCCodeEmitter.h
+file path=usr/include/llvm/MC/MCCodeGenInfo.h
+file path=usr/include/llvm/MC/MCContext.h
+file path=usr/include/llvm/MC/MCDirectives.h
+file path=usr/include/llvm/MC/MCDisassembler.h
+file path=usr/include/llvm/MC/MCDwarf.h
+file path=usr/include/llvm/MC/MCELF.h
+file path=usr/include/llvm/MC/MCELFObjectWriter.h
+file path=usr/include/llvm/MC/MCELFStreamer.h
+file path=usr/include/llvm/MC/MCELFSymbolFlags.h
+file path=usr/include/llvm/MC/MCExpr.h
+file path=usr/include/llvm/MC/MCExternalSymbolizer.h
+file path=usr/include/llvm/MC/MCFixedLenDisassembler.h
+file path=usr/include/llvm/MC/MCFixup.h
+file path=usr/include/llvm/MC/MCFixupKindInfo.h
+file path=usr/include/llvm/MC/MCInst.h
+file path=usr/include/llvm/MC/MCInstBuilder.h
+file path=usr/include/llvm/MC/MCInstPrinter.h
+file path=usr/include/llvm/MC/MCInstrAnalysis.h
+file path=usr/include/llvm/MC/MCInstrDesc.h
+file path=usr/include/llvm/MC/MCInstrInfo.h
+file path=usr/include/llvm/MC/MCInstrItineraries.h
+file path=usr/include/llvm/MC/MCLabel.h
+file path=usr/include/llvm/MC/MCLinkerOptimizationHint.h
+file path=usr/include/llvm/MC/MCMachOSymbolFlags.h
+file path=usr/include/llvm/MC/MCMachObjectWriter.h
+file path=usr/include/llvm/MC/MCObjectFileInfo.h
+file path=usr/include/llvm/MC/MCObjectStreamer.h
+file path=usr/include/llvm/MC/MCObjectWriter.h
+file path=usr/include/llvm/MC/MCParser/AsmCond.h
+file path=usr/include/llvm/MC/MCParser/AsmLexer.h
+file path=usr/include/llvm/MC/MCParser/MCAsmLexer.h
+file path=usr/include/llvm/MC/MCParser/MCAsmParser.h
+file path=usr/include/llvm/MC/MCParser/MCAsmParserExtension.h
+file path=usr/include/llvm/MC/MCParser/MCParsedAsmOperand.h
+file path=usr/include/llvm/MC/MCRegisterInfo.h
+file path=usr/include/llvm/MC/MCRelocationInfo.h
+file path=usr/include/llvm/MC/MCSchedule.h
+file path=usr/include/llvm/MC/MCSection.h
+file path=usr/include/llvm/MC/MCSectionCOFF.h
+file path=usr/include/llvm/MC/MCSectionELF.h
+file path=usr/include/llvm/MC/MCSectionMachO.h
+file path=usr/include/llvm/MC/MCStreamer.h
+file path=usr/include/llvm/MC/MCSubtargetInfo.h
+file path=usr/include/llvm/MC/MCSymbol.h
+file path=usr/include/llvm/MC/MCSymbolizer.h
+file path=usr/include/llvm/MC/MCTargetAsmParser.h
+file path=usr/include/llvm/MC/MCTargetOptions.h
+file path=usr/include/llvm/MC/MCTargetOptionsCommandFlags.h
+file path=usr/include/llvm/MC/MCValue.h
+file path=usr/include/llvm/MC/MCWin64EH.h
+file path=usr/include/llvm/MC/MCWinCOFFObjectWriter.h
+file path=usr/include/llvm/MC/MCWinCOFFStreamer.h
+file path=usr/include/llvm/MC/MCWinEH.h
+file path=usr/include/llvm/MC/MachineLocation.h
+file path=usr/include/llvm/MC/SectionKind.h
+file path=usr/include/llvm/MC/StringTableBuilder.h
+file path=usr/include/llvm/MC/SubtargetFeature.h
+file path=usr/include/llvm/MC/YAML.h
+file path=usr/include/llvm/Object/Archive.h
+file path=usr/include/llvm/Object/Binary.h
+file path=usr/include/llvm/Object/COFF.h
+file path=usr/include/llvm/Object/COFFYAML.h
+file path=usr/include/llvm/Object/ELF.h
+file path=usr/include/llvm/Object/ELFObjectFile.h
+file path=usr/include/llvm/Object/ELFTypes.h
+file path=usr/include/llvm/Object/ELFYAML.h
+file path=usr/include/llvm/Object/Error.h
+file path=usr/include/llvm/Object/IRObjectFile.h
+file path=usr/include/llvm/Object/MachO.h
+file path=usr/include/llvm/Object/MachOUniversal.h
+file path=usr/include/llvm/Object/ObjectFile.h
+file path=usr/include/llvm/Object/RelocVisitor.h
+file path=usr/include/llvm/Object/SymbolicFile.h
+file path=usr/include/llvm/Option/Arg.h
+file path=usr/include/llvm/Option/ArgList.h
+file path=usr/include/llvm/Option/OptParser.td
+file path=usr/include/llvm/Option/OptSpecifier.h
+file path=usr/include/llvm/Option/OptTable.h
+file path=usr/include/llvm/Option/Option.h
+file path=usr/include/llvm/Pass.h
+file path=usr/include/llvm/PassAnalysisSupport.h
+file path=usr/include/llvm/PassInfo.h
+file path=usr/include/llvm/PassManager.h
+file path=usr/include/llvm/PassRegistry.h
+file path=usr/include/llvm/PassSupport.h
+file path=usr/include/llvm/ProfileData/CoverageMapping.h
+file path=usr/include/llvm/ProfileData/CoverageMappingReader.h
+file path=usr/include/llvm/ProfileData/CoverageMappingWriter.h
+file path=usr/include/llvm/ProfileData/InstrProf.h
+file path=usr/include/llvm/ProfileData/InstrProfReader.h
+file path=usr/include/llvm/ProfileData/InstrProfWriter.h
+file path=usr/include/llvm/ProfileData/SampleProf.h
+file path=usr/include/llvm/ProfileData/SampleProfReader.h
+file path=usr/include/llvm/ProfileData/SampleProfWriter.h
+file path=usr/include/llvm/Support/AIXDataTypesFix.h
+file path=usr/include/llvm/Support/ARMBuildAttributes.h
+file path=usr/include/llvm/Support/ARMEHABI.h
+file path=usr/include/llvm/Support/ARMWinEH.h
+file path=usr/include/llvm/Support/AlignOf.h
+file path=usr/include/llvm/Support/Allocator.h
+file path=usr/include/llvm/Support/ArrayRecycler.h
+file path=usr/include/llvm/Support/Atomic.h
+file path=usr/include/llvm/Support/BlockFrequency.h
+file path=usr/include/llvm/Support/BranchProbability.h
+file path=usr/include/llvm/Support/CBindingWrapping.h
+file path=usr/include/llvm/Support/COFF.h
+file path=usr/include/llvm/Support/Capacity.h
+file path=usr/include/llvm/Support/Casting.h
+file path=usr/include/llvm/Support/CodeGen.h
+file path=usr/include/llvm/Support/CommandLine.h
+file path=usr/include/llvm/Support/Compiler.h
+file path=usr/include/llvm/Support/Compression.h
+file path=usr/include/llvm/Support/ConvertUTF.h
+file path=usr/include/llvm/Support/CrashRecoveryContext.h
+file path=usr/include/llvm/Support/DOTGraphTraits.h
+file path=usr/include/llvm/Support/DataExtractor.h
+file path=usr/include/llvm/Support/DataStream.h
+file path=usr/include/llvm/Support/DataTypes.h
+file path=usr/include/llvm/Support/Debug.h
+file path=usr/include/llvm/Support/Dwarf.h
+file path=usr/include/llvm/Support/DynamicLibrary.h
+file path=usr/include/llvm/Support/ELF.h
+file path=usr/include/llvm/Support/ELFRelocs/AArch64.def
+file path=usr/include/llvm/Support/ELFRelocs/ARM.def
+file path=usr/include/llvm/Support/ELFRelocs/Hexagon.def
+file path=usr/include/llvm/Support/ELFRelocs/Mips.def
+file path=usr/include/llvm/Support/ELFRelocs/PowerPC.def
+file path=usr/include/llvm/Support/ELFRelocs/PowerPC64.def
+file path=usr/include/llvm/Support/ELFRelocs/Sparc.def
+file path=usr/include/llvm/Support/ELFRelocs/SystemZ.def
+file path=usr/include/llvm/Support/ELFRelocs/i386.def
+file path=usr/include/llvm/Support/ELFRelocs/x86_64.def
+file path=usr/include/llvm/Support/Endian.h
+file path=usr/include/llvm/Support/EndianStream.h
+file path=usr/include/llvm/Support/Errc.h
+file path=usr/include/llvm/Support/Errno.h
+file path=usr/include/llvm/Support/ErrorHandling.h
+file path=usr/include/llvm/Support/ErrorOr.h
+file path=usr/include/llvm/Support/FileOutputBuffer.h
+file path=usr/include/llvm/Support/FileSystem.h
+file path=usr/include/llvm/Support/FileUtilities.h
+file path=usr/include/llvm/Support/Format.h
+file path=usr/include/llvm/Support/FormattedStream.h
+file path=usr/include/llvm/Support/GCOV.h
+file path=usr/include/llvm/Support/GenericDomTree.h
+file path=usr/include/llvm/Support/GenericDomTreeConstruction.h
+file path=usr/include/llvm/Support/GraphWriter.h
+file path=usr/include/llvm/Support/Host.h
+file path=usr/include/llvm/Support/LEB128.h
+file path=usr/include/llvm/Support/LICENSE.TXT
+file path=usr/include/llvm/Support/LineIterator.h
+file path=usr/include/llvm/Support/Locale.h
+file path=usr/include/llvm/Support/LockFileManager.h
+file path=usr/include/llvm/Support/MD5.h
+file path=usr/include/llvm/Support/MachO.h
+file path=usr/include/llvm/Support/ManagedStatic.h
+file path=usr/include/llvm/Support/MathExtras.h
+file path=usr/include/llvm/Support/Memory.h
+file path=usr/include/llvm/Support/MemoryBuffer.h
+file path=usr/include/llvm/Support/MemoryObject.h
+file path=usr/include/llvm/Support/Mutex.h
+file path=usr/include/llvm/Support/MutexGuard.h
+file path=usr/include/llvm/Support/OnDiskHashTable.h
+file path=usr/include/llvm/Support/Options.h
+file path=usr/include/llvm/Support/OutputBuffer.h
+file path=usr/include/llvm/Support/Path.h
+file path=usr/include/llvm/Support/PluginLoader.h
+file path=usr/include/llvm/Support/PointerLikeTypeTraits.h
+file path=usr/include/llvm/Support/PrettyStackTrace.h
+file path=usr/include/llvm/Support/Process.h
+file path=usr/include/llvm/Support/Program.h
+file path=usr/include/llvm/Support/RWMutex.h
+file path=usr/include/llvm/Support/RandomNumberGenerator.h
+file path=usr/include/llvm/Support/Recycler.h
+file path=usr/include/llvm/Support/RecyclingAllocator.h
+file path=usr/include/llvm/Support/Regex.h
+file path=usr/include/llvm/Support/Registry.h
+file path=usr/include/llvm/Support/RegistryParser.h
+file path=usr/include/llvm/Support/SMLoc.h
+file path=usr/include/llvm/Support/SaveAndRestore.h
+file path=usr/include/llvm/Support/ScaledNumber.h
+file path=usr/include/llvm/Support/Signals.h
+file path=usr/include/llvm/Support/Solaris.h
+file path=usr/include/llvm/Support/SourceMgr.h
+file path=usr/include/llvm/Support/SpecialCaseList.h
+file path=usr/include/llvm/Support/StreamingMemoryObject.h
+file path=usr/include/llvm/Support/StringPool.h
+file path=usr/include/llvm/Support/SwapByteOrder.h
+file path=usr/include/llvm/Support/SystemUtils.h
+file path=usr/include/llvm/Support/TargetRegistry.h
+file path=usr/include/llvm/Support/TargetSelect.h
+file path=usr/include/llvm/Support/ThreadLocal.h
+file path=usr/include/llvm/Support/Threading.h
+file path=usr/include/llvm/Support/TimeValue.h
+file path=usr/include/llvm/Support/Timer.h
+file path=usr/include/llvm/Support/ToolOutputFile.h
+file path=usr/include/llvm/Support/Unicode.h
+file path=usr/include/llvm/Support/UnicodeCharRanges.h
+file path=usr/include/llvm/Support/UniqueLock.h
+file path=usr/include/llvm/Support/Valgrind.h
+file path=usr/include/llvm/Support/Watchdog.h
+file path=usr/include/llvm/Support/Win64EH.h
+file path=usr/include/llvm/Support/WindowsError.h
+file path=usr/include/llvm/Support/YAMLParser.h
+file path=usr/include/llvm/Support/YAMLTraits.h
+file path=usr/include/llvm/Support/circular_raw_ostream.h
+file path=usr/include/llvm/Support/raw_os_ostream.h
+file path=usr/include/llvm/Support/raw_ostream.h
+file path=usr/include/llvm/Support/type_traits.h
+file path=usr/include/llvm/TableGen/Error.h
+file path=usr/include/llvm/TableGen/Main.h
+file path=usr/include/llvm/TableGen/Record.h
+file path=usr/include/llvm/TableGen/SetTheory.h
+file path=usr/include/llvm/TableGen/StringMatcher.h
+file path=usr/include/llvm/TableGen/StringToOffsetTable.h
+file path=usr/include/llvm/TableGen/TableGenBackend.h
+file path=usr/include/llvm/Target/CostTable.h
+file path=usr/include/llvm/Target/Target.td
+file path=usr/include/llvm/Target/TargetCallingConv.h
+file path=usr/include/llvm/Target/TargetCallingConv.td
+file path=usr/include/llvm/Target/TargetFrameLowering.h
+file path=usr/include/llvm/Target/TargetInstrInfo.h
+file path=usr/include/llvm/Target/TargetIntrinsicInfo.h
+file path=usr/include/llvm/Target/TargetItinerary.td
+file path=usr/include/llvm/Target/TargetLibraryInfo.h
+file path=usr/include/llvm/Target/TargetLowering.h
+file path=usr/include/llvm/Target/TargetLoweringObjectFile.h
+file path=usr/include/llvm/Target/TargetMachine.h
+file path=usr/include/llvm/Target/TargetOpcodes.h
+file path=usr/include/llvm/Target/TargetOptions.h
+file path=usr/include/llvm/Target/TargetRegisterInfo.h
+file path=usr/include/llvm/Target/TargetSchedule.td
+file path=usr/include/llvm/Target/TargetSelectionDAG.td
+file path=usr/include/llvm/Target/TargetSelectionDAGInfo.h
+file path=usr/include/llvm/Target/TargetSubtargetInfo.h
+file path=usr/include/llvm/Transforms/IPO.h
+file path=usr/include/llvm/Transforms/IPO/InlinerPass.h
+file path=usr/include/llvm/Transforms/IPO/PassManagerBuilder.h
+file path=usr/include/llvm/Transforms/Instrumentation.h
+file path=usr/include/llvm/Transforms/ObjCARC.h
+file path=usr/include/llvm/Transforms/Scalar.h
+file path=usr/include/llvm/Transforms/Utils/ASanStackFrameLayout.h
+file path=usr/include/llvm/Transforms/Utils/BasicBlockUtils.h
+file path=usr/include/llvm/Transforms/Utils/BuildLibCalls.h
+file path=usr/include/llvm/Transforms/Utils/BypassSlowDivision.h
+file path=usr/include/llvm/Transforms/Utils/Cloning.h
+file path=usr/include/llvm/Transforms/Utils/CmpInstAnalysis.h
+file path=usr/include/llvm/Transforms/Utils/CodeExtractor.h
+file path=usr/include/llvm/Transforms/Utils/CtorUtils.h
+file path=usr/include/llvm/Transforms/Utils/GlobalStatus.h
+file path=usr/include/llvm/Transforms/Utils/IntegerDivision.h
+file path=usr/include/llvm/Transforms/Utils/Local.h
+file path=usr/include/llvm/Transforms/Utils/LoopUtils.h
+file path=usr/include/llvm/Transforms/Utils/ModuleUtils.h
+file path=usr/include/llvm/Transforms/Utils/PromoteMemToReg.h
+file path=usr/include/llvm/Transforms/Utils/SSAUpdater.h
+file path=usr/include/llvm/Transforms/Utils/SSAUpdaterImpl.h
+file path=usr/include/llvm/Transforms/Utils/SimplifyIndVar.h
+file path=usr/include/llvm/Transforms/Utils/SimplifyLibCalls.h
+file path=usr/include/llvm/Transforms/Utils/SymbolRewriter.h
+file path=usr/include/llvm/Transforms/Utils/UnifyFunctionExitNodes.h
+file path=usr/include/llvm/Transforms/Utils/UnrollLoop.h
+file path=usr/include/llvm/Transforms/Utils/ValueMapper.h
+file path=usr/include/llvm/Transforms/Utils/VectorUtils.h
+file path=usr/include/llvm/Transforms/Vectorize.h
+file path=usr/lib/$(MACH64)/libLLVMAnalysis.a
+file path=usr/lib/$(MACH64)/libLLVMAsmParser.a
+file path=usr/lib/$(MACH64)/libLLVMAsmPrinter.a
+file path=usr/lib/$(MACH64)/libLLVMBitReader.a
+file path=usr/lib/$(MACH64)/libLLVMBitWriter.a
+file path=usr/lib/$(MACH64)/libLLVMCodeGen.a
+file path=usr/lib/$(MACH64)/libLLVMCore.a
+file path=usr/lib/$(MACH64)/libLLVMDebugInfo.a
+file path=usr/lib/$(MACH64)/libLLVMExecutionEngine.a
+file path=usr/lib/$(MACH64)/libLLVMIRReader.a
+file path=usr/lib/$(MACH64)/libLLVMInstCombine.a
+file path=usr/lib/$(MACH64)/libLLVMInstrumentation.a
+file path=usr/lib/$(MACH64)/libLLVMInterpreter.a
+file path=usr/lib/$(MACH64)/libLLVMLTO.a
+file path=usr/lib/$(MACH64)/libLLVMLineEditor.a
+file path=usr/lib/$(MACH64)/libLLVMLinker.a
+file path=usr/lib/$(MACH64)/libLLVMMC.a
+file path=usr/lib/$(MACH64)/libLLVMMCDisassembler.a
+file path=usr/lib/$(MACH64)/libLLVMMCJIT.a
+file path=usr/lib/$(MACH64)/libLLVMMCParser.a
+file path=usr/lib/$(MACH64)/libLLVMObjCARCOpts.a
+file path=usr/lib/$(MACH64)/libLLVMObject.a
+file path=usr/lib/$(MACH64)/libLLVMOption.a
+file path=usr/lib/$(MACH64)/libLLVMProfileData.a
+file path=usr/lib/$(MACH64)/libLLVMRuntimeDyld.a
+file path=usr/lib/$(MACH64)/libLLVMScalarOpts.a
+file path=usr/lib/$(MACH64)/libLLVMSelectionDAG.a
+file path=usr/lib/$(MACH64)/libLLVMSparcAsmParser.a variant.arch=sparc
+file path=usr/lib/$(MACH64)/libLLVMSparcAsmPrinter.a variant.arch=sparc
+file path=usr/lib/$(MACH64)/libLLVMSparcCodeGen.a variant.arch=sparc
+file path=usr/lib/$(MACH64)/libLLVMSparcDesc.a variant.arch=sparc
+file path=usr/lib/$(MACH64)/libLLVMSparcDisassembler.a variant.arch=sparc
+file path=usr/lib/$(MACH64)/libLLVMSparcInfo.a variant.arch=sparc
+file path=usr/lib/$(MACH64)/libLLVMSupport.a
+file path=usr/lib/$(MACH64)/libLLVMTableGen.a
+file path=usr/lib/$(MACH64)/libLLVMTarget.a
+file path=usr/lib/$(MACH64)/libLLVMTransformUtils.a
+file path=usr/lib/$(MACH64)/libLLVMVectorize.a
+file path=usr/lib/$(MACH64)/libLLVMX86AsmParser.a variant.arch=i386
+file path=usr/lib/$(MACH64)/libLLVMX86AsmPrinter.a variant.arch=i386
+file path=usr/lib/$(MACH64)/libLLVMX86CodeGen.a variant.arch=i386
+file path=usr/lib/$(MACH64)/libLLVMX86Desc.a variant.arch=i386
+file path=usr/lib/$(MACH64)/libLLVMX86Disassembler.a variant.arch=i386
+file path=usr/lib/$(MACH64)/libLLVMX86Info.a variant.arch=i386
+file path=usr/lib/$(MACH64)/libLLVMX86Utils.a variant.arch=i386
+file path=usr/lib/$(MACH64)/libLLVMipa.a
+file path=usr/lib/$(MACH64)/libLLVMipo.a
+file path=usr/lib/$(MACH64)/libLTO.a
+file path=usr/share/llvm/cmake/AddLLVM.cmake
+file path=usr/share/llvm/cmake/AddLLVMDefinitions.cmake
+file path=usr/share/llvm/cmake/AddOCaml.cmake
+file path=usr/share/llvm/cmake/AddSphinxTarget.cmake
+file path=usr/share/llvm/cmake/ChooseMSVCCRT.cmake
+file path=usr/share/llvm/cmake/CrossCompile.cmake
+file path=usr/share/llvm/cmake/FindOCaml.cmake
+file path=usr/share/llvm/cmake/FindSphinx.cmake
+file path=usr/share/llvm/cmake/GetSVN.cmake
+file path=usr/share/llvm/cmake/HandleLLVMOptions.cmake
+file path=usr/share/llvm/cmake/HandleLLVMStdlib.cmake
+file path=usr/share/llvm/cmake/LLVM-Config.cmake
+file path=usr/share/llvm/cmake/LLVMConfig.cmake
+file path=usr/share/llvm/cmake/LLVMConfigVersion.cmake
+file path=usr/share/llvm/cmake/LLVMExports.cmake
+file path=usr/share/llvm/cmake/LLVMParseArguments.cmake
+file path=usr/share/llvm/cmake/LLVMProcessSources.cmake
+file path=usr/share/llvm/cmake/TableGen.cmake
+license llvm.license license="University of Illinois/NCSA"
+depend type=require fmri=pkg:/developer/llvm/clang
+depend type=require fmri=pkg:/developer/llvm/llvm
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/llvm.license	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,225 @@
+Clang/LLVM copyrights and licenses:
+
+1. NCSA License: http://opensource.org/licenses/NCSA
+
+==============================================================================
+LLVM Release License
+==============================================================================
+University of Illinois/NCSA
+Open Source License
+
+Copyright (c) 2003-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.
+
+==============================================================================
+Copyrights and Licenses for Third Party Software Distributed with LLVM:
+==============================================================================
+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
+-------             ---------
+Autoconf            llvm/autoconf
+                    llvm/projects/ModuleMaker/autoconf
+                    llvm/projects/sample/autoconf
+CellSPU backend     llvm/lib/Target/CellSPU/README.txt
+Google Test         llvm/utils/unittest/googletest
+OpenBSD regex       llvm/lib/Support/{reg*, COPYRIGHT.regex}
+pyyaml tests        llvm/test/YAMLParser/{*.data, LICENSE.TXT}
+
+
+2. Clang/LLVM Autoconf License:
+------------------------------------------------------------------------------
+Autoconf Files
+------------------------------------------------------------------------------
+All autoconf files are licensed under the LLVM license with the following
+additions:
+
+llvm/autoconf/install-sh:
+	This script is licensed under the LLVM license, with the following
+	additional copyrights and restrictions:
+
+	Copyright 1991 by the Massachusetts Institute of Technology
+
+	Permission to use, copy, modify, distribute, and sell this software
+	and its documentation for any purpose is hereby granted without fee,
+	provided that the above copyright notice appear in all copies and
+	that both that copyright notice and this permission notice appear
+	in supporting documentation, and that the name of M.I.T. not be used
+	in advertising or publicity pertaining to distribution of the software
+	without specific, written prior permission.  M.I.T. makes no
+	representations about the suitability of this software for any
+	purpose.  It is provided "as is" without express or implied warranty.
+
+	Please see the source files for additional copyrights.
+
+
+3. CellSPU backend License:
+
+This code was contributed by a team from the Computer Systems Research
+Department in The Aerospace Corporation:
+
+- Scott Michel (head bottle washer and much of the non-floating point
+  instructions)
+- Mark Thomas (floating point instructions)
+- Michael AuYeung (intrinsics)
+- Chandler Carruth (LLVM expertise)
+- Nehal Desai (debugging, i32 operations, RoadRunner SPU expertise)
+
+Some minor fixes added by Kalle Raiskila.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR
+OTHERWISE.  IN NO EVENT SHALL THE AEROSPACE CORPORATION BE LIABLE FOR DAMAGES
+OF ANY KIND OR NATURE WHETHER BASED IN CONTRACT, TORT, OR OTHERWISE ARISING
+OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE INCLUDING, WITHOUT
+LIMITATION, DAMAGES RESULTING FROM LOST OR CONTAMINATED DATA, LOST PROFITS OR
+REVENUE, COMPUTER MALFUNCTION, OR FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL,
+OR PUNITIVE  DAMAGES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES OR
+SUCH DAMAGES ARE FORESEEABLE.
+
+
+4. Google License:
+
+Copyright 2008, Google Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+    * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+    * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+5. OpenBSD License:
+
+$OpenBSD: COPYRIGHT,v 1.3 2003/06/02 20:18:36 millert Exp $
+
+Copyright 1992, 1993, 1994 Henry Spencer.  All rights reserved.
+This software is not subject to any license of the American Telephone
+and Telegraph Company or of the Regents of the University of California.
+
+Permission is granted to anyone to use this software for any purpose on
+any computer system, and to alter it and redistribute it, subject
+to the following restrictions:
+
+1. The author is not responsible for the consequences of use of this
+   software, no matter how awful, even if they arise from flaws in it.
+
+2. The origin of this software must not be misrepresented, either by
+   explicit claim or by omission.  Since few users ever read sources,
+   credits must appear in the documentation.
+
+3. Altered versions must be plainly marked as such, and must not be
+   misrepresented as being the original software.  Since few users
+   ever read sources, credits must appear in the documentation.
+
+4. This notice may not be removed or altered.
+
+=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/*-
+ * Copyright (c) 1994
+ *      The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ *      @(#)COPYRIGHT   8.1 (Berkeley) 3/16/94
+ */
+
+6. pyyaml tests License:
+
+Copyright (c) 2006 Kirill Simonov
+
+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.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/llvm.p5m	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,88 @@
+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+
+#
+# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+#
+
+set name=pkg.fmri \
+    value=pkg:/developer/llvm/llvm@$(IPS_COMPONENT_VERSION),$(BUILD_VERSION)
+set name=pkg.summary \
+    value="LLVM $(COMPONENT_VERSION) runtime - The Low Level Virtual Machine"
+set name=com.oracle.info.description \
+    value="LLVM - The Low Level Virtual Machine Compiler Infrastructure Framework"
+set name=com.oracle.info.tpno value=$(TPNO)
+set name=info.classification value=org.opensolaris.category.2008:Development/C \
+    value=org.opensolaris.category.2008:Development/C++ \
+    value=org.opensolaris.category.2008:Development/GNU \
+    value="org.opensolaris.category.2008:Development/Objective C"
+set name=info.source-url value=$(COMPONENT_ARCHIVE_URL)
+set name=info.upstream-url value=$(COMPONENT_PROJECT_URL)
+set name=org.opensolaris.arc-caseid value=PSARC/2013/188
+set name=org.opensolaris.consolidation value=$(CONSOLIDATION)
+file path=usr/bin/FileCheck
+file path=usr/bin/bugpoint
+file path=usr/bin/count
+file path=usr/bin/llc
+file path=usr/bin/lli
+file path=usr/bin/lli-child-target
+file path=usr/bin/llvm-ar
+file path=usr/bin/llvm-as
+file path=usr/bin/llvm-bcanalyzer
+file path=usr/bin/llvm-config
+file path=usr/bin/llvm-cov
+file path=usr/bin/llvm-diff
+file path=usr/bin/llvm-dis
+file path=usr/bin/llvm-dsymutil
+file path=usr/bin/llvm-dwarfdump
+file path=usr/bin/llvm-extract
+file path=usr/bin/llvm-link
+file path=usr/bin/llvm-lto
+file path=usr/bin/llvm-mc
+file path=usr/bin/llvm-mcmarkup
+file path=usr/bin/llvm-nm
+file path=usr/bin/llvm-objdump
+file path=usr/bin/llvm-profdata
+hardlink path=usr/bin/llvm-ranlib target=llvm-ar
+file path=usr/bin/llvm-readobj
+file path=usr/bin/llvm-rtdyld
+file path=usr/bin/llvm-size
+file path=usr/bin/llvm-stress
+file path=usr/bin/llvm-symbolizer
+file path=usr/bin/llvm-tblgen
+file path=usr/bin/llvm-vtabledump
+file path=usr/bin/macho-dump
+file path=usr/bin/not
+file path=usr/bin/obj2yaml
+file path=usr/bin/opt
+file path=usr/bin/verify-uselistorder
+file path=usr/bin/yaml2obj
+file path=usr/lib/$(MACH64)/BugpointPasses.so
+file path=usr/lib/$(MACH64)/LLVMHello.so
+link path=usr/lib/$(MACH64)/libLLVM-$(COMPONENT_VERSION).so \
+    target=libLLVM-3.6.so
+file path=usr/lib/$(MACH64)/libLLVM-3.6.so
+file path=usr/lib/$(MACH64)/libLTO.so
+license llvm.license license="University of Illinois/NCSA"
+depend type=require fmri=pkg:/developer/gcc-49
+depend type=require fmri=pkg:/developer/gnu-binutils
+depend type=require fmri=pkg:/system/library/gcc/gcc-runtime-49
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/000-AutoRegen.sh.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,26 @@
+# Solaris autoconf-based build.
+# https://llvm.org/bugs/show_bug.cgi?id=24641
+--- autoconf/AutoRegen.sh	2014-02-28 13:17:54.000000000 -0500
++++ autoconf/AutoRegen.sh	2015-07-18 15:03:22.104835693 -0400
+@@ -19,6 +19,21 @@
+ want_aclocal_version='1\.9\.6'
+ ### END NOTE #########################################################
+ 
++UNAMES="`uname -s`"
++UNAMER="`uname -r`"
++
++if [ "${UNAMES}" = "SunOS" ] ; then
++  if [ "${UNAMER}" = "5.11" ] ; then
++    want_autoconf_version='2\.68'
++    want_autoheader_version=$want_autoconf_version
++    want_aclocal_version='1\.11\.2'
++  elif [ "${UNAMER}" = "5.12" ] ; then
++    want_autoconf_version='2\.69'
++    want_autoheader_version=$want_autoconf_version
++    want_aclocal_version='1\.15'
++  fi
++fi
++
+ outfile=configure
+ configfile=configure.ac
+ 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/001-Makefile.config.in.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,43 @@
+# Solaris autoconf-based build.
+# https://llvm.org/bugs/show_bug.cgi?id=24641
+--- Makefile.config.in	2014-11-04 16:35:15.000000000 -0800
++++ Makefile.config.in	2015-08-31 09:18:01.367776683 -0700
+@@ -12,6 +12,8 @@
+ #
+ #===------------------------------------------------------------------------===#
+ 
++MACH = $(shell uname -p)
++
+ # Define LLVM specific info and directories based on the autoconf variables
+ LLVMPackageName   := @PACKAGE_TARNAME@
+ LLVMVersion       := @PACKAGE_VERSION@
+@@ -220,6 +222,12 @@
+ 
+ LIBS       := @LIBS@
+ 
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++  ifeq ($(MACH),sparc)
++    LIBS += -lkstat
++  endif
++endif
++
+ # Targets that are possible to build
+ ALL_TARGETS := @ALL_TARGETS@
+ 
+@@ -337,14 +345,14 @@
+ ENABLE_EMBED_STDCXX := @ENABLE_EMBED_STDCXX@
+ 
+ # Use -fvisibility-inlines-hidden?
+-ENABLE_VISIBILITY_INLINES_HIDDEN := @ENABLE_VISIBILITY_INLINES_HIDDEN@
++ENABLE_VISIBILITY_INLINES_HIDDEN := 0
+ 
+ # Do we want to allow timestamping information into builds?
+ ENABLE_TIMESTAMPS := @ENABLE_TIMESTAMPS@
+ 
+ # This option tells the Makefiles to produce verbose output.
+ # It essentially prints the commands that make is executing
+-#VERBOSE = 1
++VERBOSE := 1
+ 
+ # Enable JIT for this platform
+ TARGET_HAS_JIT = @TARGET_HAS_JIT@
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/002-Makefile.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,15 @@
+# Solaris autoconf-based build.
+# https://llvm.org/bugs/show_bug.cgi?id=24641
+--- tools/llvm-shlib/Makefile	2014-07-31 23:16:03.000000000 -0700
++++ tools/llvm-shlib/Makefile	2015-06-07 11:01:59.791190596 -0700
+@@ -71,7 +71,9 @@
+ 
+ ifeq ($(HOST_OS),SunOS)
+     # add -z allextract ahead of other libraries on Solaris
+-    LLVMLibsOptions := -Wl,-z -Wl,allextract $(LLVMLibsOptions)
++    LLVMLibsOptions := -Wl,-z -Wl,rescan -Wl,-z -Wl,allextract $(LLVMLibsOptions)
++    LLVMLibsOptions += -Wl,-h -Wl,lib$(LIBRARYNAME)$(SHLIBEXT)
++    LLVMLibsOptions += -Wl,-z -Wl,defaultextract -Wl,-z -Wl,defs
+ endif
+ 
+ ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/003-Makefile.rules.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,18 @@
+# Strip unused sections in Solaris.
+# https://llvm.org/bugs/show_bug.cgi?id=24641
+--- Makefile.rules	2014-11-04 16:35:15.000000000 -0800
++++ Makefile.rules	2015-07-17 18:28:25.379220132 -0700
+@@ -638,9 +638,12 @@
+   ifeq ($(HOST_OS),Darwin)
+     LD.Flags += -Wl,-dead_strip
+   else
+-    ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
++    ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW SunOS))
+       LD.Flags += -Wl,--gc-sections
+     endif
++    ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++      LD.Flags += -Wl,-z -Wl,discard-unused=sections
++    endif
+   endif
+ endif
+ 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/004-configure.ac.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,27 @@
+# Solaris autoconf-based build.
+# https://llvm.org/bugs/show_bug.cgi?id=24641
+--- autoconf/configure.ac	2015-05-01 21:17:33.000000000 -0700
++++ autoconf/configure.ac	2015-06-01 09:30:27.734038335 -0700
+@@ -1486,8 +1486,11 @@
+ fi
+ 
+ dnl mallinfo is optional; the code can compile (minus features) without it
++dnl Explicitly disable on Solaris.
++if test "$llvm_cv_target_os_type" != "SunOS" ; then
+ AC_SEARCH_LIBS(mallinfo,malloc,AC_DEFINE([HAVE_MALLINFO],[1],
+                [Define if mallinfo() is available on this platform.]))
++fi
+ 
+ dnl pthread locking functions are optional - but llvm will not be thread-safe
+ dnl without locks.
+@@ -1965,7 +1968,10 @@
+ fi
+ 
+ dnl Determine whether the compiler supports -fvisibility-inlines-hidden.
++dnl Explicitly disable on Solaris.
++if test "$llvm_cv_target_os_type" != "SunOS" ; then
+ AC_CXX_USE_VISIBILITY_INLINES_HIDDEN
++fi
+ 
+ dnl Determine linker rpath flag
+ if test "$llvm_cv_link_use_r" = "yes" ; then
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/005-Makefile.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,22 @@
+# Solaris autoconf-based build.
+# https://llvm.org/bugs/show_bug.cgi?id=24641
+--- tools/clang/tools/libclang/Makefile	2014-10-29 11:55:09.000000000 -0700
++++ tools/clang/tools/libclang/Makefile	2015-06-10 15:18:27.471754914 -0700
+@@ -33,10 +33,16 @@
+ include $(CLANG_LEVEL)/Makefile
+ 
+ # Add soname to the library.
+-ifeq ($(HOST_OS), $(filter $(HOST_OS), Linux FreeBSD GNU GNU/kFreeBSD))
++ifeq ($(HOST_OS), $(filter $(HOST_OS), Linux FreeBSD GNU GNU/kFreeBSD SunOS))
+         LLVMLibsOptions += -Wl,-soname,lib$(LIBRARYNAME)$(SHLIBEXT)
+ endif
+ 
++# Extract everything necessary from Solaris *.a archives
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++  SharedLinkOptions += -Wl,-z -Wl,rescan-now -Wl,-z -Wl,allextract
++  LLVMLibsOptions += -Wl,-z -Wl,defaultextract
++endif
++
+ ifeq ($(ENABLE_CLANG_ARCMT),1)
+   CXX.Flags += -DCLANG_ENABLE_ARCMT
+ endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/006-clang-D10272.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,1767 @@
+# Giant clang 3.6.2 patch for correcting misalignments.
+# Patch is from: http://reviews.llvm.org/D10272
+# Adjustments were made for 3.6.2 (the original does not apply cleanly).
+--- include/llvm/Support/Compiler.h	2014-11-18 17:17:30.000000000 -0500
++++ include/llvm/Support/Compiler.h	2015-07-17 23:43:07.143745400 -0400
+@@ -303,6 +303,37 @@
+ # define LLVM_ASSUME_ALIGNED(p, a) (p)
+ #endif
+ 
++/// \macro LLVM_ALIGNAS
++/// \brief Used to specify a minimum alignment for a structure or variable. The
++/// alignment must be a constant integer. Use LLVM_PTR_SIZE to compute
++/// alignments in terms of the size of a pointer.
++///
++/// Note that __declspec(align) has special quirks, it's not legal to pass a
++/// structure with __declspec(align) as a formal parameter.
++#ifdef _MSC_VER
++# define LLVM_ALIGNAS(x) __declspec(align(x))
++#elif __GNUC__ && !__has_feature(cxx_alignas) && !LLVM_GNUC_PREREQ(4, 8, 0)
++# define LLVM_ALIGNAS(x) __attribute__((aligned(x)))
++#else
++# define LLVM_ALIGNAS(x) alignas(x)
++#endif
++
++/// \macro LLVM_PTR_SIZE
++/// \brief A constant integer equivalent to the value of sizeof(void*).
++/// Generally used in combination with LLVM_ALIGNAS or when doing computation in
++/// the preprocessor.
++#ifdef __SIZEOF_POINTER__
++# define LLVM_PTR_SIZE __SIZEOF_POINTER__
++#elif defined(_WIN64)
++# define LLVM_PTR_SIZE 8
++#elif defined(_WIN32)
++# define LLVM_PTR_SIZE 4
++#elif defined(_MSC_VER)
++# error "could not determine LLVM_PTR_SIZE as a constant int for MSVC"
++#else
++# define LLVM_PTR_SIZE sizeof(void *)
++#endif
++
+ /// \macro LLVM_FUNCTION_NAME
+ /// \brief Expands to __func__ on compilers which support it.  Otherwise,
+ /// expands to a compiler-dependent replacement.
+--- tools/clang/include/clang/AST/Decl.h	2015-01-13 16:31:13.000000000 -0800
++++ tools/clang/include/clang/AST/Decl.h	2015-07-17 16:43:46.474996996 -0700
+@@ -3658,6 +3658,9 @@
+   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
+   static bool classofKind(Kind K) { return K == Import; }
+ };
++static_assert(llvm::AlignOf<ImportDecl>::Alignment >=
++                  llvm::AlignOf<SourceLocation>::Alignment,
++              "Alignment is insufficient for objects appended to ImportDecl");
+ 
+ /// \brief Represents an empty-declaration.
+ class EmptyDecl : public Decl {
+--- tools/clang/include/clang/AST/DeclBase.h	2014-11-17 15:36:45.000000000 -0800
++++ tools/clang/include/clang/AST/DeclBase.h	2015-07-17 16:43:46.476997606 -0700
+@@ -69,6 +69,9 @@
+ /// Decl - This represents one declaration (or definition), e.g. a variable,
+ /// typedef, function, struct, etc.
+ ///
++/// Note: There are objects tacked on before the *beginning* of Decl
++/// (and its subclasses) in its Decl::operator new(). Proper alignment
++/// for all subclasses is asserted in DeclBase.cpp.
+ class Decl {
+ public:
+   /// \brief Lists the kind of concrete classes of Decl.
+--- tools/clang/include/clang/AST/DeclCXX.h	2014-12-10 12:04:48.000000000 -0800
++++ tools/clang/include/clang/AST/DeclCXX.h	2015-07-17 16:43:46.479237326 -0700
+@@ -2130,6 +2130,10 @@
+   /// \brief Get the initializer.
+   Expr *getInit() const { return static_cast<Expr*>(Init); }
+ };
++static_assert(
++    llvm::AlignOf<CXXCtorInitializer>::Alignment >=
++        llvm::AlignOf<VarDecl *>::Alignment,
++    "Alignment is insufficient for objects appended to CXXCtorInitializer");
+ 
+ /// \brief Represents a C++ constructor within a class.
+ ///
+--- tools/clang/include/clang/AST/DeclFriend.h	2014-07-16 18:59:34.000000000 -0700
++++ tools/clang/include/clang/AST/DeclFriend.h	2015-07-17 16:43:46.480506828 -0700
+@@ -172,6 +172,9 @@
+   friend class ASTDeclReader;
+   friend class ASTDeclWriter;
+ };
++static_assert(llvm::AlignOf<FriendDecl>::Alignment >=
++                  llvm::AlignOf<TemplateParameterList *>::Alignment,
++              "Alignment is insufficient for objects appended to FriendDecl");
+ 
+ /// An iterator over the friend declarations of a class.
+ class CXXRecordDecl::friend_iterator {
+--- tools/clang/include/clang/AST/DeclGroup.h	2014-05-05 23:48:52.000000000 -0700
++++ tools/clang/include/clang/AST/DeclGroup.h	2015-07-17 16:43:46.481808784 -0700
+@@ -14,6 +14,7 @@
+ #ifndef LLVM_CLANG_AST_DECLGROUP_H
+ #define LLVM_CLANG_AST_DECLGROUP_H
+ 
++#include "llvm/Support/AlignOf.h"
+ #include "llvm/Support/DataTypes.h"
+ #include <cassert>
+ 
+@@ -51,6 +52,9 @@
+     return ((Decl* const*) (this+1))[i];
+   }
+ };
++static_assert(llvm::AlignOf<DeclGroup>::Alignment >=
++                  llvm::AlignOf<Decl *>::Alignment,
++              "Alignment is insufficient for objects appended to DeclGroup");
+ 
+ class DeclGroupRef {
+   // Note this is not a PointerIntPair because we need the address of the
+--- tools/clang/include/clang/AST/DeclOpenMP.h	2014-11-10 20:05:39.000000000 -0800
++++ tools/clang/include/clang/AST/DeclOpenMP.h	2015-07-17 16:43:46.482893197 -0700
+@@ -84,6 +84,10 @@
+   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
+   static bool classofKind(Kind K) { return K == OMPThreadPrivate; }
+ };
++static_assert(
++    llvm::AlignOf<OMPThreadPrivateDecl>::Alignment >=
++        llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to OMPThreadPrivateDecl");
+ 
+ }  // end namespace clang
+ 
+--- tools/clang/include/clang/AST/DeclTemplate.h	2014-08-30 09:55:39.000000000 -0700
++++ tools/clang/include/clang/AST/DeclTemplate.h	2015-07-17 16:43:46.485713092 -0700
+@@ -43,7 +43,7 @@
+ 
+ /// \brief Stores a list of template parameters for a TemplateDecl and its
+ /// derived classes.
+-class TemplateParameterList {
++class LLVM_ALIGNAS(/*alignof(void*)*/ LLVM_PTR_SIZE) TemplateParameterList {
+   /// The location of the 'template' keyword.
+   SourceLocation TemplateLoc;
+ 
+@@ -131,6 +131,10 @@
+     return SourceRange(TemplateLoc, RAngleLoc);
+   }
+ };
++static_assert(
++    llvm::AlignOf<TemplateParameterList>::Alignment >=
++        llvm::AlignOf<NamedDecl *>::Alignment,
++    "Alignment is insufficient for objects appended to TemplateParameterList");
+ 
+ /// \brief Stores a list of template parameters for a TemplateDecl and its
+ /// derived classes. Suitable for creating on the stack.
+@@ -460,27 +464,20 @@
+ ///     friend void foo<>(T);
+ ///   };
+ /// \endcode
+-class DependentFunctionTemplateSpecializationInfo {
+-  struct CA {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8)
++    DependentFunctionTemplateSpecializationInfo {
+     /// The number of potential template candidates.
+     unsigned NumTemplates;
+ 
+     /// The number of template arguments.
+     unsigned NumArgs;
+-  };
+-
+-  union {
+-    // Force sizeof to be a multiple of sizeof(void*) so that the
+-    // trailing data is aligned.
+-    void *Aligner;
+-    struct CA d;
+-  };
+ 
+   /// The locations of the left and right angle brackets.
+   SourceRange AngleLocs;
+ 
+   FunctionTemplateDecl * const *getTemplates() const {
+-    return reinterpret_cast<FunctionTemplateDecl*const*>(this+1);
++    return reinterpret_cast<FunctionTemplateDecl *const *>(
++        &getTemplateArgs()[NumArgs]);
+   }
+ 
+ public:
+@@ -490,9 +487,7 @@
+ 
+   /// \brief Returns the number of function templates that this might
+   /// be a specialization of.
+-  unsigned getNumTemplates() const {
+-    return d.NumTemplates;
+-  }
++  unsigned getNumTemplates() const { return NumTemplates; }
+ 
+   /// \brief Returns the i'th template candidate.
+   FunctionTemplateDecl *getTemplate(unsigned I) const {
+@@ -502,14 +497,11 @@
+ 
+   /// \brief Returns the explicit template arguments that were given.
+   const TemplateArgumentLoc *getTemplateArgs() const {
+-    return reinterpret_cast<const TemplateArgumentLoc*>(
+-                                            &getTemplates()[getNumTemplates()]);
++    return reinterpret_cast<const TemplateArgumentLoc *>(this + 1);
+   }
+ 
+   /// \brief Returns the number of explicit template arguments that were given.
+-  unsigned getNumTemplateArgs() const {
+-    return d.NumArgs;
+-  }
++  unsigned getNumTemplateArgs() const { return NumArgs; }
+ 
+   /// \brief Returns the nth template argument.
+   const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
+@@ -525,6 +517,15 @@
+     return AngleLocs.getEnd();
+   }
+ };
++static_assert(
++    llvm::AlignOf<DependentFunctionTemplateSpecializationInfo>::Alignment >=
++        llvm::AlignOf<TemplateArgumentLoc>::Alignment,
++    "Alignment is insufficient for objects appended to "
++    "DependentFunctionTemplateSpecializationInfo");
++static_assert(llvm::AlignOf<TemplateArgumentLoc>::Alignment >=
++                  llvm::AlignOf<FunctionTemplateDecl *>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "DependentFunctionTemplateSpecializationInfo");
+ 
+ /// Declaration of a redeclarable template.
+ class RedeclarableTemplateDecl : public TemplateDecl, 
+@@ -1203,6 +1204,10 @@
+   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
+   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
+ };
++static_assert(llvm::AlignOf<NonTypeTemplateParmDecl>::Alignment >=
++                  llvm::AlignOf<void *>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "NonTypeTemplateParmDecl");
+ 
+ /// TemplateTemplateParmDecl - Declares a template template parameter,
+ /// e.g., "T" in
+@@ -1369,6 +1374,10 @@
+   friend class ASTDeclReader;
+   friend class ASTDeclWriter;
+ };
++static_assert(llvm::AlignOf<TemplateTemplateParmDecl>::Alignment >=
++                  llvm::AlignOf<TemplateParameterList *>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "TemplateTemplateParmDecl");
+ 
+ /// \brief Represents a class template specialization, which refers to
+ /// a class template with a given set of template arguments.
+--- tools/clang/include/clang/AST/EvaluatedExprVisitor.h	2014-12-03 13:00:20.000000000 -0800
++++ tools/clang/include/clang/AST/EvaluatedExprVisitor.h	2015-07-17 16:43:46.487103645 -0700
+@@ -85,7 +85,7 @@
+ 
+   void VisitLambdaExpr(LambdaExpr *LE) {
+     // Only visit the capture initializers, and not the body.
+-    for (LambdaExpr::capture_init_iterator I = LE->capture_init_begin(),
++    for (LambdaExpr::const_capture_init_iterator I = LE->capture_init_begin(),
+                                            E = LE->capture_init_end();
+          I != E; ++I)
+       if (*I)
+--- tools/clang/include/clang/AST/Expr.h	2015-01-12 02:17:46.000000000 -0800
++++ tools/clang/include/clang/AST/Expr.h	2015-07-17 16:43:46.491602160 -0700
+@@ -894,7 +894,7 @@
+ ///   DeclRefExprBits.RefersToEnclosingVariableOrCapture
+ ///       Specifies when this declaration reference expression (validly)
+ ///       refers to an enclosed local or a captured variable.
+-class DeclRefExpr : public Expr {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DeclRefExpr : public Expr {
+   /// \brief The declaration that we are referencing.
+   ValueDecl *D;
+ 
+@@ -1048,13 +1048,17 @@
+     if (!hasTemplateKWAndArgsInfo())
+       return nullptr;
+ 
+-    if (hasFoundDecl())
++    if (hasFoundDecl()) {
+       return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
+-        &getInternalFoundDecl() + 1);
++          llvm::alignAddr(&getInternalFoundDecl() + 1,
++                          llvm::alignOf<ASTTemplateKWAndArgsInfo>()));
++    }
+ 
+-    if (hasQualifier())
++    if (hasQualifier()) {
+       return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
+-        &getInternalQualifierLoc() + 1);
++          llvm::alignAddr(&getInternalQualifierLoc() + 1,
++                          llvm::alignOf<ASTTemplateKWAndArgsInfo>()));
++    }
+ 
+     return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
+   }
+@@ -1167,6 +1171,16 @@
+   friend class ASTStmtReader;
+   friend class ASTStmtWriter;
+ };
++static_assert(llvm::AlignOf<DeclRefExpr>::Alignment >=
++                  llvm::AlignOf<NestedNameSpecifierLoc>::Alignment,
++              "Alignment is insufficient for objects appended to DeclRefExpr");
++static_assert(llvm::AlignOf<NestedNameSpecifierLoc>::Alignment >=
++                  llvm::AlignOf<NamedDecl *>::Alignment,
++              "Alignment is insufficient for objects appended to DeclRefExpr");
++// Code re-aligns before ASTTemplateKWAndArgsInfo
++static_assert(llvm::AlignOf<DeclRefExpr>::Alignment >=
++                  llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++              "Alignment is insufficient for objects appended to DeclRefExpr");
+ 
+ /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
+ class PredefinedExpr : public Expr {
+@@ -1968,6 +1982,12 @@
+     return child_range(begin, begin + NumExprs);
+   }
+ };
++static_assert(llvm::AlignOf<OffsetOfExpr>::Alignment >=
++                  llvm::AlignOf<OffsetOfExpr::OffsetOfNode *>::Alignment,
++              "Alignment is insufficient for objects appended to OffsetOfExpr");
++static_assert(llvm::AlignOf<OffsetOfExpr::OffsetOfNode>::Alignment >=
++                  llvm::AlignOf<Expr *>::Alignment,
++              "Alignment is insufficient for objects appended to OffsetOfExpr");
+ 
+ /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
+ /// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
+@@ -2309,9 +2329,10 @@
+ 
+ /// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
+ ///
+-class MemberExpr : public Expr {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) MemberExpr : public Expr {
++public:
+   /// Extra data stored in some member expressions.
+-  struct MemberNameQualifier {
++  struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) MemberNameQualifier {
+     /// \brief The nested-name-specifier that qualifies the name, including
+     /// source-location information.
+     NestedNameSpecifierLoc QualifierLoc;
+@@ -2321,6 +2342,7 @@
+     DeclAccessPair FoundDecl;
+   };
+ 
++private:
+   /// Base - the expression for the base pointer or structure references.  In
+   /// X.F, this is "X".
+   Stmt *Base;
+@@ -2591,6 +2613,12 @@
+   friend class ASTReader;
+   friend class ASTStmtWriter;
+ };
++static_assert(llvm::AlignOf<MemberExpr>::Alignment >=
++                  llvm::AlignOf<MemberExpr::MemberNameQualifier>::Alignment,
++              "Alignment is insufficient for objects appended to MemberExpr");
++static_assert(llvm::AlignOf<MemberExpr::MemberNameQualifier>::Alignment >=
++                  llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++              "Alignment is insufficient for objects appended to MemberExpr");
+ 
+ /// CompoundLiteralExpr - [C99 6.5.2.5]
+ ///
+@@ -2747,6 +2775,11 @@
+   // Iterators
+   child_range children() { return child_range(&Op, &Op+1); }
+ };
++static_assert(llvm::AlignOf<CastExpr>::Alignment >=
++                  llvm::AlignOf<CXXBaseSpecifier *>::Alignment,
++              "Alignment is insufficient for objects appended to CastExpr");
++// (Note that the data is actually tacked onto one of its subclasses,
++// but they'll inherit alignment)
+ 
+ /// ImplicitCastExpr - Allows us to explicitly represent implicit type
+ /// conversions, which have no direct representation in the original
+@@ -4272,6 +4305,10 @@
+     return child_range(begin, begin + NumSubExprs);
+   }
+ };
++static_assert(
++    llvm::AlignOf<DesignatedInitExpr>::Alignment >=
++        llvm::AlignOf<Stmt *>::Alignment,
++    "Alignment is insufficient for objects appended to DesignatedInitExpr");
+ 
+ /// \brief Represents an implicitly-generated value initialization of
+ /// an object of a given type.
+@@ -4749,6 +4786,10 @@
+     return T->getStmtClass() == PseudoObjectExprClass;
+   }
+ };
++static_assert(
++    llvm::AlignOf<PseudoObjectExpr>::Alignment >=
++        llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to PseudoObjectExpr");
+ 
+ /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
+ /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
+--- tools/clang/include/clang/AST/ExprCXX.h	2015-01-14 03:29:14.000000000 -0800
++++ tools/clang/include/clang/AST/ExprCXX.h	2015-07-18 11:25:29.503136056 -0700
+@@ -933,6 +933,10 @@
+   friend class ASTStmtReader;
+   friend class ASTStmtWriter;
+ };
++static_assert(
++    llvm::AlignOf<CXXDefaultArgExpr>::Alignment >=
++        llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to CXXDefaultArgExpr");
+ 
+ /// \brief A use of a default initializer in a constructor or in aggregate
+ /// initialization.
+@@ -1395,23 +1399,38 @@
+     getStoredStmts()[NumCaptures] = nullptr;
+   }
+   
+-  Stmt **getStoredStmts() const {
++  Stmt **getStoredStmts() {
+     return reinterpret_cast<Stmt **>(const_cast<LambdaExpr *>(this) + 1);
+   }
+   
++  Stmt *const *getStoredStmts() const {
++    return reinterpret_cast<Stmt *const *>(this + 1);
++  }
++  
+   /// \brief Retrieve the mapping from captures to the first array index
+   /// variable.
+-  unsigned *getArrayIndexStarts() const {
++  unsigned *getArrayIndexStarts() {
+     return reinterpret_cast<unsigned *>(getStoredStmts() + NumCaptures + 1);
+   }
+   
++  const unsigned *getArrayIndexStarts() const {
++    return reinterpret_cast<const unsigned *>(getStoredStmts() + NumCaptures + 1);
++  }
++  
+   /// \brief Retrieve the complete set of array-index variables.
+-  VarDecl **getArrayIndexVars() const {
++  VarDecl **getArrayIndexVars() {
+     unsigned ArrayIndexSize =
+         llvm::RoundUpToAlignment(sizeof(unsigned) * (NumCaptures + 1),
+                                  llvm::alignOf<VarDecl*>());
+     return reinterpret_cast<VarDecl **>(
+-        reinterpret_cast<char*>(getArrayIndexStarts()) + ArrayIndexSize);
++        reinterpret_cast<unsigned char*>(getArrayIndexStarts()) + ArrayIndexSize);
++  }
++
++  VarDecl *const *getArrayIndexVars() const {
++    unsigned ArrayIndexSize = llvm::RoundUpToAlignment(
++        sizeof(unsigned) * (NumCaptures + 1), llvm::alignOf<VarDecl *>());
++    return reinterpret_cast<VarDecl *const *>(
++        reinterpret_cast<const unsigned char *>(getArrayIndexStarts()) + ArrayIndexSize);
+   }
+ 
+ public:
+@@ -1492,21 +1511,43 @@
+   /// arguments.
+   typedef Expr **capture_init_iterator;
+ 
++  /// \brief Const iterator that walks over the capture initialization
++  /// arguments.
++  typedef Expr *const *const_capture_init_iterator;
++
+   /// \brief Retrieve the initialization expressions for this lambda's captures.
+-  llvm::iterator_range<capture_init_iterator> capture_inits() const {
++  llvm::iterator_range<capture_init_iterator> capture_inits() {
+     return llvm::iterator_range<capture_init_iterator>(capture_init_begin(),
+                                                        capture_init_end());
+   }
+ 
++  /// \brief Retrieve the initialization expressions for this lambda's captures.
++  llvm::iterator_range<const_capture_init_iterator> capture_inits() const {
++    return llvm::iterator_range<const_capture_init_iterator>(
++        capture_init_begin(), capture_init_end());
++  }
++
+   /// \brief Retrieve the first initialization argument for this
+   /// lambda expression (which initializes the first capture field).
+-  capture_init_iterator capture_init_begin() const {
++  capture_init_iterator capture_init_begin() {
+     return reinterpret_cast<Expr **>(getStoredStmts());
+   }
+ 
++  /// \brief Retrieve the first initialization argument for this
++  /// lambda expression (which initializes the first capture field).
++  const_capture_init_iterator capture_init_begin() const {
++    return reinterpret_cast<Expr *const *>(getStoredStmts());
++  }
++
+   /// \brief Retrieve the iterator pointing one past the last
+   /// initialization argument for this lambda expression.
+-  capture_init_iterator capture_init_end() const {
++  capture_init_iterator capture_init_end() {
++    return capture_init_begin() + NumCaptures;
++  }
++
++  /// \brief Retrieve the iterator pointing one past the last
++  /// initialization argument for this lambda expression.
++  const_capture_init_iterator capture_init_end() const {
+     return capture_init_begin() + NumCaptures;    
+   }
+ 
+@@ -1515,7 +1556,8 @@
+   ///
+   /// \param Iter The iterator that points at the capture initializer for 
+   /// which we are extracting the corresponding index variables.
+-  ArrayRef<VarDecl *> getCaptureInitIndexVars(capture_init_iterator Iter) const;
++  ArrayRef<VarDecl *>
++  getCaptureInitIndexVars(const_capture_init_iterator Iter) const;
+   
+   /// \brief Retrieve the source range covering the lambda introducer,
+   /// which contains the explicit capture list surrounded by square
+@@ -1570,6 +1612,16 @@
+   friend class ASTStmtReader;
+   friend class ASTStmtWriter;
+ };
++static_assert(llvm::AlignOf<LambdaExpr>::Alignment >=
++                  llvm::AlignOf<Stmt *>::Alignment,
++              "Alignment is insufficient for objects appended to LambdaExpr");
++static_assert(llvm::AlignOf<Stmt *>::Alignment >=
++                  llvm::AlignOf<unsigned>::Alignment,
++              "Alignment is insufficient for objects appended to LambdaExpr");
++// Code re-aligns before VarDecl *[]
++static_assert(llvm::AlignOf<LambdaExpr>::Alignment >=
++                  llvm::AlignOf<VarDecl *>::Alignment,
++              "Alignment is insufficient for objects appended to LambdaExpr");
+ 
+ /// An expression "T()" which creates a value-initialized rvalue of type
+ /// T, which is a non-class type.  See (C++98 [5.2.3p2]).
+@@ -2157,6 +2209,10 @@
+   friend class ASTStmtWriter;
+ 
+ };
++static_assert(
++    llvm::AlignOf<TypeTraitExpr>::Alignment >=
++        llvm::AlignOf<TypeSourceInfo *>::Alignment,
++    "Alignment is insufficient for objects appended to TypeTraitExpr");
+ 
+ /// \brief An Embarcadero array type trait, as used in the implementation of
+ /// __array_rank and __array_extent.
+@@ -2289,7 +2345,7 @@
+ 
+ /// \brief A reference to an overloaded function set, either an
+ /// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
+-class OverloadExpr : public Expr {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) OverloadExpr : public Expr {
+   /// \brief The common name of these declarations.
+   DeclarationNameInfo NameInfo;
+ 
+@@ -2578,6 +2634,10 @@
+     return T->getStmtClass() == UnresolvedLookupExprClass;
+   }
+ };
++static_assert(
++    llvm::AlignOf<UnresolvedLookupExpr>::Alignment >=
++        llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++    "Alignment is insufficient for objects appended to UnresolvedLookupExpr");
+ 
+ /// \brief A qualified reference to a name whose declaration cannot
+ /// yet be resolved.
+@@ -2593,7 +2653,8 @@
+ /// qualifier (X<T>::) and the name of the entity being referenced
+ /// ("value"). Such expressions will instantiate to a DeclRefExpr once the
+ /// declaration can be found.
+-class DependentScopeDeclRefExpr : public Expr {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentScopeDeclRefExpr
++    : public Expr {
+   /// \brief The nested-name-specifier that qualifies this unresolved
+   /// declaration name.
+   NestedNameSpecifierLoc QualifierLoc;
+@@ -2739,6 +2800,10 @@
+   friend class ASTStmtReader;
+   friend class ASTStmtWriter;
+ };
++static_assert(llvm::AlignOf<DependentScopeDeclRefExpr>::Alignment >=
++                  llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "DependentScopeDeclRefExpr");
+ 
+ /// Represents an expression -- generally a full-expression -- that
+ /// introduces cleanups to be run at the end of the sub-expression's
+@@ -2810,6 +2875,10 @@
+   // Iterators
+   child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
+ };
++static_assert(
++    llvm::AlignOf<ExprWithCleanups>::Alignment >=
++        llvm::AlignOf<ExprWithCleanups::CleanupObject>::Alignment,
++    "Alignment is insufficient for objects appended to ExprWithCleanups");
+ 
+ /// \brief Describes an explicit type conversion that uses functional
+ /// notion but could not be resolved because one or more arguments are
+@@ -2930,6 +2999,10 @@
+     return child_range(begin, begin + NumArgs);
+   }
+ };
++static_assert(llvm::AlignOf<CXXUnresolvedConstructExpr>::Alignment >=
++                  llvm::AlignOf<Expr *>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "CXXUnresolvedConstructExpr");
+ 
+ /// \brief Represents a C++ member access expression where the actual
+ /// member referenced could not be resolved because the base
+@@ -2938,7 +3011,8 @@
+ /// Like UnresolvedMemberExprs, these can be either implicit or
+ /// explicit accesses.  It is only possible to get one of these with
+ /// an implicit access if a qualifier is provided.
+-class CXXDependentScopeMemberExpr : public Expr {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) CXXDependentScopeMemberExpr
++    : public Expr {
+   /// \brief The expression for the base pointer or class reference,
+   /// e.g., the \c x in x.f.  Can be null in implicit accesses.
+   Stmt *Base;
+@@ -3177,6 +3251,10 @@
+   friend class ASTStmtReader;
+   friend class ASTStmtWriter;
+ };
++static_assert(llvm::AlignOf<CXXDependentScopeMemberExpr>::Alignment >=
++                  llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "CXXDependentScopeMemberExpr");
+ 
+ /// \brief Represents a C++ member access expression for which lookup
+ /// produced a set of overloaded functions.
+@@ -3193,7 +3271,8 @@
+ /// In the final AST, an explicit access always becomes a MemberExpr.
+ /// An implicit access may become either a MemberExpr or a
+ /// DeclRefExpr, depending on whether the member is static.
+-class UnresolvedMemberExpr : public OverloadExpr {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) UnresolvedMemberExpr
++    : public OverloadExpr {
+   /// \brief Whether this member expression used the '->' operator or
+   /// the '.' operator.
+   bool IsArrow : 1;
+@@ -3316,6 +3395,21 @@
+     return child_range(&Base, &Base + 1);
+   }
+ };
++static_assert(
++    llvm::AlignOf<UnresolvedMemberExpr>::Alignment >=
++        llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++    "Alignment is insufficient for objects appended to UnresolvedMemberExpr");
++
++inline ASTTemplateKWAndArgsInfo *OverloadExpr::getTemplateKWAndArgsInfo() {
++  if (!HasTemplateKWAndArgsInfo)
++    return nullptr;
++  if (isa<UnresolvedLookupExpr>(this))
++    return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
++        cast<UnresolvedLookupExpr>(this) + 1);
++  else
++    return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
++        cast<UnresolvedMemberExpr>(this) + 1);
++}
+ 
+ /// \brief Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
+ ///
+@@ -3438,15 +3532,6 @@
+   }
+ };
+ 
+-inline ASTTemplateKWAndArgsInfo *OverloadExpr::getTemplateKWAndArgsInfo() {
+-  if (!HasTemplateKWAndArgsInfo) return nullptr;
+-  if (isa<UnresolvedLookupExpr>(this))
+-    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
+-      (cast<UnresolvedLookupExpr>(this) + 1);
+-  else
+-    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
+-      (cast<UnresolvedMemberExpr>(this) + 1);
+-}
+ 
+ /// \brief Represents an expression that computes the length of a parameter
+ /// pack.
+@@ -3709,6 +3794,10 @@
+ 
+   child_range children() { return child_range(); }
+ };
++static_assert(
++    llvm::AlignOf<FunctionParmPackExpr>::Alignment >=
++        llvm::AlignOf<ParmVarDecl *>::Alignment,
++    "Alignment is insufficient for objects appended to FunctionParmPackExpr");
+ 
+ /// \brief Represents a prvalue temporary that is written into memory so that
+ /// a reference can bind to it.
+--- tools/clang/include/clang/AST/ExprObjC.h	2014-12-18 09:13:56.000000000 -0800
++++ tools/clang/include/clang/AST/ExprObjC.h	2015-07-17 16:43:46.499286743 -0700
+@@ -201,6 +201,10 @@
+     
+   friend class ASTStmtReader;
+ };
++static_assert(
++    llvm::AlignOf<ObjCArrayLiteral>::Alignment >=
++        llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCArrayLiteral");
+ 
+ /// \brief An element in an Objective-C dictionary literal.
+ ///
+@@ -231,6 +235,7 @@
+ /// ObjCDictionaryLiteral - AST node to represent objective-c dictionary 
+ /// literals; as in:  @{@"name" : NSUserName(), @"date" : [NSDate date] };
+ class ObjCDictionaryLiteral : public Expr {
++public:
+   /// \brief Key/value pair used to store the key and value of a given element.
+   ///
+   /// Objects of this type are stored directly after the expression.
+@@ -251,6 +256,7 @@
+     unsigned NumExpansionsPlusOne;
+   };
+ 
++private:
+   /// \brief The number of elements in this dictionary literal.
+   unsigned NumElements : 31;
+   
+@@ -341,6 +347,7 @@
+   child_range children() { 
+     // Note: we're taking advantage of the layout of the KeyValuePair struct
+     // here. If that struct changes, this code will need to change as well.
++    static_assert(sizeof(KeyValuePair) == sizeof(Stmt *) * 2, "");
+     return child_range(reinterpret_cast<Stmt **>(this + 1),
+                        reinterpret_cast<Stmt **>(this + 1) + NumElements * 2);
+   }
+@@ -348,7 +355,14 @@
+   friend class ASTStmtReader;
+   friend class ASTStmtWriter;
+ };
+-
++static_assert(
++    llvm::AlignOf<ObjCDictionaryLiteral>::Alignment >=
++        llvm::AlignOf<ObjCDictionaryLiteral::KeyValuePair>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCDictionaryLiteral");
++static_assert(
++    llvm::AlignOf<ObjCDictionaryLiteral::KeyValuePair>::Alignment >=
++        llvm::AlignOf<ObjCDictionaryLiteral::ExpansionData>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCDictionaryLiteral");
+ 
+ /// ObjCEncodeExpr, used for \@encode in Objective-C.  \@encode has the same
+ /// type and behavior as StringLiteral except that the string initializer is
+@@ -1394,6 +1408,17 @@
+   friend class ASTStmtReader;
+   friend class ASTStmtWriter;
+ };
++static_assert(
++    llvm::AlignOf<ObjCMessageExpr>::Alignment >=
++        llvm::AlignOf<void *>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCMessageExpr");
++static_assert(
++    llvm::AlignOf<void *>::Alignment >= llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCMessageExpr");
++static_assert(
++    llvm::AlignOf<Expr *>::Alignment >=
++        llvm::AlignOf<SourceLocation>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCMessageExpr");
+ 
+ /// ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
+ /// (similar in spirit to MemberExpr).
+--- tools/clang/include/clang/AST/Stmt.h	2015-01-12 02:17:46.000000000 -0800
++++ tools/clang/include/clang/AST/Stmt.h	2015-07-17 16:43:46.502138721 -0700
+@@ -865,7 +865,10 @@
+     return T->getStmtClass() == AttributedStmtClass;
+   }
+ };
+-
++static_assert(
++    llvm::AlignOf<AttributedStmt>::Alignment >=
++        llvm::AlignOf<Attr *>::Alignment,
++    "Alignment is insufficient for objects appended to AttributedStmt");
+ 
+ /// IfStmt - This represents an if/then/else.
+ ///
+@@ -2070,8 +2073,10 @@
+   /// \brief Construct an empty captured statement.
+   CapturedStmt(EmptyShell Empty, unsigned NumCaptures);
+ 
+-  Stmt **getStoredStmts() const {
+-    return reinterpret_cast<Stmt **>(const_cast<CapturedStmt *>(this) + 1);
++  Stmt **getStoredStmts() { return reinterpret_cast<Stmt **>(this + 1); }
++
++  Stmt *const *getStoredStmts() const {
++    return reinterpret_cast<Stmt *const *>(this + 1);
+   }
+ 
+   Capture *getStoredCaptures() const;
+@@ -2090,14 +2095,12 @@
+ 
+   /// \brief Retrieve the statement being captured.
+   Stmt *getCapturedStmt() { return getStoredStmts()[NumCaptures]; }
+-  const Stmt *getCapturedStmt() const {
+-    return const_cast<CapturedStmt *>(this)->getCapturedStmt();
+-  }
++  const Stmt *getCapturedStmt() const { return getStoredStmts()[NumCaptures]; }
+ 
+   /// \brief Retrieve the outlined function declaration.
+   CapturedDecl *getCapturedDecl() { return CapDeclAndKind.getPointer(); }
+   const CapturedDecl *getCapturedDecl() const {
+-    return const_cast<CapturedStmt *>(this)->getCapturedDecl();
++    return CapDeclAndKind.getPointer();
+   }
+ 
+   /// \brief Set the outlined function declaration.
+@@ -2158,18 +2161,36 @@
+   typedef Expr **capture_init_iterator;
+   typedef llvm::iterator_range<capture_init_iterator> capture_init_range;
+ 
+-  capture_init_range capture_inits() const {
++  /// \brief Const iterator that walks over the capture initialization
++  /// arguments.
++  typedef Expr *const *const_capture_init_iterator;
++  typedef llvm::iterator_range<const_capture_init_iterator>
++      const_capture_init_range;
++
++  capture_init_range capture_inits() {
+     return capture_init_range(capture_init_begin(), capture_init_end());
+   }
+ 
++  const_capture_init_range capture_inits() const {
++    return const_capture_init_range(capture_init_begin(), capture_init_end());
++  }
++
+   /// \brief Retrieve the first initialization argument.
+-  capture_init_iterator capture_init_begin() const {
++  capture_init_iterator capture_init_begin() {
+     return reinterpret_cast<Expr **>(getStoredStmts());
+   }
+ 
++  const_capture_init_iterator capture_init_begin() const {
++    return reinterpret_cast<Expr *const *>(getStoredStmts());
++  }
++
+   /// \brief Retrieve the iterator pointing one past the last initialization
+   /// argument.
+-  capture_init_iterator capture_init_end() const {
++  capture_init_iterator capture_init_end() {
++    return capture_init_begin() + NumCaptures;
++  }
++
++  const_capture_init_iterator capture_init_end() const {
+     return capture_init_begin() + NumCaptures;
+   }
+ 
+@@ -2191,6 +2212,13 @@
+ 
+   friend class ASTStmtReader;
+ };
++static_assert(llvm::AlignOf<CapturedStmt>::Alignment >=
++                  llvm::AlignOf<Stmt *>::Alignment,
++              "Alignment is insufficient for objects appended to CapturedStmt");
++// Code re-aligns before Capture[]
++static_assert(llvm::AlignOf<CapturedStmt>::Alignment >=
++                  llvm::AlignOf<CapturedStmt::Capture>::Alignment,
++              "Alignment is insufficient for objects appended to CapturedStmt");
+ 
+ }  // end namespace clang
+ 
+--- tools/clang/include/clang/AST/StmtCXX.h	2014-05-05 23:48:52.000000000 -0700
++++ tools/clang/include/clang/AST/StmtCXX.h	2015-07-17 16:43:46.503758907 -0700
+@@ -118,6 +118,9 @@
+ 
+   friend class ASTStmtReader;
+ };
++static_assert(llvm::AlignOf<CXXTryStmt>::Alignment >=
++                  llvm::AlignOf<Stmt *>::Alignment,
++              "Alignment is insufficient for objects appended to CXXTryStmt");
+ 
+ /// CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for
+ /// statement, represented as 'for (range-declarator : range-expression)'.
+--- tools/clang/include/clang/AST/StmtObjC.h	2014-05-05 23:48:52.000000000 -0700
++++ tools/clang/include/clang/AST/StmtObjC.h	2015-07-17 16:43:46.505254168 -0700
+@@ -249,6 +249,9 @@
+                        getStmts() + 1 + NumCatchStmts + HasFinally);
+   }
+ };
++static_assert(
++    llvm::AlignOf<ObjCAtTryStmt>::Alignment >= llvm::AlignOf<Stmt *>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCAtTryStmt");
+ 
+ /// \brief Represents Objective-C's \@synchronized statement.
+ ///
+--- tools/clang/include/clang/AST/TemplateBase.h	2015-01-14 03:29:14.000000000 -0800
++++ tools/clang/include/clang/AST/TemplateBase.h	2015-07-17 16:43:46.506876445 -0700
+@@ -360,6 +360,20 @@
+   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const;
+ };
+ 
++static_assert(llvm::AlignOf<TemplateSpecializationType>::Alignment >=
++                  llvm::AlignOf<TemplateArgument>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "TemplateSpecializationType");
++static_assert(llvm::AlignOf<TemplateArgument>::Alignment >=
++                  llvm::AlignOf<QualType>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "TemplateSpecializationType");
++
++static_assert(llvm::AlignOf<DependentTemplateSpecializationType>::Alignment >=
++                  llvm::AlignOf<TemplateArgument>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "DependentTemplateSpecializationType");
++
+ /// Location information for a TemplateArgument.
+ struct TemplateArgumentLocInfo {
+ private:
+@@ -604,6 +618,10 @@
+   void copyInto(TemplateArgumentListInfo &List) const;
+   static std::size_t sizeFor(unsigned NumTemplateArgs);
+ };
++static_assert(llvm::AlignOf<ASTTemplateArgumentListInfo>::Alignment >=
++                  llvm::AlignOf<TemplateArgumentLoc>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "ASTTemplateArgumentListInfo");
+ 
+ /// \brief Extends ASTTemplateArgumentListInfo with the source location
+ /// information for the template keyword; this is used as part of the
+@@ -640,6 +658,18 @@
+ 
+   static std::size_t sizeFor(unsigned NumTemplateArgs);
+ };
++static_assert(llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment >=
++                  llvm::AlignOf<TemplateArgumentLoc>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "ASTTemplateKWAndArgsInfo");
++static_assert(llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment >=
++                  llvm::AlignOf<SourceLocation>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "ASTTemplateKWAndArgsInfo");
++static_assert(llvm::AlignOf<TemplateArgumentLoc>::Alignment >=
++                  llvm::AlignOf<SourceLocation>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "ASTTemplateKWAndArgsInfo");
+ 
+ const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
+                                     const TemplateArgument &Arg);
+--- tools/clang/include/clang/AST/TemplateName.h	2014-05-10 13:57:56.000000000 -0700
++++ tools/clang/include/clang/AST/TemplateName.h	2015-07-17 16:43:46.508333537 -0700
+@@ -108,6 +108,10 @@
+   iterator begin() const { return getStorage(); }
+   iterator end() const { return getStorage() + size(); }
+ };
++static_assert(llvm::AlignOf<OverloadedTemplateStorage>::Alignment >=
++                  llvm::AlignOf<NamedDecl *>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "OverloadedTemplateStorage");
+ 
+ /// \brief A structure for storing an already-substituted template template
+ /// parameter pack.
+--- tools/clang/include/clang/AST/Type.h	2015-01-14 03:29:14.000000000 -0800
++++ tools/clang/include/clang/AST/Type.h	2015-07-17 16:43:46.512517865 -0700
+@@ -2991,11 +2991,13 @@
+     assert(hasAnyConsumedParams());
+ 
+     // Find the end of the exceptions.
+-    Expr *const *eh_end = reinterpret_cast<Expr *const *>(param_type_end());
+-    if (getExceptionSpecType() != EST_ComputedNoexcept)
+-      eh_end += NumExceptions;
+-    else
++    Expr *const *eh_end = reinterpret_cast<Expr *const *>(exception_end());
++    if (getExceptionSpecType() == EST_ComputedNoexcept)
+       eh_end += 1; // NoexceptExpr
++    // The memory layout of these types isn't handled here, so
++    // hopefully this is never called for them?
++    assert(getExceptionSpecType() != EST_Uninstantiated &&
++           getExceptionSpecType() != EST_Unevaluated);
+ 
+     return reinterpret_cast<const bool*>(eh_end);
+   }
+@@ -3167,7 +3169,29 @@
+                       param_type_iterator ArgTys, unsigned NumArgs,
+                       const ExtProtoInfo &EPI, const ASTContext &Context);
+ };
+-
++static_assert(
++    llvm::AlignOf<FunctionProtoType>::Alignment >=
++        llvm::AlignOf<QualType>::Alignment,
++    "Alignment is insufficient for objects appended to FunctionProtoType");
++// After QualType[], there can be one of 4 options: more QualType, Expr*, 2x
++// FunctionDecl*, FunctionDecl*
++static_assert(
++    llvm::AlignOf<QualType>::Alignment >= llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to FunctionProtoType");
++static_assert(
++    llvm::AlignOf<QualType>::Alignment >=
++        llvm::AlignOf<FunctionDecl *>::Alignment,
++    "Alignment is insufficient for objects appended to FunctionProtoType");
++// And then, after any of those options, comes bool[]
++static_assert(
++    llvm::AlignOf<QualType>::Alignment >= llvm::AlignOf<bool>::Alignment,
++    "Alignment is insufficient for objects appended to FunctionProtoType");
++static_assert(
++    llvm::AlignOf<Expr *>::Alignment >= llvm::AlignOf<bool>::Alignment,
++    "Alignment is insufficient for objects appended to FunctionProtoType");
++static_assert(
++    llvm::AlignOf<FunctionDecl *>::Alignment >= llvm::AlignOf<bool>::Alignment,
++    "Alignment is insufficient for objects appended to FunctionProtoType");
+ 
+ /// \brief Represents the dependent type named by a dependently-scoped
+ /// typename using declaration, e.g.
+@@ -3777,8 +3801,9 @@
+ /// TemplateArguments, followed by a QualType representing the
+ /// non-canonical aliased type when the template is a type alias
+ /// template.
+-class TemplateSpecializationType
+-  : public Type, public llvm::FoldingSetNode {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
++    : public Type,
++      public llvm::FoldingSetNode {
+   /// \brief The name of the template being specialized.  This is
+   /// either a TemplateName::Template (in which case it is a
+   /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
+@@ -3900,6 +3925,13 @@
+     return T->getTypeClass() == TemplateSpecialization;
+   }
+ };
++// static_assert(llvm::AlignOf<TemplateSpecializationType>::Alignment >=
++// llvm::AlignOf<TemplateArgument>::Alignment, "Alignment is insufficient for
++// objects appended to TemplateSpecializationType");
++// static_assert(llvm::AlignOf<TemplateArgument>::Alignment >=
++// llvm::AlignOf<QualType>::Alignment, "Alignment is insufficient for objects
++// appended to TemplateSpecializationType");
++// ^ Moved after class TemplateArgument, as it is is forward declared here.
+ 
+ /// \brief The injected class name of a C++ class template or class
+ /// template partial specialization.  Used to record that a type was
+@@ -4175,8 +4207,9 @@
+ /// DependentTemplateSpecializationType - Represents a template
+ /// specialization type whose template cannot be resolved, e.g.
+ ///   A<T>::template B<T>
+-class DependentTemplateSpecializationType :
+-  public TypeWithKeyword, public llvm::FoldingSetNode {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentTemplateSpecializationType
++    : public TypeWithKeyword,
++      public llvm::FoldingSetNode {
+ 
+   /// \brief The nested name specifier containing the qualifier.
+   NestedNameSpecifier *NNS;
+@@ -4241,6 +4274,10 @@
+     return T->getTypeClass() == DependentTemplateSpecialization;
+   }
+ };
++// static_assert(llvm::AlignOf<DependentTemplateSpecializationType>::Alignment
++// >= llvm::AlignOf<TemplateArgument>::Alignment, "Alignment is insufficient for
++// objects appended to DependentTemplateSpecializationType");
++// ^ Moved after class TemplateArgument, as it is is forward declared here.
+ 
+ /// \brief Represents a pack expansion of types.
+ ///
+@@ -4456,6 +4493,10 @@
+                       ObjCProtocolDecl *const *protocols,
+                       unsigned NumProtocols);
+ };
++static_assert(
++    llvm::AlignOf<ObjCObjectTypeImpl>::Alignment >=
++        llvm::AlignOf<ObjCProtocolDecl *>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCObjectTypeImpl");
+ 
+ inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
+   return reinterpret_cast<ObjCProtocolDecl**>(
+--- tools/clang/include/clang/AST/TypeLoc.h	2014-10-24 06:52:55.000000000 -0700
++++ tools/clang/include/clang/AST/TypeLoc.h	2015-07-17 16:43:46.514327822 -0700
+@@ -199,6 +199,7 @@
+ 
+ /// \brief Return the TypeLoc for a type source info.
+ inline TypeLoc TypeSourceInfo::getTypeLoc() const {
++  // TODO: is this alignment already sufficient?
+   return TypeLoc(Ty, const_cast<void*>(static_cast<const void*>(this + 1)));
+ }
+ 
+--- tools/clang/include/clang/CodeGen/CGFunctionInfo.h	2014-12-12 15:41:25.000000000 -0800
++++ tools/clang/include/clang/CodeGen/CGFunctionInfo.h	2015-07-17 16:43:46.515714903 -0700
+@@ -333,11 +333,13 @@
+ /// CGFunctionInfo - Class to encapsulate the information about a
+ /// function definition.
+ class CGFunctionInfo : public llvm::FoldingSetNode {
++public:
+   struct ArgInfo {
+     CanQualType type;
+     ABIArgInfo info;
+   };
+ 
++private:
+   /// The LLVM::CallingConv to use for this function (as specified by the
+   /// user).
+   unsigned CallingConvention : 8;
+@@ -500,6 +502,10 @@
+     }
+   }
+ };
++static_assert(
++    llvm::AlignOf<CGFunctionInfo>::Alignment >=
++        llvm::AlignOf<CGFunctionInfo::ArgInfo>::Alignment,
++    "Alignment is insufficient for objects appended to CGFunctionInfo");
+ 
+ }  // end namespace CodeGen
+ }  // end namespace clang
+--- tools/clang/include/clang/Lex/MacroArgs.h	2014-08-13 12:25:19.000000000 -0400
++++ tools/clang/include/clang/Lex/MacroArgs.h	2015-07-17 22:23:39.000000000 -0400
+@@ -15,13 +15,13 @@
+ #define LLVM_CLANG_LEX_MACROARGS_H
+ 
+ #include "clang/Basic/LLVM.h"
++#include "clang/Lex/Token.h"
+ #include "llvm/ADT/ArrayRef.h"
+ #include <vector>
+ 
+ namespace clang {
+   class MacroInfo;
+   class Preprocessor;
+-  class Token;
+   class SourceLocation;
+ 
+ /// MacroArgs - An instance of this class captures information about
+@@ -120,6 +120,9 @@
+   /// its freelist.
+   MacroArgs *deallocate();
+ };
++static_assert(llvm::AlignOf<MacroArgs>::Alignment >=
++                  llvm::AlignOf<Token>::Alignment,
++              "Alignment is insufficient for objects appended to MacroArgs");
+ 
+ }  // end namespace clang
+ 
+--- tools/clang/include/clang/Lex/MacroInfo.h	2014-08-13 12:25:19.000000000 -0400
++++ tools/clang/include/clang/Lex/MacroInfo.h	2015-07-18 01:52:39.590867365 -0400
+@@ -17,11 +17,15 @@
+ 
+ #include "clang/Lex/Token.h"
+ #include "llvm/ADT/ArrayRef.h"
++#include "llvm/ADT/FoldingSet.h"
++#include "llvm/ADT/PointerIntPair.h"
+ #include "llvm/ADT/SmallVector.h"
+ #include "llvm/Support/Allocator.h"
+ #include <cassert>
+ 
+ namespace clang {
++class Module;
++class ModuleMacro;
+ class Preprocessor;
+ 
+ /// \brief Encapsulates the data about a macro definition (e.g. its tokens).
+@@ -294,6 +298,9 @@
+ 
+   friend class Preprocessor;
+ };
++static_assert(llvm::AlignOf<MacroInfo>::Alignment >=
++                  llvm::AlignOf<unsigned>::Alignment,
++              "Alignment is insufficient for objects appended to MacroInfo");
+ 
+ class DefMacroDirective;
+ 
+@@ -517,6 +524,75 @@
+   static bool classof(const DefMacroDirective *) { return true; }
+ };
+ 
++/// \brief Represents a macro directive exported by a module.
++///
++/// There's an instance of this class for every macro #define or #undef that is
++/// the final directive for a macro name within a module. These entities also
++/// represent the macro override graph.
++///
++/// These are stored in a FoldingSet in the preprocessor.
++class ModuleMacro : public llvm::FoldingSetNode {
++  /// The name defined by the macro.
++  IdentifierInfo *II;
++  /// The body of the #define, or nullptr if this is a #undef.
++  MacroInfo *Macro;
++  /// The module that exports this macro.
++  Module *OwningModule;
++  /// The number of module macros that override this one.
++  unsigned NumOverriddenBy;
++  /// The number of modules whose macros are directly overridden by this one.
++  unsigned NumOverrides;
++  // ModuleMacro *OverriddenMacros[NumOverrides];
++
++  friend class Preprocessor;
++
++  ModuleMacro(Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro,
++              ArrayRef<ModuleMacro *> Overrides)
++      : II(II), Macro(Macro), OwningModule(OwningModule), NumOverriddenBy(0),
++        NumOverrides(Overrides.size()) {
++    std::copy(Overrides.begin(), Overrides.end(),
++              reinterpret_cast<ModuleMacro **>(this + 1));
++  }
++
++public:
++  static ModuleMacro *create(Preprocessor &PP, Module *OwningModule,
++                             IdentifierInfo *II, MacroInfo *Macro,
++                             ArrayRef<ModuleMacro *> Overrides);
++
++  void Profile(llvm::FoldingSetNodeID &ID) const {
++    return Profile(ID, OwningModule, II);
++  }
++  static void Profile(llvm::FoldingSetNodeID &ID, Module *OwningModule,
++                      IdentifierInfo *II) {
++    ID.AddPointer(OwningModule);
++    ID.AddPointer(II);
++  }
++
++  /// Get the ID of the module that exports this macro.
++  Module *getOwningModule() const { return OwningModule; }
++
++  /// Get definition for this exported #define, or nullptr if this
++  /// represents a #undef.
++  MacroInfo *getMacroInfo() const { return Macro; }
++
++  /// Iterators over the overridden module IDs.
++  /// \{
++  typedef ModuleMacro *const *overrides_iterator;
++  overrides_iterator overrides_begin() const {
++    return reinterpret_cast<overrides_iterator>(this + 1);
++  }
++  overrides_iterator overrides_end() const {
++    return overrides_begin() + NumOverrides;
++  }
++  ArrayRef<ModuleMacro *> overrides() const {
++    return llvm::makeArrayRef(overrides_begin(), overrides_end());
++  }
++  /// \}
++
++  /// Get the number of macros that override this one.
++  unsigned getNumOverridingMacros() const { return NumOverriddenBy; }
++};
++
+ /// \brief A directive for an undefined macro.
+ class UndefMacroDirective : public MacroDirective  {
+ public:
+@@ -550,6 +626,9 @@
+   }
+   static bool classof(const VisibilityMacroDirective *) { return true; }
+ };
++static_assert(llvm::AlignOf<ModuleMacro>::Alignment >=
++                  llvm::AlignOf<ModuleMacro *>::Alignment,
++              "Alignment is insufficient for objects appended to ModuleMacro");
+ 
+ inline unsigned *MacroDirective::getModuleDataStart() {
+   if (auto *Def = dyn_cast<DefMacroDirective>(this))
+--- tools/clang/include/clang/Sema/AttributeList.h	2015-01-20 11:27:49.000000000 -0800
++++ tools/clang/include/clang/Sema/AttributeList.h	2015-07-17 16:43:46.520539511 -0700
+@@ -135,9 +135,7 @@
+   AttributeList *NextInPool;
+ 
+   /// Arguments, if any, are stored immediately following the object.
+-  ArgsUnion *getArgsBuffer() {
+-    return reinterpret_cast<ArgsUnion*>(this+1);
+-  }
++  ArgsUnion *getArgsBuffer() { return reinterpret_cast<ArgsUnion *>(this + 1); }
+   ArgsUnion const *getArgsBuffer() const {
+     return reinterpret_cast<ArgsUnion const *>(this+1);
+   }
+@@ -468,6 +466,26 @@
+   /// a Spelling enumeration, the value UINT_MAX is returned.
+   unsigned getSemanticSpelling() const;
+ };
++static_assert(
++    llvm::AlignOf<AttributeList>::Alignment >=
++        llvm::AlignOf<ArgsUnion>::Alignment,
++    "Alignment is insufficient for objects appended to AttributeList");
++static_assert(
++    llvm::AlignOf<ArgsUnion>::Alignment >=
++        llvm::AlignOf<AvailabilityChange>::Alignment,
++    "Alignment is insufficient for objects appended to AttributeList");
++static_assert(
++    llvm::AlignOf<ArgsUnion>::Alignment >=
++        llvm::AlignOf<AttributeList::TypeTagForDatatypeData>::Alignment,
++    "Alignment is insufficient for objects appended to AttributeList");
++static_assert(
++    llvm::AlignOf<AttributeList>::Alignment >=
++        llvm::AlignOf<ParsedType>::Alignment,
++    "Alignment is insufficient for objects appended to AttributeList");
++static_assert(
++    llvm::AlignOf<AttributeList>::Alignment >=
++        llvm::AlignOf<AttributeList::PropertyData>::Alignment,
++    "Alignment is insufficient for objects appended to AttributeList");
+ 
+ /// A factory, from which one makes pools, from which one creates
+ /// individual attributes which are deallocated with the pool.
+--- tools/clang/include/clang/Sema/CodeCompleteConsumer.h	2014-05-05 23:48:52.000000000 -0700
++++ tools/clang/include/clang/Sema/CodeCompleteConsumer.h	2015-07-17 16:43:46.522097320 -0700
+@@ -493,6 +493,14 @@
+   /// which is mainly useful for debugging.
+   std::string getAsString() const;
+ };
++static_assert(
++    llvm::AlignOf<CodeCompletionString>::Alignment >=
++        llvm::AlignOf<CodeCompletionString::Chunk>::Alignment,
++    "Alignment is insufficient for objects appended to CodeCompletionString");
++static_assert(
++    llvm::AlignOf<CodeCompletionString::Chunk>::Alignment >=
++        llvm::AlignOf<const char *>::Alignment,
++    "Alignment is insufficient for objects appended to CodeCompletionString");
+ 
+ /// \brief An allocator used specifically for the purpose of code completion.
+ class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
+--- tools/clang/include/clang/Sema/ParsedTemplate.h	2014-05-05 23:48:52.000000000 -0700
++++ tools/clang/include/clang/Sema/ParsedTemplate.h	2015-07-17 16:43:46.523177530 -0700
+@@ -205,6 +205,10 @@
+       free(this); 
+     }
+   };
++  static_assert(
++      llvm::AlignOf<TemplateIdAnnotation>::Alignment >=
++          llvm::AlignOf<ParsedTemplateArgument>::Alignment,
++      "Alignment is insufficient for objects appended to TemplateIdAnnotation");
+ 
+   /// Retrieves the range of the given template parameter lists.
+   SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params,
+--- tools/clang/lib/AST/Decl.cpp	2015-05-04 11:23:59.000000000 -0700
++++ tools/clang/lib/AST/Decl.cpp	2015-07-17 16:43:46.525788978 -0700
+@@ -3064,8 +3064,8 @@
+                              const TemplateArgumentListInfo &TemplateArgs) {
+   assert(TemplateOrSpecialization.isNull());
+   size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
+-  Size += Templates.size() * sizeof(FunctionTemplateDecl*);
+   Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
++  Size += Templates.size() * sizeof(FunctionTemplateDecl *);
+   void *Buffer = Context.Allocate(Size);
+   DependentFunctionTemplateSpecializationInfo *Info =
+     new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
+@@ -3078,8 +3078,8 @@
+                                       const TemplateArgumentListInfo &TArgs)
+   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
+ 
+-  d.NumTemplates = Ts.size();
+-  d.NumArgs = TArgs.size();
++  NumTemplates = Ts.size();
++  NumArgs = TArgs.size();
+ 
+   FunctionTemplateDecl **TsArray =
+     const_cast<FunctionTemplateDecl**>(getTemplates());
+--- tools/clang/lib/AST/DeclBase.cpp	2014-11-17 15:36:45.000000000 -0800
++++ tools/clang/lib/AST/DeclBase.cpp	2015-07-17 17:03:06.999226816 -0700
+@@ -45,14 +45,28 @@
+   getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
+ }
+ 
++#define DECL(DERIVED, BASE)                                                    \
++  static_assert(llvm::AlignOf<uint64_t>::Alignment >=                          \
++                    llvm::AlignOf<DERIVED##Decl>::Alignment,                   \
++                "Alignment is insufficient for objects appended to all Decl "  \
++                "subclasses");
++#define ABSTRACT_DECL(DECL)
++#include "clang/AST/DeclNodes.inc"
++
+ void *Decl::operator new(std::size_t Size, const ASTContext &Context,
+                          unsigned ID, std::size_t Extra) {
+   // Allocate an extra 8 bytes worth of storage, which ensures that the
+   // resulting pointer will still be 8-byte aligned. 
+-  void *Start = Context.Allocate(Size + Extra + 8);
+-  void *Result = (char*)Start + 8;
++  static_assert(sizeof(unsigned) * 2 >= llvm::AlignOf<uint64_t>::Alignment,
++      "sizeof(unsigned) * 2 < llvm::AlignOf<uint64_t>::Alignment!");
++
++  void *Start = Context.Allocate(Size + Extra + 8, 8U);
++  void *Result = reinterpret_cast<void*>(
++      reinterpret_cast<unsigned char*>(
++        reinterpret_cast<unsigned char*>(Start) + 8));
+ 
+-  unsigned *PrefixPtr = (unsigned *)Result - 2;
++  unsigned *PrefixPtr =
++    reinterpret_cast<unsigned*>(reinterpret_cast<unsigned*>(Result) - 2);
+ 
+   // Zero out the first 4 bytes; this is used to store the owning module ID.
+   PrefixPtr[0] = 0;
+--- tools/clang/lib/AST/Expr.cpp	2015-01-12 02:17:46.000000000 -0800
++++ tools/clang/lib/AST/Expr.cpp	2015-07-17 16:43:46.530620842 -0700
+@@ -399,10 +399,15 @@
+     Size += sizeof(NestedNameSpecifierLoc);
+   if (FoundD)
+     Size += sizeof(NamedDecl *);
+-  if (TemplateArgs)
++  if (TemplateArgs) {
++    Size = llvm::RoundUpToAlignment(Size,
++                                    llvm::alignOf<ASTTemplateKWAndArgsInfo>());
+     Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
+-  else if (TemplateKWLoc.isValid())
++  } else if (TemplateKWLoc.isValid()) {
++    Size = llvm::RoundUpToAlignment(Size,
++                                    llvm::alignOf<ASTTemplateKWAndArgsInfo>());
+     Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
++  }
+ 
+   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
+   return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
+@@ -420,8 +425,11 @@
+     Size += sizeof(NestedNameSpecifierLoc);
+   if (HasFoundDecl)
+     Size += sizeof(NamedDecl *);
+-  if (HasTemplateKWAndArgsInfo)
++  if (HasTemplateKWAndArgsInfo) {
++    Size = llvm::RoundUpToAlignment(Size,
++                                    llvm::alignOf<ASTTemplateKWAndArgsInfo>());
+     Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
++  }
+ 
+   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
+   return new (Mem) DeclRefExpr(EmptyShell());
+@@ -3871,7 +3879,8 @@
+                            SourceLocation ColonOrEqualLoc,
+                            bool UsesColonSyntax, Expr *Init) {
+   void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
+-                         sizeof(Stmt *) * (IndexExprs.size() + 1), 8);
++                             sizeof(Stmt *) * (IndexExprs.size() + 1),
++                         llvm::alignOf<DesignatedInitExpr>());
+   return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
+                                       ColonOrEqualLoc, UsesColonSyntax,
+                                       IndexExprs, Init);
+--- tools/clang/lib/AST/ExprCXX.cpp	2014-09-25 17:28:20.000000000 -0700
++++ tools/clang/lib/AST/ExprCXX.cpp	2015-07-17 16:43:46.532400798 -0700
+@@ -1070,14 +1070,14 @@
+ }
+ 
+ ArrayRef<VarDecl *> 
+-LambdaExpr::getCaptureInitIndexVars(capture_init_iterator Iter) const {
++LambdaExpr::getCaptureInitIndexVars(const_capture_init_iterator Iter) const {
+   assert(HasArrayIndexVars && "No array index-var data?");
+   
+   unsigned Index = Iter - capture_init_begin();
+   assert(Index < getLambdaClass()->getLambdaData().NumCaptures &&
+          "Capture index out-of-range");
+-  VarDecl **IndexVars = getArrayIndexVars();
+-  unsigned *IndexStarts = getArrayIndexStarts();
++  VarDecl *const *IndexVars = getArrayIndexVars();
++  const unsigned *IndexStarts = getArrayIndexStarts();
+   return llvm::makeArrayRef(IndexVars + IndexStarts[Index],
+                             IndexVars + IndexStarts[Index + 1]);
+ }
+@@ -1098,8 +1098,12 @@
+ }
+ 
+ CompoundStmt *LambdaExpr::getBody() const {
++  // FIXME: this mutation in getBody is bogus. It should be
++  // initialized in ASTStmtReader::VisitLambdaExpr, but for reasons I
++  // don't understand, that doesn't work.
+   if (!getStoredStmts()[NumCaptures])
+-    getStoredStmts()[NumCaptures] = getCallOperator()->getBody();
++    *const_cast<clang::Stmt **>(&getStoredStmts()[NumCaptures]) =
++        getCallOperator()->getBody();
+     
+   return reinterpret_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
+ }
+--- tools/clang/lib/AST/Stmt.cpp	2014-12-14 23:07:06.000000000 -0800
++++ tools/clang/lib/AST/Stmt.cpp	2015-07-17 16:43:46.536947418 -0700
+@@ -816,7 +816,7 @@
+ CXXTryStmt *CXXTryStmt::Create(const ASTContext &C, SourceLocation tryLoc,
+                                Stmt *tryBlock, ArrayRef<Stmt*> handlers) {
+   std::size_t Size = sizeof(CXXTryStmt);
+-  Size += ((handlers.size() + 1) * sizeof(Stmt));
++  Size += ((handlers.size() + 1) * sizeof(Stmt *));
+ 
+   void *Mem = C.Allocate(Size, llvm::alignOf<CXXTryStmt>());
+   return new (Mem) CXXTryStmt(tryLoc, tryBlock, handlers);
+@@ -825,7 +825,7 @@
+ CXXTryStmt *CXXTryStmt::Create(const ASTContext &C, EmptyShell Empty,
+                                unsigned numHandlers) {
+   std::size_t Size = sizeof(CXXTryStmt);
+-  Size += ((numHandlers + 1) * sizeof(Stmt));
++  Size += ((numHandlers + 1) * sizeof(Stmt *));
+ 
+   void *Mem = C.Allocate(Size, llvm::alignOf<CXXTryStmt>());
+   return new (Mem) CXXTryStmt(Empty, numHandlers);
+@@ -2027,4 +2027,3 @@
+       C.Allocate(Size + sizeof(OMPClause *) * NumClauses + sizeof(Stmt *));
+   return new (Mem) OMPTeamsDirective(NumClauses);
+ }
+-
+--- tools/clang/lib/Basic/IdentifierTable.cpp	2014-12-11 04:18:08.000000000 -0800
++++ tools/clang/lib/Basic/IdentifierTable.cpp	2015-07-17 16:43:46.538457921 -0700
+@@ -376,6 +376,11 @@
+     Profile(ID, keyword_begin(), getNumArgs());
+   }
+ };
++static_assert(
++    llvm::AlignOf<MultiKeywordSelector>::Alignment >=
++        llvm::AlignOf<IdentifierInfo *>::Alignment,
++    "Alignment is insufficient for objects appended to MultiKeywordSelector");
++
+ } // end namespace clang.
+ 
+ unsigned Selector::getNumArgs() const {
+--- tools/clang/lib/CodeGen/CGCleanup.h	2014-11-18 23:49:47.000000000 -0800
++++ tools/clang/lib/CodeGen/CGCleanup.h	2015-07-17 16:43:46.540112662 -0700
+@@ -211,9 +211,12 @@
+     return Scope->getKind() == Catch;
+   }
+ };
++static_assert(llvm::AlignOf<EHCatchScope>::Alignment >=
++                  llvm::AlignOf<EHCatchScope::Handler *>::Alignment,
++              "Alignment is insufficient for objects appended to EHCatchScope");
+ 
+ /// A cleanup scope which generates the cleanup blocks lazily.
+-class EHCleanupScope : public EHScope {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EHCleanupScope : public EHScope {
+   /// The nearest normal cleanup scope enclosing this one.
+   EHScopeStack::stable_iterator EnclosingNormal;
+ 
+@@ -391,6 +394,13 @@
+     return (Scope->getKind() == Cleanup);
+   }
+ };
++// Assert objects tacked on the end of EHCleanupScope won't be
++// misaligned.  NOTE: there's actually a bunch of different data
++// classes tacked on, so let's just ensure alignment good enough for
++// uint64_t bytes.
++static_assert(llvm::AlignOf<EHCleanupScope>::Alignment >=
++                  llvm::AlignOf<uint64_t>::Alignment,
++              "");
+ 
+ /// An exceptions scope which filters exceptions thrown through it.
+ /// Only exceptions matching the filter types will be permitted to be
+@@ -435,6 +445,10 @@
+     return scope->getKind() == Filter;
+   }
+ };
++static_assert(
++    llvm::AlignOf<EHFilterScope>::Alignment >=
++        llvm::AlignOf<llvm::Value *>::Alignment,
++    "Alignment is insufficient for objects appended to EHFilterScope");
+ 
+ /// An exceptions scope which calls std::terminate if any exception
+ /// reaches it.
+@@ -467,27 +481,27 @@
+   EHScope &operator*() const { return *get(); }
+ 
+   iterator &operator++() {
++    size_t Size;
+     switch (get()->getKind()) {
+     case EHScope::Catch:
+-      Ptr += EHCatchScope::getSizeForNumHandlers(
++      Size = EHCatchScope::getSizeForNumHandlers(
+           static_cast<const EHCatchScope*>(get())->getNumHandlers());
+       break;
+ 
+     case EHScope::Filter:
+-      Ptr += EHFilterScope::getSizeForNumFilters(
++      Size = EHFilterScope::getSizeForNumFilters(
+           static_cast<const EHFilterScope*>(get())->getNumFilters());
+       break;
+ 
+     case EHScope::Cleanup:
+-      Ptr += static_cast<const EHCleanupScope*>(get())
+-        ->getAllocatedSize();
++      Size = static_cast<const EHCleanupScope *>(get())->getAllocatedSize();
+       break;
+ 
+     case EHScope::Terminate:
+-      Ptr += EHTerminateScope::getSize();
++      Size = EHTerminateScope::getSize();
+       break;
+     }
+-
++    Ptr += llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
+     return *this;
+   }
+ 
+@@ -523,7 +537,7 @@
+ 
+   EHCatchScope &scope = cast<EHCatchScope>(*begin());
+   InnermostEHScope = scope.getEnclosingEHScope();
+-  StartOfData += EHCatchScope::getSizeForNumHandlers(scope.getNumHandlers());
++  unallocate(EHCatchScope::getSizeForNumHandlers(scope.getNumHandlers()));
+ }
+ 
+ inline void EHScopeStack::popTerminate() {
+@@ -531,7 +545,7 @@
+ 
+   EHTerminateScope &scope = cast<EHTerminateScope>(*begin());
+   InnermostEHScope = scope.getEnclosingEHScope();
+-  StartOfData += EHTerminateScope::getSize();
++  unallocate(EHTerminateScope::getSize());
+ }
+ 
+ inline EHScopeStack::iterator EHScopeStack::find(stable_iterator sp) const {
+--- tools/clang/lib/CodeGen/CGCleanup.cpp	2015-01-13 23:38:27.000000000 -0800
++++ tools/clang/lib/CodeGen/CGCleanup.cpp	2015-07-17 17:08:23.853121118 -0700
+@@ -94,6 +94,7 @@
+ 
+ /// Push an entry of the given size onto this protected-scope stack.
+ char *EHScopeStack::allocate(size_t Size) {
++  Size = llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
+   if (!StartOfBuffer) {
+     unsigned Capacity = 1024;
+     while (Capacity < Size) Capacity *= 2;
+@@ -123,6 +124,10 @@
+   return StartOfData;
+ }
+ 
++void EHScopeStack::unallocate(size_t Size) {
++  StartOfData += llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
++}
++
+ EHScopeStack::stable_iterator
+ EHScopeStack::getInnermostActiveNormalCleanup() const {
+   for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
+@@ -153,7 +158,6 @@
+ 
+ 
+ void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
+-  assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
+   char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
+   bool IsNormalCleanup = Kind & NormalCleanup;
+   bool IsEHCleanup = Kind & EHCleanup;
+@@ -181,7 +185,7 @@
+   EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
+   InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
+   InnermostEHScope = Cleanup.getEnclosingEHScope();
+-  StartOfData += Cleanup.getAllocatedSize();
++  unallocate(Cleanup.getAllocatedSize());
+ 
+   // Destroy the cleanup.
+   Cleanup.Destroy();
+@@ -211,7 +215,7 @@
+   assert(!empty() && "popping exception stack when not empty");
+ 
+   EHFilterScope &filter = cast<EHFilterScope>(*begin());
+-  StartOfData += EHFilterScope::getSizeForNumFilters(filter.getNumFilters());
++  unallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
+ 
+   InnermostEHScope = filter.getEnclosingEHScope();
+ }
+--- tools/clang/lib/CodeGen/CGExprCXX.cpp	2015-01-13 23:38:27.000000000 -0800
++++ tools/clang/lib/CodeGen/CGExprCXX.cpp	2015-07-17 16:43:46.544527492 -0700
+@@ -1129,6 +1129,10 @@
+       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
+     }
+   };
++  static_assert(
++      llvm::AlignOf<CallDeleteDuringNew>::Alignment >=
++          llvm::AlignOf<RValue>::Alignment,
++      "Alignment is insufficient for objects appended to CallDeleteDuringNew");
+ 
+   /// A cleanup to call the given 'operator delete' function upon
+   /// abnormal exit from a new expression when the new expression is
+@@ -1188,6 +1192,10 @@
+       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
+     }
+   };
++  static_assert(
++      llvm::AlignOf<CallDeleteDuringConditionalNew>::Alignment >=
++          llvm::AlignOf<DominatingValue<RValue>::saved_type>::Alignment,
++      "Alignment is insufficient for objects appended to CallDeleteDuringNew");
+ }
+ 
+ /// Enter a cleanup to call 'operator delete' if the initializer in a
+@@ -1819,7 +1827,7 @@
+       MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
+ 
+   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
+-  for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
++  for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
+                                          e = E->capture_init_end();
+        i != e; ++i, ++CurField) {
+     // Emit initialization
+--- tools/clang/lib/CodeGen/CGStmt.cpp	2015-01-13 23:38:27.000000000 -0800
++++ tools/clang/lib/CodeGen/CGStmt.cpp	2015-07-17 16:43:46.546244580 -0700
+@@ -2122,7 +2122,7 @@
+       CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
+ 
+   RecordDecl::field_iterator CurField = RD->field_begin();
+-  for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(),
++  for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
+                                            E = S.capture_init_end();
+        I != E; ++I, ++CurField) {
+     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
+--- tools/clang/lib/CodeGen/EHScopeStack.h	2014-10-31 19:33:56.000000000 -0400
++++ tools/clang/lib/CodeGen/EHScopeStack.h	2015-07-18 01:53:43.588447919 -0400
+@@ -89,6 +89,8 @@
+ /// and catch blocks.
+ class EHScopeStack {
+ public:
++  enum { ScopeStackAlignment = llvm::AlignOf<uint64_t>::Alignment };
++
+   /// A saved depth on the scope stack.  This is necessary because
+   /// pushing scopes onto the stack invalidates iterators.
+   class stable_iterator {
+@@ -297,6 +299,7 @@
+   SmallVector<BranchFixup, 8> BranchFixups;
+ 
+   char *allocate(size_t Size);
++  void unallocate(size_t Size);
+ 
+   void *pushCleanup(CleanupKind K, size_t DataSize);
+ 
+@@ -311,6 +314,8 @@
+   /// Push a lazily-created cleanup on the stack.
+   template <class T>
+   void pushCleanup(CleanupKind Kind) {
++    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
++        "Insufficient Alignment!");
+     void *Buffer = pushCleanup(Kind, sizeof(T));
+     Cleanup *Obj = new(Buffer) T();
+     (void) Obj;
+@@ -319,6 +324,8 @@
+   /// Push a lazily-created cleanup on the stack.
+   template <class T, class A0>
+   void pushCleanup(CleanupKind Kind, A0 a0) {
++    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
++        "Insufficient Alignment!");
+     void *Buffer = pushCleanup(Kind, sizeof(T));
+     Cleanup *Obj = new(Buffer) T(a0);
+     (void) Obj;
+@@ -327,6 +334,8 @@
+   /// Push a lazily-created cleanup on the stack.
+   template <class T, class A0, class A1>
+   void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
++    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
++        "Insufficient Alignment!");
+     void *Buffer = pushCleanup(Kind, sizeof(T));
+     Cleanup *Obj = new(Buffer) T(a0, a1);
+     (void) Obj;
+@@ -335,6 +344,8 @@
+   /// Push a lazily-created cleanup on the stack.
+   template <class T, class A0, class A1, class A2>
+   void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
++    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
++        "Insufficient Alignment!");
+     void *Buffer = pushCleanup(Kind, sizeof(T));
+     Cleanup *Obj = new(Buffer) T(a0, a1, a2);
+     (void) Obj;
+@@ -343,6 +354,8 @@
+   /// Push a lazily-created cleanup on the stack.
+   template <class T, class A0, class A1, class A2, class A3>
+   void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
++    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
++        "Insufficient Alignment!");
+     void *Buffer = pushCleanup(Kind, sizeof(T));
+     Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
+     (void) Obj;
+@@ -351,11 +364,24 @@
+   /// Push a lazily-created cleanup on the stack.
+   template <class T, class A0, class A1, class A2, class A3, class A4>
+   void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
++    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
++        "Insufficient Alignment!");
+     void *Buffer = pushCleanup(Kind, sizeof(T));
+     Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
+     (void) Obj;
+   }
+ 
++  /// Push a lazily-created cleanup on the stack. Tuple version.
++  template <class T, class... As>
++  void pushCleanupTuple(CleanupKind Kind, std::tuple<As...> A) {
++    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
++        "Insufficient Alignment!");
++    void *Buffer = pushCleanup(Kind, sizeof(T));
++    Cleanup *Obj = new (Buffer) T(std::move(A));
++    (void) Obj;
++  }
++
++
+   // Feel free to add more variants of the following:
+ 
+   /// Push a cleanup with non-constant storage requirements on the
+@@ -371,6 +397,8 @@
+   /// stack is modified.
+   template <class T, class A0, class A1, class A2>
+   T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
++    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
++        "Insufficient Alignment!");
+     void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
+     return new (Buffer) T(N, a0, a1, a2);
+   }
+--- tools/clang/lib/Lex/PPDirectives.cpp	2014-12-27 23:42:49.000000000 -0800
++++ tools/clang/lib/Lex/PPDirectives.cpp	2015-07-17 16:43:46.550148988 -0700
+@@ -48,8 +48,6 @@
+ 
+ MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
+                                                        unsigned SubModuleID) {
+-  static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
+-                "alignment for MacroInfo is less than the ID");
+   DeserializedMacroInfoChain *MIChain =
+       BP.Allocate<DeserializedMacroInfoChain>();
+   MIChain->Next = DeserialMIChainHead;
+--- tools/clang/lib/Sema/SemaExceptionSpec.cpp	2014-11-21 19:09:05.000000000 -0800
++++ tools/clang/lib/Sema/SemaExceptionSpec.cpp	2015-07-17 16:43:46.552022232 -0700
+@@ -971,7 +971,8 @@
+   case Expr::LambdaExprClass: {
+     const LambdaExpr *Lambda = cast<LambdaExpr>(E);
+     CanThrowResult CT = CT_Cannot;
+-    for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
++    for (LambdaExpr::const_capture_init_iterator
++             Cap = Lambda->capture_init_begin(),
+                                         CapEnd = Lambda->capture_init_end();
+          Cap != CapEnd; ++Cap)
+       CT = mergeCanThrow(CT, canThrow(*Cap));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/007-TemplateBase.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,224 @@
+# 1. RAII - Resource Acquisition Is Initialization.
+# 2. Default bit-copying or assigning union member bitfields
+#    between unions of different types or size is undefined behavior.
+# 3. Default bit-copying or assigning unions of different types or
+#    size is undefined behavior.
+# 4. Default bit-copying or assigning nested unions is undefined behavior.
+# https://llvm.org/bugs/show_bug.cgi?id=24608
+--- tools/clang/include/clang/AST/TemplateBase.h	2015-07-17 16:43:46.506876445 -0700
++++ tools/clang/include/clang/AST/TemplateBase.h	2015-07-17 17:39:04.239131360 -0700
+@@ -22,6 +22,7 @@
+ #include "llvm/ADT/iterator_range.h"
+ #include "llvm/Support/Compiler.h"
+ #include "llvm/Support/ErrorHandling.h"
++#include <cstring>
+ 
+ namespace llvm {
+   class FoldingSetNodeID;
+@@ -84,8 +85,8 @@
+     // We store a decomposed APSInt with the data allocated by ASTContext if
+     // BitWidth > 64. The memory may be shared between multiple
+     // TemplateArgument instances.
+-    unsigned BitWidth : 31;
+-    unsigned IsUnsigned : 1;
++    unsigned BitWidth;
++    bool IsUnsigned;
+     union {
+       uint64_t VAL;          ///< Used to store the <= 64 bits integer value.
+       const uint64_t *pVal;  ///< Used to store the >64 bits integer value.
+@@ -112,6 +113,7 @@
+     struct A Args;
+     struct TA TemplateArg;
+     struct TV TypeOrValue;
++    uint64_t Buffer[8];
+   };
+ 
+   TemplateArgument(TemplateName, bool) LLVM_DELETED_FUNCTION;
+@@ -119,12 +121,27 @@
+ public:
+   /// \brief Construct an empty, invalid template argument.
+   TemplateArgument() {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TypeOrValue.Kind = Null;
+     TypeOrValue.V = 0;
+   }
+ 
++  TemplateArgument(const TemplateArgument &RHS) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
++    (void) std::memcpy(Buffer, RHS.Buffer, sizeof(Buffer));
++  }
++
++  TemplateArgument &operator=(const TemplateArgument &RHS) {
++    if (this != &RHS) {
++      (void) std::memset(Buffer, 0, sizeof(Buffer));
++      (void) std::memcpy(Buffer, RHS.Buffer, sizeof(Buffer));
++    }
++    return *this;
++  }
++
+   /// \brief Construct a template type argument.
+   TemplateArgument(QualType T, bool isNullPtr = false) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TypeOrValue.Kind = isNullPtr ? NullPtr : Type;
+     TypeOrValue.V = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
+   }
+@@ -134,6 +151,7 @@
+   /// template declaration.
+   TemplateArgument(ValueDecl *D, QualType QT) {
+     assert(D && "Expected decl");
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     DeclArg.Kind = Declaration;
+     DeclArg.QT = QT.getAsOpaquePtr();
+     DeclArg.D = D;
+@@ -146,6 +164,7 @@
+   /// \brief Construct an integral constant template argument with the same
+   /// value as Other but a different type.
+   TemplateArgument(const TemplateArgument &Other, QualType Type) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     Integer = Other.Integer;
+     Integer.Type = Type.getAsOpaquePtr();
+   }
+@@ -159,6 +178,7 @@
+   ///
+   /// \param Name The template name.
+   TemplateArgument(TemplateName Name) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TemplateArg.Kind = Template;
+     TemplateArg.Name = Name.getAsVoidPointer();
+     TemplateArg.NumExpansions = 0;
+@@ -176,6 +196,7 @@
+   /// \param NumExpansions The number of expansions that will be generated by
+   /// instantiating
+   TemplateArgument(TemplateName Name, Optional<unsigned> NumExpansions) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TemplateArg.Kind = TemplateExpansion;
+     TemplateArg.Name = Name.getAsVoidPointer();
+     if (NumExpansions)
+@@ -190,6 +211,7 @@
+   /// lists used for dependent types and for expression; it will not
+   /// occur in a non-dependent, canonical template argument list.
+   TemplateArgument(Expr *E) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TypeOrValue.Kind = Expression;
+     TypeOrValue.V = reinterpret_cast<uintptr_t>(E);
+   }
+@@ -199,6 +221,7 @@
+   /// We assume that storage for the template arguments provided
+   /// outlives the TemplateArgument itself.
+   TemplateArgument(const TemplateArgument *Args, unsigned NumArgs) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     this->Args.Kind = Pack;
+     this->Args.Args = Args;
+     this->Args.NumArgs = NumArgs;
+@@ -391,25 +414,55 @@
+     struct T Template;
+     Expr *Expression;
+     TypeSourceInfo *Declarator;
++    unsigned long Buffer[4];
+   };
+ 
+ public:
+   TemplateArgumentLocInfo();
+   
+-  TemplateArgumentLocInfo(TypeSourceInfo *TInfo) : Declarator(TInfo) {}
++  TemplateArgumentLocInfo(TypeSourceInfo *TInfo) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
++    Declarator = TInfo;
++  }
+   
+-  TemplateArgumentLocInfo(Expr *E) : Expression(E) {}
++  TemplateArgumentLocInfo(Expr *E) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
++    Expression = E;
++  }
+   
+   TemplateArgumentLocInfo(NestedNameSpecifierLoc QualifierLoc,
+                           SourceLocation TemplateNameLoc,
+-                          SourceLocation EllipsisLoc)
+-  {
++                          SourceLocation EllipsisLoc) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     Template.Qualifier = QualifierLoc.getNestedNameSpecifier();
+     Template.QualifierLocData = QualifierLoc.getOpaqueData();
+     Template.TemplateNameLoc = TemplateNameLoc.getRawEncoding();
+     Template.EllipsisLoc = EllipsisLoc.getRawEncoding();
+   }
+ 
++  TemplateArgumentLocInfo(const TemplateArgumentLocInfo &RHS) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
++    Template.Qualifier = RHS.Template.Qualifier;
++    Template.QualifierLocData = RHS.Template.QualifierLocData;
++    Template.TemplateNameLoc = RHS.Template.TemplateNameLoc;
++    Template.EllipsisLoc = RHS.Template.EllipsisLoc;
++    Expression = RHS.Expression;
++    Declarator = RHS.Declarator;
++  }
++
++  TemplateArgumentLocInfo &operator=(const TemplateArgumentLocInfo &RHS) {
++    if (this != &RHS) {
++      (void) std::memset(Buffer, 0, sizeof(Buffer));
++      Template.Qualifier = RHS.Template.Qualifier;
++      Template.QualifierLocData = RHS.Template.QualifierLocData;
++      Template.TemplateNameLoc = RHS.Template.TemplateNameLoc;
++      Template.EllipsisLoc = RHS.Template.EllipsisLoc;
++      Expression = RHS.Expression;
++      Declarator = RHS.Declarator;
++    }
++    return *this;
++  }
++
+   TypeSourceInfo *getAsTypeSourceInfo() const {
+     return Declarator;
+   }
+# 1. RAII - Resource Acquisition Is Initialization.
+# 2. Allocate memory with suitable alignment for uint64_t.
+# 3. reinterpret_cast<> from void* to <type*>.
+--- tools/clang/lib/AST/TemplateBase.cpp	2015-01-08 16:58:16.000000000 -0800
++++ tools/clang/lib/AST/TemplateBase.cpp	2015-07-17 17:42:51.744142395 -0700
+@@ -71,6 +71,7 @@
+ 
+ TemplateArgument::TemplateArgument(ASTContext &Ctx, const llvm::APSInt &Value,
+                                    QualType Type) {
++  (void) std::memset(Buffer, '\0', sizeof(Buffer));
+   Integer.Kind = Integral;
+   // Copy the APSInt value into our decomposed form.
+   Integer.BitWidth = Value.getBitWidth();
+@@ -78,9 +79,9 @@
+   // If the value is large, we have to get additional memory from the ASTContext
+   unsigned NumWords = Value.getNumWords();
+   if (NumWords > 1) {
+-    void *Mem = Ctx.Allocate(NumWords * sizeof(uint64_t));
+-    std::memcpy(Mem, Value.getRawData(), NumWords * sizeof(uint64_t));
+-    Integer.pVal = static_cast<uint64_t *>(Mem);
++    void *Mem = Ctx.Allocate(NumWords * sizeof(uint64_t), alignof(uint64_t));
++    (void) std::memcpy(Mem, Value.getRawData(), NumWords * sizeof(uint64_t));
++    Integer.pVal = reinterpret_cast<uint64_t *>(Mem);
+   } else {
+     Integer.VAL = Value.getZExtValue();
+   }
+@@ -422,7 +423,9 @@
+ //===----------------------------------------------------------------------===//
+ 
+ TemplateArgumentLocInfo::TemplateArgumentLocInfo() {
+-  memset((void*)this, 0, sizeof(TemplateArgumentLocInfo));
++  (void) std::memset(Buffer, 0, sizeof(Buffer));
++  Expression = nullptr;
++  Declarator = nullptr;
+ }
+ 
+ SourceRange TemplateArgumentLoc::getSourceRange() const {
+# 1. Pointer Arithmetic Paranoia.
+--- tools/clang/lib/AST/Type.cpp	2014-12-28 01:18:54.000000000 -0800
++++ tools/clang/lib/AST/Type.cpp	2015-07-17 17:43:57.848813992 -0700
+@@ -1464,7 +1464,10 @@
+     if (Args[I].containsUnexpandedParameterPack())
+       setContainsUnexpandedParameterPack();
+ 
+-    new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
++    TemplateArgument *TA = getArgBuffer();
++    TA = &(TA[I]);
++    TA = new (TA) TemplateArgument();
++    *TA = Args[I];
+   }
+ }
+ 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/008-DeclTemplate.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,26 @@
+# 1. Write copy-constructor and assignment operator.
+# https://llvm.org/bugs/show_bug.cgi?id=24608
+--- tools/clang/include/clang/AST/DeclTemplate.h	2015-07-17 16:43:46.485713092 -0700
++++ tools/clang/include/clang/AST/DeclTemplate.h	2015-07-17 17:55:26.681560803 -0700
+@@ -485,6 +485,21 @@
+                                  const UnresolvedSetImpl &Templates,
+                                  const TemplateArgumentListInfo &TemplateArgs);
+ 
++  DependentFunctionTemplateSpecializationInfo(
++            const DependentFunctionTemplateSpecializationInfo &RHS) 
++  : NumTemplates(RHS.NumTemplates), NumArgs(RHS.NumArgs),
++  AngleLocs(RHS.AngleLocs) { }
++
++  DependentFunctionTemplateSpecializationInfo
++  &operator=(const DependentFunctionTemplateSpecializationInfo &RHS) {
++    if (this != &RHS) {
++      NumTemplates = RHS.NumTemplates;
++      NumArgs = RHS.NumArgs;
++      AngleLocs = RHS.AngleLocs;
++    }
++    return *this;
++  }
++
+   /// \brief Returns the number of function templates that this might
+   /// be a specialization of.
+   unsigned getNumTemplates() const { return NumTemplates; }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/009-InitPreprocessor.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,69 @@
+# The anonymous std::string temporary created by getClangFullRepositoryVersion
+# goes out-of-scope in C++11 because COW std::string is not allowed.
+# I.e. the std::string buffer of the anonymous temporary goes out of scope.
+# Because of this, the buffer referenced by the underlying StringRef in
+# llvm::Twine is invalid as soon as the std::string temporary expires.
+# The tagged clang version string must be created as a data segment global
+# constant via macro, just like all the other clang version macro identifiers.
+# https://llvm.org/bugs/show_bug.cgi?id=24684
+--- tools/clang/include/clang/Basic/Version.inc.in	2010-06-25 13:33:46.000000000 -0400
++++ tools/clang/include/clang/Basic/Version.inc.in	2015-07-05 14:20:27.771128865 -0400
+@@ -4,3 +4,4 @@
+ #if @CLANG_HAS_VERSION_PATCHLEVEL@
+ #define CLANG_VERSION_PATCHLEVEL @CLANG_VERSION_PATCHLEVEL@
+ #endif
++#define CLANG_VERSION_TAGGED_STRING @CLANG_VERSION_TAGGED_STRING@
+--- tools/clang/include/clang/Basic/Makefile	2014-03-31 09:14:44.000000000 -0400
++++ tools/clang/include/clang/Basic/Makefile	2015-07-05 14:19:58.972485543 -0400
+@@ -16,8 +16,18 @@
+ 
+ INPUT_TDS = $(wildcard $(PROJ_SRC_DIR)/Diagnostic*.td)
+ 
++SVN_OR_RC :=
++
+ # Compute the Clang version from the LLVM version, unless specified explicitly.
+ ifndef CLANG_VERSION
++ifeq ($(LLVMVersion), $(findstring svn, $(LLVMVersion)), svn)
++  SVN_OR_RC := "svn"
++endif
++
++ifeq ($(LLVMVersion), $(findstring rc, $(LLVMVersion)), rc)
++  SVN_OR_RC := "rc"
++endif
++
+ CLANG_VERSION := $(subst svn,,$(LLVMVersion))
+ CLANG_VERSION := $(subst rc,,$(CLANG_VERSION))
+ endif
+@@ -26,6 +36,14 @@
+ CLANG_VERSION_MAJOR := $(word 1,$(CLANG_VERSION_COMPONENTS))
+ CLANG_VERSION_MINOR := $(word 2,$(CLANG_VERSION_COMPONENTS))
+ CLANG_VERSION_PATCHLEVEL := $(word 3,$(CLANG_VERSION_COMPONENTS))
++CLANG_VERSION_TAGGED_STRING :=
++
++ifeq ($(SVN_OR_RC),)
++CLANG_VERSION_TAGGED_STRING := "\"\(tags/RELEASE_$(CLANG_VERSION_MAJOR)$(CLANG_VERSION_MINOR)$(CLANG_VERSION_PATCHLEVEL)/final\)\""
++else
++CLANG_VERSION_TAGGED_STRING := "\"\(tags/RELEASE_$(CLANG_VERSION_MAJOR)$(CLANG_VERSION_MINOR)$(CLANG_VERSION_PATCHLEVEL)/$(SVN_OR_RC)\)\""
++endif
++
+ ifeq ($(CLANG_VERSION_PATCHLEVEL),)
+ CLANG_HAS_VERSION_PATCHLEVEL := 0
+ else
+@@ -67,4 +85,5 @@
+ 	           -e "s#@CLANG_VERSION_MINOR@#$(CLANG_VERSION_MINOR)#g" \
+ 	           -e "s#@CLANG_VERSION_PATCHLEVEL@#$(CLANG_VERSION_PATCHLEVEL)#g" \
+ 	           -e "s#@CLANG_HAS_VERSION_PATCHLEVEL@#$(CLANG_HAS_VERSION_PATCHLEVEL)#g" \
++	           -e "s#@CLANG_VERSION_TAGGED_STRING@#$(CLANG_VERSION_TAGGED_STRING:' '='')#g" \
+ 	           $< > $@
+--- tools/clang/lib/Frontend/InitPreprocessor.cpp	2015-04-27 04:12:42.000000000 -0400
++++ tools/clang/lib/Frontend/InitPreprocessor.cpp	2015-07-05 14:24:20.804334574 -0400
+@@ -470,8 +470,7 @@
+   Builder.defineMacro("__clang_patchlevel__", "0");
+ #endif
+   Builder.defineMacro("__clang_version__", 
+-                      "\"" CLANG_VERSION_STRING " "
+-                      + getClangFullRepositoryVersion() + "\"");
++                      "\"" CLANG_VERSION_STRING " " CLANG_VERSION_TAGGED_STRING "\"");
+ #undef TOSTR
+ #undef TOSTR2
+   if (!LangOpts.MSVCCompat) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/010-linker-mapfiles.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,130 @@
+# 1. Enable the linker map files provided by clang/llvm for symbol
+# scope and visibility in shared libraries.
+# 2. We must use our own linker map file for compatibility with
+# the GNU linkers and GNU Binutils (libbfd).
+# Solaris autoconf-based build.
+# https://llvm.org/bugs/show_bug.cgi?id=24641
+--- Makefile.rules	2015-07-17 19:12:32.515872699 -0700
++++ Makefile.rules	2015-07-17 19:17:40.294355307 -0700
+@@ -643,6 +643,7 @@
+     endif
+     ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
+       LD.Flags += -Wl,-z -Wl,discard-unused=sections
++      LD.Flags += -Wl,-M -Wl,$(PROJ_SRC_ROOT)/mapfiles/map.gnu-sections
+     endif
+   endif
+ endif
+@@ -655,6 +656,10 @@
+   ifneq ($(HOST_OS), Darwin)
+     ifdef TOOLNAME
+       LD.Flags += $(RPATH) -Wl,'$$ORIGIN/../lib'
++      ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++        LD.Flags += -Wl,-z -Wl,discard-unused=sections
++        LD.Flags += -Wl,-M -Wl,$(PROJ_SRC_ROOT)/mapfiles/map.gnu-sections
++      endif
+     endif
+   else
+     ifneq ($(DARWIN_MAJVERS),4)
+@@ -1122,11 +1127,26 @@
+ clean-local::
+ 	-$(Verb) $(RM) -f $(NativeExportsFile)
+ else
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++# Solaris ld requires a version script rather than a plain list.
++NativeExportsFile := $(ObjDir)/$(notdir $(EXPORTED_SYMBOL_FILE)).map
++$(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir
++	$(Verb) echo "{" > $@
++	$(Verb) grep -q '[[:alnum:]_]' $< && echo "  global:" >> $@ || :
++	$(Verb) sed -e 's/$$/;/' -e 's/^/    /' < $< >> $@
++ifneq ($(HOST_OS),OpenBSD)
++	$(Verb) echo "  local: *;" >> $@
++endif
++	$(Verb) echo "};" >> $@
++clean-local::
++	-$(Verb) $(RM) -f $(NativeExportsFile)
++else
+ # Default behavior: just use the exports file verbatim.
+ NativeExportsFile := $(EXPORTED_SYMBOL_FILE)
+ endif
+ endif
+ endif
++endif
+ 
+ # Now add the linker command-line options to use the native export file.
+ 
+@@ -1146,6 +1166,11 @@
+ SharedLinkOptions += $(NativeExportsFile)
+ endif
+ 
++# Solaris
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++LLVMLibsOptions += -Wl,-M -Wl,$(NativeExportsFile)
++endif
++
+ endif
+ 
+ ###############################################################################
+--- /dev/null	2015-07-08 19:15:05.000000000 -0700
++++ mapfiles/map.gnu-sections	2015-07-08 19:13:41.905920797 -0700
+@@ -0,0 +1,61 @@
++$mapfile_version 2
++
++# Emulate the rules used by the GNU ld and gold linkers for merging input
++# sections into output sections in executables and shared objects. From
++# Ian Lance Taylor and Cary Coutant.
++
++# gcc 4.3 generates the following sorts of section names when it
++# needs a section name specific to a function:
++#   .text.FN
++#   .rodata.FN
++#   .sdata2.FN
++#   .data.FN
++#   .data.rel.FN
++#   .data.rel.local.FN
++#   .data.rel.ro.FN
++#   .data.rel.ro.local.FN
++#   .sdata.FN
++#   .bss.FN
++#   .sbss.FN
++#   .tdata.FN
++#   .tbss.FN
++#
++# The GNU linker maps all of those to the part before the .FN,
++# except that .data.rel.local.FN is mapped to .data, and
++# .data.rel.ro.local.FN is mapped to .data.rel.ro.  The sections
++# beginning with .data.rel.ro.local are grouped together.
++#
++# For an anonymous namespace, the string FN can contain a '.'.
++#
++# Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
++# GNU linker maps to .rodata.
++
++$if _ET_DYN || _ET_EXEC
++
++LOAD_SEGMENT text {
++	ASSIGN_SECTION {
++		IS_NAME = MATCH(g/.data.rel.local.*/);
++		FLAGS = ALLOC !WRITE;
++		OUTPUT_SECTION { NAME = .data };
++	};
++	ASSIGN_SECTION {
++		IS_NAME = MATCH(r/^\.(text|rodata|sdata2|data\.rel\.ro|data\.rel|data|sdata|bss|sbss|tdata|tbss)\./);
++		FLAGS = ALLOC !WRITE;
++		OUTPUT_SECTION { NAME = MATCHREF(/.${n1}/) };
++	};
++};
++
++LOAD_SEGMENT data {
++	ASSIGN_SECTION {
++		IS_NAME = MATCH(g/.data.rel.local.*/);
++		FLAGS = ALLOC WRITE;
++		OUTPUT_SECTION { NAME = .data };
++	};
++	ASSIGN_SECTION {
++		IS_NAME = MATCH(r/^\.(text|rodata|sdata2|data\.rel\.ro|data\.rel|data|sdata|bss|sbss|tdata|tbss)\./);
++		FLAGS = ALLOC WRITE;
++		OUTPUT_SECTION { NAME = MATCHREF(/.${n1}/) };
++	};
++};
++
++$endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/011-gxx-abi-version.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,85 @@
+# Add an implementation for -fabi-version=<N> in clang.
+# This is useful and required for testing the GNU C++
+# Standard Library for GCC >= 5.0.
+# https://llvm.org/bugs/show_bug.cgi?id=24685
+--- tools/clang/include/clang/Basic/LangOptions.def	2014-12-03 16:53:36.000000000 -0500
++++ tools/clang/include/clang/Basic/LangOptions.def	2015-07-11 11:35:34.710878157 -0400
+@@ -134,6 +134,8 @@
+               "default struct packing maximum alignment")
+ VALUE_LANGOPT(MaxTypeAlign  , 32, 0,
+               "default maximum alignment for types")
++VALUE_LANGOPT(GXXABIVersion , 32, 0,
++              "Use specified GNU C++ Standard Library ABI version")
+ VALUE_LANGOPT(PICLevel    , 2, 0, "__PIC__ level")
+ VALUE_LANGOPT(PIELevel    , 2, 0, "__PIE__ level")
+ LANGOPT(GNUInline         , 1, 0, "GNU inline semantics")
+--- tools/clang/lib/Frontend/InitPreprocessor.cpp	2015-09-01 06:51:55.849518525 -0700
++++ tools/clang/lib/Frontend/InitPreprocessor.cpp	2015-09-02 13:53:24.781943196 -0700
+@@ -479,7 +479,31 @@
+     Builder.defineMacro("__GNUC_MINOR__", "2");
+     Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
+     Builder.defineMacro("__GNUC__", "4");
++    // GCC provides a number of C++ ABI Versions in:
++    // ${top_srcdir}/gcc/c-family/c-cppbuiltin.c
++    // Currently valid GXX ABI Versions are documented here:
++    // https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Dialect-Options.html
++    // clang only supports a subset.
++    switch (LangOpts.GXXABIVersion) {
++    default:
+     Builder.defineMacro("__GXX_ABI_VERSION", "1002");
++      break;
++    case 4:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1004");
++      break;
++    case 5:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1005");
++      break;
++    case 6:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1006");
++      break;
++    case 7:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1007");
++      break;
++    case 8:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1008");
++      break;
++    }
+   }
+ 
+   // Define macros for the C11 / C++11 memory orderings
+--- tools/clang/lib/Frontend/CompilerInvocation.cpp	2015-05-04 14:23:43.000000000 -0400
++++ tools/clang/lib/Frontend/CompilerInvocation.cpp	2015-07-11 15:40:20.580031428 -0400
+@@ -1539,6 +1539,7 @@
+   Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
+   Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
+   Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
++  Opts.GXXABIVersion = getLastArgIntValue(Args, OPT_fabi_version_EQ, 0, Diags);
+   Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
+   Opts.PIELevel = getLastArgIntValue(Args, OPT_pie_level, 0, Diags);
+   Opts.Static = Args.hasArg(OPT_static_define);
+--- tools/clang/include/clang/Driver/Options.td	2015-01-26 18:17:18.000000000 -0500
++++ tools/clang/include/clang/Driver/Options.td	2015-07-11 15:44:39.660620608 -0400
+@@ -574,6 +574,8 @@
+ def ffp_contract : Joined<["-"], "ffp-contract=">, Group<f_Group>,
+   Flags<[CC1Option]>, HelpText<"Form fused FP ops (e.g. FMAs): fast (everywhere)"
+   " | on (according to FP_CONTRACT pragma, default) | off (never fuse)">;
++def fabi_version_EQ : Joined<["-"], "fabi-version=">, Group<f_Group>,
++  Flags<[CC1Option]>, HelpText<"Use specified GNU C++ ABI version">;
+ 
+ def ffor_scope : Flag<["-"], "ffor-scope">, Group<f_Group>;
+ def fno_for_scope : Flag<["-"], "fno-for-scope">, Group<f_Group>;
+--- tools/clang/lib/Driver/Tools.cpp	2015-02-03 17:57:34.000000000 -0500
++++ tools/clang/lib/Driver/Tools.cpp	2015-07-11 23:36:17.198486944 -0400
+@@ -2812,6 +2812,12 @@
+     CmdArgs.push_back(A->getValue());
+   }
+ 
++  if (Arg *A = Args.getLastArg(options::OPT_fabi_version_EQ)) {
++    StringRef v = A->getValue();
++    CmdArgs.push_back(Args.MakeArgString("-fabi-version=" + v));
++    A->claim();
++  }
++
+   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
+                                options::OPT_freg_struct_return)) {
+     if (getToolChain().getArch() != llvm::Triple::x86) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/012-TypeLocBuilder.cpp.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,73 @@
+# https://llvm.org/bugs/show_bug.cgi?id=24615
+--- tools/clang/lib/Sema/TypeLocBuilder.h	2014-08-13 09:25:19.000000000 -0700
++++ tools/clang/lib/Sema/TypeLocBuilder.h	2015-08-28 16:45:41.733661825 -0700
+@@ -39,7 +39,7 @@
+ #endif
+     
+   /// The inline buffer.
+-  enum { BufferMaxAlignment = llvm::AlignOf<void*>::Alignment };
++  enum { BufferMaxAlignment = llvm::AlignOf<uint64_t>::Alignment };
+   llvm::AlignedCharArray<BufferMaxAlignment, InlineCapacity> InlineBuffer;
+   unsigned NumBytesAtAlign4, NumBytesAtAlign8;
+ 
+@@ -52,7 +52,7 @@
+ 
+   ~TypeLocBuilder() {
+     if (Buffer != InlineBuffer.buffer)
+-      delete[] Buffer;
++      std::free(Buffer);
+   }
+ 
+   /// Ensures that this buffer has at least as much capacity as described.
+--- tools/clang/lib/Sema/TypeLocBuilder.cpp	2014-05-25 23:22:03.000000000 -0700
++++ tools/clang/lib/Sema/TypeLocBuilder.cpp	2015-08-25 18:53:43.000000000 -0700
+@@ -13,6 +13,8 @@
+ //===----------------------------------------------------------------------===//
+ 
+ #include "TypeLocBuilder.h"
++#include <cstring>
++#include <stdlib.h>
+ 
+ using namespace clang;
+ 
+@@ -46,14 +48,36 @@
+   assert(NewCapacity > Capacity);
+ 
+   // Allocate the new buffer and copy the old data into it.
+-  char *NewBuffer = new char[NewCapacity];
++  char *NewBuffer;
++
++#if defined(_MSC_VER)
++  NewBuffer = _aligned_malloc(NewCapacity, (size_t) BufferMaxAlignment);
++  assert(NewBuffer && "_aligned_malloc failed!");
++  if (!NewBuffer) {
++    llvm::errs() << __PRETTY_FUNCTION__ << ": _aligned_malloc failed!\n";
++    abort();
++  }
++#else
++  int R = posix_memalign((void**) &NewBuffer,
++                         (size_t) BufferMaxAlignment, NewCapacity);
++  assert((R == 0) && "posix_memalign failed!");
++  assert(NewBuffer && "posix_memalign failed!");
++  if ((R != 0) || (!NewBuffer)) {
++    llvm::errs() << __PRETTY_FUNCTION__ << ": posix_memalign failed!\n";
++    abort();
++  }
++#endif
++
++  (void) std::memset(NewBuffer, 0, NewCapacity);
++
+   unsigned NewIndex = Index + NewCapacity - Capacity;
+-  memcpy(&NewBuffer[NewIndex],
++  (void) std::memcpy(&NewBuffer[NewIndex],
+          &Buffer[Index],
+          Capacity - Index);
+ 
+-  if (Buffer != InlineBuffer.buffer)
+-    delete[] Buffer;
++  if (Buffer != InlineBuffer.buffer) {
++    std::free(Buffer);
++  }
+ 
+   Buffer = NewBuffer;
+   Capacity = NewCapacity;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/013-llvm-alignments.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,127 @@
+# http://reviews.llvm.org/D10271
+# Backported to 3.6.2.
+--- include/llvm/IR/DerivedTypes.h	2014-11-21 14:03:35.000000000 -0500
++++ include/llvm/IR/DerivedTypes.h	2015-08-23 17:27:29.355504909 -0400
+@@ -140,7 +140,8 @@
+     return T->getTypeID() == FunctionTyID;
+   }
+ };
+-
++static_assert(AlignOf<FunctionType>::Alignment >= AlignOf<Type *>::Alignment,
++              "Insufficient alignment for objects appended to FunctionType");
+ 
+ /// CompositeType - Common super class of ArrayType, StructType, PointerType
+ /// and VectorType.
+--- include/llvm/IR/User.h	2014-10-15 16:39:05.000000000 -0400
++++ include/llvm/IR/User.h	2015-08-23 17:27:29.365505148 -0400
+@@ -22,6 +22,7 @@
+ #include "llvm/ADT/iterator.h"
+ #include "llvm/ADT/iterator_range.h"
+ #include "llvm/IR/Value.h"
++#include "llvm/Support/AlignOf.h"
+ #include "llvm/Support/ErrorHandling.h"
+ 
+ namespace llvm {
+@@ -172,6 +173,11 @@
+     return isa<Instruction>(V) || isa<Constant>(V);
+   }
+ };
++// Either Use objects, or a Use pointer can be prepended to User.
++static_assert(AlignOf<Use>::Alignment >= AlignOf<User>::Alignment,
++              "Insufficient alignment after objects prepended to User");
++static_assert(AlignOf<Use *>::Alignment >= AlignOf<User>::Alignment,
++              "Insufficient alignment after objects prepended to User");
+ 
+ template<> struct simplify_type<User::op_iterator> {
+   typedef Value* SimpleType;
+--- include/llvm/Support/AlignOf.h	2014-01-08 22:28:55.000000000 -0500
++++ include/llvm/Support/AlignOf.h	2015-08-23 17:27:29.365505148 -0400
+@@ -36,9 +36,18 @@
+ ///  compile-time constant (e.g., for template instantiation).
+ template <typename T>
+ struct AlignOf {
++#ifndef _MSC_VER
++  // Avoid warnings from GCC like:
++  //   comparison between 'enum llvm::AlignOf<X>::<anonymous>' and 'enum
++  //   llvm::AlignOf<Y>::<anonymous>' [-Wenum-compare]
++  // by using constexpr instead of enum.
++  // (except on MSVC, since it doesn't support constexpr yet).
++  static constexpr unsigned Alignment =
++      static_cast<unsigned int>(sizeof(AlignmentCalcImpl<T>) - sizeof(T));
++#else
+   enum { Alignment =
+          static_cast<unsigned int>(sizeof(AlignmentCalcImpl<T>) - sizeof(T)) };
+-
++#endif
+   enum { Alignment_GreaterEqual_2Bytes = Alignment >= 2 ? 1 : 0 };
+   enum { Alignment_GreaterEqual_4Bytes = Alignment >= 4 ? 1 : 0 };
+   enum { Alignment_GreaterEqual_8Bytes = Alignment >= 8 ? 1 : 0 };
+@@ -50,6 +59,10 @@
+   enum { Alignment_LessEqual_16Bytes = Alignment <= 16 ? 1 : 0 };
+ };
+ 
++#ifndef _MSC_VER
++template <typename T> constexpr unsigned AlignOf<T>::Alignment;
++#endif
++
+ /// alignOf - A templated function that returns the minimum alignment of
+ ///  of a type.  This provides no extra functionality beyond the AlignOf
+ ///  class besides some cosmetic cleanliness.  Example usage:
+--- lib/IR/AttributeImpl.h	2014-08-13 12:26:38.000000000 -0400
++++ lib/IR/AttributeImpl.h	2015-08-23 17:27:29.366505172 -0400
+@@ -180,6 +180,9 @@
+       AttrList[I].Profile(ID);
+   }
+ };
++static_assert(AlignOf<AttributeSetNode>::Alignment >=
++                  AlignOf<Attribute>::Alignment,
++              "Insufficient alignment for objects appended to AttributeSetNode");
+ 
+ //===----------------------------------------------------------------------===//
+ /// \class
+@@ -188,9 +191,11 @@
+ class AttributeSetImpl : public FoldingSetNode {
+   friend class AttributeSet;
+ 
+-  LLVMContext &Context;
+-
++public:
+   typedef std::pair<unsigned, AttributeSetNode*> IndexAttrPair;
++
++private:
++  LLVMContext &Context;
+   unsigned NumAttrs; ///< Number of entries in this set.
+ 
+   /// \brief Return a pointer to the IndexAttrPair for the specified slot.
+@@ -205,6 +210,7 @@
+   AttributeSetImpl(LLVMContext &C,
+                    ArrayRef<std::pair<unsigned, AttributeSetNode *> > Attrs)
+       : Context(C), NumAttrs(Attrs.size()) {
++
+ #ifndef NDEBUG
+     if (Attrs.size() >= 2) {
+       for (const std::pair<unsigned, AttributeSetNode *> *i = Attrs.begin() + 1,
+@@ -266,6 +272,9 @@
+ 
+   void dump() const;
+ };
++static_assert(AlignOf<AttributeSetImpl>::Alignment >=
++                  AlignOf<AttributeSetImpl::IndexAttrPair>::Alignment,
++              "Insufficient alignment for objects appended to AttributeSetImpl");
+ 
+ } // end llvm namespace
+ 
+--- lib/IR/User.cpp	2015-08-23 17:27:29.366505172 -0400
++++ lib/IR/User.cpp	2015-08-23 17:34:56.427494589 -0400
+@@ -40,6 +40,11 @@
+ //===----------------------------------------------------------------------===//
+ 
+ Use *User::allocHungoffUses(unsigned N) const {
++  static_assert(AlignOf<Use>::Alignment >= AlignOf<Use::UserRef>::Alignment,
++                "Insufficient alignment for hung-off-uses objects");
++  static_assert(AlignOf<Use::UserRef>::Alignment >=
++                AlignOf<BasicBlock*>::Alignment,
++                "Insufficient alignment for hung-off-uses objects");
+   // Allocate the array of Uses, followed by a pointer (with bottom bit set) to
+   // the User.
+   size_t size = N * sizeof(Use) + sizeof(Use::UserRef);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/014-clang-gcc-toolchain.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,2323 @@
+# Solaris GCC Toolchain discovery.
+# https://llvm.org/bugs/show_bug.cgi?id=24606
+--- lib/Support/Host.cpp	2014-12-16 19:38:04.000000000 -0800
++++ lib/Support/Host.cpp	2016-02-09 09:59:19.281147309 -0800
+@@ -39,6 +39,11 @@
+ #include <mach/machine.h>
+ #endif
+ 
++#if defined(sun) || defined(__sun) || defined(__sun__)
++#include <cstring>
++#include <kstat.h>
++#endif
++
+ #define DEBUG_TYPE "host-detection"
+ 
+ //===----------------------------------------------------------------------===//
+@@ -674,6 +679,43 @@
+   
+   return "generic";
+ }
++#elif ((defined(sun) || defined(__sun) || defined(__sun__)) && \
++       (defined(sparc) || defined(__sparc) || defined(__sparc__)))
++StringRef sys::getHostCPUName() {
++  kstat_ctl_t *KC = 0;
++  kstat_t *KSP = 0;
++  kstat_named_t *KNP = 0;
++  static char Buffer[256];
++  static bool Init = false;
++  const char *Value;
++
++  if (!Init) {
++    KC = kstat_open();
++    if (KC) {
++      KSP = kstat_lookup(KC, "cpu_info", -1, "cpu_info0");
++      kstat_read(KC, KSP, NULL);
++      KNP = reinterpret_cast<kstat_named_t*>(kstat_data_lookup(KSP, "brand"));
++      Value = (const char *) KNP->value.str.addr.ptr;
++      (void) std::sprintf(Buffer, "%s (", Value);
++
++      KNP =
++        reinterpret_cast<kstat_named_t*>(kstat_data_lookup(KSP, "cpu_type"));
++      Value = (const char*) KNP->value.c;
++      (void) std::strcat(Buffer, Value);
++      (void) std::strcat(Buffer, ") ");
++
++      KNP =
++        reinterpret_cast<kstat_named_t*>(kstat_data_lookup(KSP,
++                                                           "implementation"));
++      Value = (const char*) KNP->value.str.addr.ptr;
++      (void) std::strcat(Buffer, Value);
++      Init = true;
++      kstat_close(KC);
++    }
++  }
++
++  return Buffer;
++}
+ #else
+ StringRef sys::getHostCPUName() {
+   return "generic";
+--- tools/clang/include/clang/Driver/Options.td	Sat Jul 18 11:44:46 2015
++++ tools/clang/include/clang/Driver/Options.td	Thu Aug 20 22:46:37 2015
+@@ -1129,6 +1129,11 @@
+ def mthread_model : Separate<["-"], "mthread-model">, Group<m_Group>, Flags<[CC1Option]>,
+   HelpText<"The thread model to use, e.g. posix, single (posix by default)">;
+ 
++def mvis : Flag<["-"], "mvis">, Group<m_Group>;
++def mvis2 : Flag<["-"], "mvis2">, Group<m_Group>;
++def mvis3 : Flag<["-"], "mvis3">, Group<m_Group>;
++def mimpure_text: Flag<["-"], "mimpure-text">, Group<m_Group>;
++
+ def mmmx : Flag<["-"], "mmmx">, Group<m_x86_Features_Group>;
+ def mno_3dnowa : Flag<["-"], "mno-3dnowa">, Group<m_x86_Features_Group>;
+ def mno_3dnow : Flag<["-"], "mno-3dnow">, Group<m_x86_Features_Group>;
+@@ -1690,6 +1695,7 @@
+ defm profile_use : BooleanFFlag<"profile-use">, Group<clang_ignored_gcc_optimization_f_Group>;
+ def fprofile_use_EQ : Joined<["-"], "fprofile-use=">, Group<clang_ignored_gcc_optimization_f_Group>;
+ def fuse_ld_EQ : Joined<["-"], "fuse-ld=">, Group<f_Group>;
++def fuse_as_EQ : Joined<["-"], "fuse-as=">, Group<f_Group>;
+ 
+ defm align_functions : BooleanFFlag<"align-functions">, Group<clang_ignored_gcc_optimization_f_Group>;
+ def falign_functions_EQ : Joined<["-"], "falign-functions=">, Group<clang_ignored_gcc_optimization_f_Group>;
+--- tools/clang/lib/Frontend/InitHeaderSearch.cpp	Thu Dec  4 16:22:48 2014
++++ tools/clang/lib/Frontend/InitHeaderSearch.cpp	Fri Aug 21 23:23:27 2015
+@@ -122,7 +122,7 @@
+   // Add the path with sysroot prepended, if desired and this is a system header
+   // group.
+   if (HasSysroot) {
+-    SmallString<256> MappedPathStorage;
++    SmallString<PATH_MAX> MappedPathStorage;
+     StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
+     if (CanPrefixSysroot(MappedPathStr)) {
+       AddUnmappedPath(IncludeSysroot + Path, Group, isFramework);
+@@ -138,7 +138,7 @@
+   assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
+ 
+   FileManager &FM = Headers.getFileMgr();
+-  SmallString<256> MappedPathStorage;
++  SmallString<PATH_MAX> MappedPathStorage;
+   StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
+ 
+   // Compute the DirectoryLookup type.
+@@ -187,12 +187,16 @@
+ 
+   // Add the multilib dirs
+   llvm::Triple::ArchType arch = triple.getArch();
+-  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
++  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64 ||
++    arch == llvm::Triple::sparcv9;
+   if (is64bit)
+     AddPath(Base + "/" + ArchDir + "/" + Dir64, CXXSystem, false);
+   else
+     AddPath(Base + "/" + ArchDir + "/" + Dir32, CXXSystem, false);
+ 
++  // Add GCC's "C" include dir
++  AddPath(Base + "/include", CXXSystem, false);
++
+   // Add the backward dir
+   AddPath(Base + "/backward", CXXSystem, false);
+ }
+@@ -442,8 +446,7 @@
+                                 "", "", "", triple);
+     break;
+   case llvm::Triple::Solaris:
+-    AddGnuCPlusPlusIncludePaths("/usr/gcc/4.5/include/c++/4.5.2/",
+-                                "i386-pc-solaris2.11", "", "", triple);
++    // All of this is handled in the driver.
+     break;
+   default:
+     break;
+@@ -462,6 +465,7 @@
+     break; // Everything else continues to use this routine's logic.
+ 
+   case llvm::Triple::Linux:
++  case llvm::Triple::Solaris:
+     return;
+ 
+   case llvm::Triple::Win32:
+@@ -484,7 +488,7 @@
+           // Remove clang from foo/lib/clang
+           StringRef Lib = llvm::sys::path::parent_path(NoVer);
+           // Remove lib from foo/lib
+-          SmallString<128> P = llvm::sys::path::parent_path(Lib);
++          SmallString<PATH_MAX> P = llvm::sys::path::parent_path(Lib);
+ 
+           // Get foo/include/c++/v1
+           llvm::sys::path::append(P, "include", "c++", "v1");
+@@ -491,10 +495,6 @@
+           AddUnmappedPath(P.str(), CXXSystem, false);
+         }
+       }
+-      // On Solaris, include the support directory for things like xlocale and
+-      // fudged system headers.
+-      if (triple.getOS() == llvm::Triple::Solaris) 
+-        AddPath("/usr/include/c++/v1/support/solaris", CXXSystem, false);
+       
+       AddPath("/usr/include/c++/v1", CXXSystem, false);
+     } else {
+--- tools/clang/lib/Driver/Tools.h	Wed Jan 28 15:52:21 2015
++++ tools/clang/lib/Driver/Tools.h	Thu Aug 20 22:46:37 2015
+@@ -529,6 +529,9 @@
+ 
+     bool hasIntegratedCPP() const override { return false; }
+ 
++    void RenderExtraToolArgs(const JobAction &JA,
++                             ArgStringList &CmdArgs) const;
++
+     void ConstructJob(Compilation &C, const JobAction &JA,
+                       const InputInfo &Output, const InputInfoList &Inputs,
+                       const llvm::opt::ArgList &TCArgs,
+@@ -541,6 +544,9 @@
+     bool hasIntegratedCPP() const override { return false; }
+     bool isLinkJob() const override { return true; }
+ 
++    void RenderExtraToolArgs(const JobAction &JA,
++                             ArgStringList &CmdArgs) const;
++
+     void ConstructJob(Compilation &C, const JobAction &JA,
+                       const InputInfo &Output, const InputInfoList &Inputs,
+                       const llvm::opt::ArgList &TCArgs,
+--- tools/clang/lib/Driver/Tools.cpp	Sat Jul 18 11:44:46 2015
++++ tools/clang/lib/Driver/Tools.cpp	Sat Aug 22 17:26:16 2015
+@@ -60,6 +60,12 @@
+   }
+ }
+ 
++static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
++                      ArgStringList &CmdArgs, const ArgList &Args);
++
++static void AddLibgcc(const Driver &D, ArgStringList &CmdArgs,
++                       const ArgList &Args, const std::string& Exec);
++
+ /// CheckPreprocessingOptions - Perform some validation of preprocessing
+ /// arguments that is shared with gcc.
+ static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
+@@ -1360,14 +1366,30 @@
+   return "";
+ }
+ 
++static const char *getSparcTargetCPU(const ArgList &Args,
++                                     const llvm::Triple &Triple);
++
++static const char *getSparcTargetCPUFeature(const char* CPU,
++                                            const ArgList &Args,
++                                            const llvm::Triple &Triple);
++
+ static void getSparcTargetFeatures(const ArgList &Args,
+-                                   std::vector<const char *> &Features) {
+-  bool SoftFloatABI = true;
++                                   std::vector<const char *> &Features,
++                                   const llvm::Triple &Triple) {
++  bool SoftFloatABI;
++
++  if ((Triple.getOS() == llvm::Triple::Solaris) ||
++      (Triple.getOS() == llvm::Triple::Linux))
++    SoftFloatABI = false;
++  else
++    SoftFloatABI = true;
++
+   if (Arg *A =
+           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
+     if (A->getOption().matches(options::OPT_mhard_float))
+       SoftFloatABI = false;
+   }
++
+   if (SoftFloatABI)
+     Features.push_back("+soft-float");
+ }
+@@ -1375,17 +1397,31 @@
+ void Clang::AddSparcTargetArgs(const ArgList &Args,
+                              ArgStringList &CmdArgs) const {
+   const Driver &D = getToolChain().getDriver();
++  const llvm::Triple &T = getToolChain().getTriple();
+ 
+   // Select the float ABI as determined by -msoft-float and -mhard-float.
++  // There is no support for soft-float ABI in Solaris.
+   StringRef FloatABI;
+   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
+                                options::OPT_mhard_float)) {
+-    if (A->getOption().matches(options::OPT_msoft_float))
++    if (A->getOption().matches(options::OPT_msoft_float)) {
++      if ((T.getOS() == llvm::Triple::Solaris) ||
++          (T.getOS() == llvm::Triple::Linux)) {
++        D.Diag(diag::warn_drv_clang_unsupported) << "-msoft-float";
++        D.Diag(diag::warn_drv_overriding_flag_option) <<
++          "-msoft-float" << "-mhard-float";
++        FloatABI = "hard";
++      } else {
+       FloatABI = "soft";
+-    else if (A->getOption().matches(options::OPT_mhard_float))
++      }
++    } else if (A->getOption().matches(options::OPT_mhard_float))
+       FloatABI = "hard";
+   }
+ 
++  if (((T.getOS() == llvm::Triple::Solaris) ||
++       (T.getOS() == llvm::Triple::Linux)) && FloatABI.empty())
++    FloatABI = "hard";
++
+   // If unspecified, choose the default based on the platform.
+   if (FloatABI.empty()) {
+     // Assume "soft", but warn the user we are guessing.
+@@ -1400,10 +1436,93 @@
+     CmdArgs.push_back("-msoft-float");
+   } else {
+     assert(FloatABI == "hard" && "Invalid float abi!");
+-    CmdArgs.push_back("-mhard-float");
+   }
++
++  std::string Feature;
++  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
++    Feature = "-march=";
++    Feature += A->getValue();
++    CmdArgs.push_back(Args.MakeArgString("-target-feature"));
++    CmdArgs.push_back(Args.MakeArgString(Feature.c_str()));
+ }
+ 
++  if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
++    Feature = "-mtune=";
++    Feature += A->getValue();
++    CmdArgs.push_back(Args.MakeArgString("-target-feature"));
++    CmdArgs.push_back(Args.MakeArgString(Feature.c_str()));
++  }
++
++  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
++    Feature = "-mcpu=";
++    Feature += A->getValue();
++    CmdArgs.push_back(Args.MakeArgString("-target-feature"));
++    CmdArgs.push_back(Args.MakeArgString(Feature.c_str()));
++  }
++}
++
++static const char *getSparcTargetCPU(const ArgList &Args,
++                                     const llvm::Triple &Triple) {
++    StringRef V;
++
++    if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
++      V = A->getValue();
++      switch (Triple.getOS()) {
++      case llvm::Triple::Solaris:
++      case llvm::Triple::Linux:
++        if (V == "v8plus" || V == "v8plusa" ||
++            V == "v8plusb" || V == "v9" ||
++            V == "v9a" || V == "v9b" ||
++            V == "sparcmaf" || V == "sparc4" )
++          return Args.MakeArgString(V);
++        break;
++      default:
++        return Args.MakeArgString("v8plusa");
++        break;
++      }
++    }
++
++    if (Arg *AA = Args.getLastArg(options::OPT_m64))
++      return "v9a";
++
++    return "v8plusa";
++}
++
++static const char *getSparcTargetCPUFeature(const char* CPU,
++                                            const ArgList &Args,
++                                            const llvm::Triple &Triple) {
++  StringRef V;
++  if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
++    V = A->getValue();
++
++    if (V.empty())
++      if (Arg *AA = Args.getLastArg(options::OPT_m64))
++        return "vis";
++
++    if (V == "ultrasparc" || V == "ultrasparc2" ||
++        V == "ultrasparc3" || V == "sparcmaf" || V == "sparc4" )
++      return Args.MakeArgString(A->getValue());
++  }
++
++  if (!CPU)
++    return 0;
++
++  std::string C = CPU;
++
++  if (C == "v8plus" || C == "v9")
++    return "";
++
++  if (C == "v8plusa" || C == "v9a")
++    return "vis1";
++  else if (C == "v8plusb" || C == "v9b")
++    return "vis2";
++  else if (C == "sparcmaf" || C == "sparc4")
++    return "vis3";
++
++  return 0;
++}
++
++
+ static const char *getSystemZTargetCPU(const ArgList &Args) {
+   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
+     return A->getValue();
+@@ -1872,7 +1991,7 @@
+     break;
+   case llvm::Triple::sparc:
+   case llvm::Triple::sparcv9:
+-    getSparcTargetFeatures(Args, Features);
++    getSparcTargetFeatures(Args, Features, Triple);
+     break;
+   case llvm::Triple::aarch64:
+   case llvm::Triple::aarch64_be:
+@@ -2695,6 +2814,23 @@
+     }
+   }
+ 
++  // Solaris-specific defaults for PIE
++  if (getToolChain().getTriple().getOS() == llvm::Triple::Solaris) {
++    switch (getToolChain().getTriple().getArch()) {
++    case llvm::Triple::x86:
++      IsPICLevelTwo = false; // "-fpie"
++      break;
++    case llvm::Triple::sparc:
++    case llvm::Triple::x86_64:
++    case llvm::Triple::sparcv9:
++      IsPICLevelTwo = true; // "-fPIE"
++      break;
++
++    default:
++      break;
++    }
++  }
++
+   // For the PIC and PIE flag options, this logic is different from the
+   // legacy logic in very old versions of GCC, as that logic was just
+   // a bug no one had ever fixed. This logic is both more rational and
+@@ -2740,6 +2876,47 @@
+   if (Args.hasArg(options::OPT_static))
+     PIC = PIE = false;
+ 
++  if (Triple.getOS() == llvm::Triple::Solaris) {
++    if (Arg *A = Args.getLastArg(options::OPT_shared)) {
++      PIC = true;
++      PIE = false;
++      CmdArgs.push_back("-mrelocation-model");
++      CmdArgs.push_back("pic");
++      if (IsPICLevelTwo) {
++        CmdArgs.push_back("-pic-level");
++        CmdArgs.push_back("2");
++      }
++    } else if (PIC) {
++      PIC = true;
++      PIE = false;
++      CmdArgs.push_back("-mrelocation-model");
++      CmdArgs.push_back("pic");
++      if (IsPICLevelTwo) {
++        CmdArgs.push_back("-pic-level");
++        CmdArgs.push_back("2");
++      }
++    } else if (PIE) {
++      PIC = PIE = true;
++      CmdArgs.push_back("-mrelocation-model");
++      CmdArgs.push_back("pic");
++      if (IsPICLevelTwo) {
++        CmdArgs.push_back("-pie-level");
++        CmdArgs.push_back("2");
++      }
++    } else if (Args.hasArg(options::OPT_static)) {
++      // Solaris doesn't to static relocations.
++      PIC = PIE = false;
++      CmdArgs.push_back("-mrelocation-model");
++      CmdArgs.push_back("dynamic-no-pic");
++    } else {
++      // This is a Solaris non-PIE executable.
++      // Solaris doesn't to static relocations.
++      PIC = PIE = false;
++      CmdArgs.push_back("-mrelocation-model");
++      CmdArgs.push_back("dynamic-no-pic");
++    }
++  }
++
+   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
+     // This is a very special mode. It trumps the other modes, almost no one
+     // uses it, and it isn't even valid on any OS but Darwin.
+@@ -2762,6 +2939,8 @@
+   } else {
+     // Currently, LLVM only knows about PIC vs. static; the PIE differences are
+     // handled in Clang's IRGen by the -pie-level flag.
++    // Solaris already took care of PIC/PIE/non-PIC above.
++    if (Triple.getOS() != llvm::Triple::Solaris) {
+     CmdArgs.push_back("-mrelocation-model");
+     CmdArgs.push_back(PIC ? "pic" : "static");
+ 
+@@ -2774,6 +2953,7 @@
+       }
+     }
+   }
++  }
+ 
+   CmdArgs.push_back("-mthread-model");
+   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
+@@ -3180,12 +3360,13 @@
+       // FIXME: we should support specifying dwarf version with
+       // -gline-tables-only.
+       CmdArgs.push_back("-gline-tables-only");
+-      // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
++      // Default is dwarf-2 for Darwin, OpenBSD and FreeBSD.
+       const llvm::Triple &Triple = getToolChain().getTriple();
+       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
+-          Triple.getOS() == llvm::Triple::FreeBSD ||
+-          Triple.getOS() == llvm::Triple::Solaris)
++          Triple.getOS() == llvm::Triple::FreeBSD)
+         CmdArgs.push_back("-gdwarf-2");
++      else if (Triple.getOS() == llvm::Triple::Solaris)
++        CmdArgs.push_back("-gdwarf-4");
+     } else if (A->getOption().matches(options::OPT_gdwarf_2))
+       CmdArgs.push_back("-gdwarf-2");
+     else if (A->getOption().matches(options::OPT_gdwarf_3))
+@@ -3194,12 +3375,13 @@
+       CmdArgs.push_back("-gdwarf-4");
+     else if (!A->getOption().matches(options::OPT_g0) &&
+              !A->getOption().matches(options::OPT_ggdb0)) {
+-      // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
++      // Default is dwarf-2 for Darwin, OpenBSD and FreeBSD.
+       const llvm::Triple &Triple = getToolChain().getTriple();
+       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
+-          Triple.getOS() == llvm::Triple::FreeBSD ||
+-          Triple.getOS() == llvm::Triple::Solaris)
++          Triple.getOS() == llvm::Triple::FreeBSD)
+         CmdArgs.push_back("-gdwarf-2");
++      else if (Triple.getOS() == llvm::Triple::Solaris)
++        CmdArgs.push_back("-gdwarf-4");
+       else
+         CmdArgs.push_back("-g");
+     }
+@@ -3594,6 +3776,7 @@
+     // If -fmessage-length=N was not specified, determine whether this is a
+     // terminal and, if so, implicitly define -fmessage-length appropriately.
+     unsigned N = llvm::sys::Process::StandardErrColumns();
++    if (N == 0) N = 72U;
+     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
+   }
+ 
+@@ -3735,6 +3918,7 @@
+     CmdArgs.push_back("-backend-option");
+     CmdArgs.push_back("-force-align-stack");
+   }
++
+   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
+                    false)) {
+     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
+@@ -3743,6 +3927,10 @@
+   if (Args.hasArg(options::OPT_mstack_alignment)) {
+     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
+     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
++  } else {
++    if ((getToolChain().getTriple().getArch() == llvm::Triple::sparc) ||
++        (getToolChain().getTriple().getArch() == llvm::Triple::sparcv9))
++      CmdArgs.push_back("-mstack-alignment=16");
+   }
+ 
+   if (getToolChain().getTriple().getArch() == llvm::Triple::aarch64 ||
+@@ -6049,6 +6237,10 @@
+   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
+ }
+ 
++void solaris::Assemble::RenderExtraToolArgs(const JobAction &JA,
++                                            ArgStringList &CmdArgs) const {
++}
++
+ void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
+                                       const InputInfo &Output,
+                                       const InputInfoList &Inputs,
+@@ -6055,61 +6247,321 @@
+                                       const ArgList &Args,
+                                       const char *LinkingOutput) const {
+   claimNoWarnArgs(Args);
++
++  const toolchains::Solaris &TC =
++    static_cast<const toolchains::Solaris&>(getToolChain());
++
++  if (!TC.isValid()) {
++    llvm::errs() << "Invalid GCC installation!\n";
++    return;
++  }
++
++  const llvm::Triple &TT = TC.getTriple();
++  const Driver &D = TC.getDriver();
++  llvm::Triple::ArchType Arch = TT.getArch();
++  StringRef Assembler = TC.getAssembler();
++  bool m32 = true;
++
++  std::string march;
++  std::string mtune;
++  std::string mcpu;
++
+   ArgStringList CmdArgs;
+ 
+-  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
+-                       options::OPT_Xassembler);
++  if (Arg *A = Args.getLastArg(options::OPT_march_EQ))
++    march = A->getValue();
++  else
++    march = TC.getMArch();
+ 
++  if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ))
++    mtune = A->getValue();
++  else
++    mtune = TC.getMTune();
++
++  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
++    mcpu = A->getValue();
++  else
++    mcpu = TC.getMCpu();
++
++  if (Arg *A = Args.getLastArg(options::OPT_m64))
++    m32 = false;
++
++  if (Args.hasArg(options::OPT_v))
++    CmdArgs.push_back("-V");
++
++  switch (Arch) {
++  case llvm::Triple::x86:
++  case llvm::Triple::x86_64:
++    if (m32)
++      CmdArgs.push_back("--32");
++    else
++      CmdArgs.push_back("--64");
++    break;
++  case llvm::Triple::sparc:
++  case llvm::Triple::sparcv9:
++    if (m32) {
++      CmdArgs.push_back("-32");
++      march="v8plusa";
++      mcpu="v8plusa";
++    } else {
++      CmdArgs.push_back("-64");
++      march="v9a";
++      mcpu="v9a";
++    }
++    break;
++  default:
++    D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
++      << TT.getTriple();
++    break;
++  }
++
++  std::string xarch;
++
++  switch (Arch) {
++    case llvm::Triple::sparc:
++    case llvm::Triple::sparcv9:
++      if (!march.empty()) {
++        xarch = "-xarch=";
++        xarch += march;
++        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
++      } else if (!mtune.empty()) {
++        xarch = "-xarch=";
++        xarch += mtune;
++        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
++      } else if (!mcpu.empty()) {
++        xarch = "-xarch=";
++        xarch += mcpu;
++        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
++      }
++
++      addAssemblerKPIC(Args, CmdArgs);
++
++      if (Args.hasArg(options::OPT_mstrict_align))
++        CmdArgs.push_back("--enforce-aligned-data");
++      break;
++    case llvm::Triple::x86:
++    case llvm::Triple::x86_64:
++      if (!march.empty()) {
++        xarch = "-mtune=";
++        xarch += march;
++        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
++      } else if (!mtune.empty()) {
++        xarch = "-mtune=";
++        xarch += mtune;
++        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
++      }
++      if (!mcpu.empty()) {
++        xarch = "-march=";
++        xarch += mcpu;
++        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
++      }
++      break;
++    default:
++      D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
++        << TT.getTriple();
++      break;
++  }
++
++  if (Args.hasArg(options::OPT_g_Flag) || Args.hasArg(options::OPT_g0) ||
++      Args.hasArg(options::OPT_g1) || Args.hasArg(options::OPT_g2) ||
++      Args.hasArg(options::OPT_g3))
++    CmdArgs.push_back("--gen-debug");
++
++  if (Output.isFilename()) {
+   CmdArgs.push_back("-o");
+   CmdArgs.push_back(Output.getFilename());
++  } else {
++    D.Diag(diag::err_drv_invalid_gcc_output_type) << "<unspecified>";
++    CmdArgs.push_back("-fsyntax-only");
++  }
+ 
+-  for (const auto &II : Inputs)
++  RenderExtraToolArgs(JA, CmdArgs);
++
++  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
++                       options::OPT_Xassembler);
++
++  for (const auto &II : Inputs) {
++    if (II.getType() == types::TY_LLVM_IR ||
++        II.getType() == types::TY_LTO_IR ||
++        II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
++      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
++        << getToolChain().getTripleString();
++    else if (II.getType() == types::TY_AST)
++      D.Diag(clang::diag::err_drv_no_ast_support)
++        << getToolChain().getTripleString();
++    else if (II.getType() == types::TY_ModuleFile)
++      D.Diag(diag::err_drv_no_module_support)
++        << getToolChain().getTripleString();
++
++    if (II.isFilename())
+     CmdArgs.push_back(II.getFilename());
++    else
++      II.getInputArg().render(Args, CmdArgs);
++  }
+ 
+-  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
+-  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
++  C.addCommand(llvm::make_unique<Command>(JA, *this,
++                                          Args.MakeArgString(Assembler),
++                                          CmdArgs));
+ }
+ 
++
++void solaris::Link::RenderExtraToolArgs(const JobAction &JA,
++                                        ArgStringList &CmdArgs) const {
++}
++
+ void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
+                                   const InputInfo &Output,
+                                   const InputInfoList &Inputs,
+                                   const ArgList &Args,
+                                   const char *LinkingOutput) const {
+-  // FIXME: Find a real GCC, don't hard-code versions here
+-  std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
+-  const llvm::Triple &T = getToolChain().getTriple();
+-  std::string LibPath = "/usr/lib/";
++  const toolchains::Solaris& TC =
++    static_cast<const toolchains::Solaris&>(getToolChain());
++
++  if (!TC.isValid()) {
++    llvm::errs() << "Invalid GCC installation!\n";
++    return;
++  }
++
++  const llvm::Triple &T = TC.getTriple();
++  const Driver &D = TC.getDriver();
+   llvm::Triple::ArchType Arch = T.getArch();
++  bool m32 = true;
++  StringRef Linker = TC.getLinker();
++
++  if (Arg *A = Args.getLastArg(options::OPT_m64))
++    m32 = false;
++
++  std::string GCCLibPath;
++  std::string YPPath;
++  GCCLibPath += "/lib/gcc/";
++  std::string LibPath = "/usr/lib/";
++  std::string ShortLibPath = "/lib/";
++  std::string ClangLibPath;
++  const char* moption;
++
+   switch (Arch) {
+   case llvm::Triple::x86:
+-    GCCLibPath +=
+-        ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
++    if (m32) {
++      GCCLibPath = TC.getGCCInternalLibDir().str();
++      GCCLibPath += "/";
++      moption = "-32";
++      YPPath = "/lib:/usr/lib";
++      ClangLibPath = "/usr/lib/clang/";
++    } else {
++      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
++      GCCLibPath += "/";
++      LibPath += "amd64/";
++      ShortLibPath += "amd64/";
++      moption = "-64";
++      YPPath = "/lib/amd64:/usr/lib/amd64";
++      ClangLibPath = "/usr/lib/clang/amd64/";
++    }
+     break;
++  case llvm::Triple::sparc:
++    if (m32) {
++      GCCLibPath = TC.getGCCInternalLibDir().str();
++      GCCLibPath += "/";
++      moption = "-32";
++      YPPath = "/lib:/usr/lib";
++      ClangLibPath = "/usr/lib/clang/";
++    } else {
++      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
++      GCCLibPath += "/";
++      LibPath += "sparcv9/";
++      ShortLibPath += "sparcv9/";
++      moption = "-64";
++      YPPath = "/lib/sparcv9:/usr/lib/sparcv9";
++      ClangLibPath = "/usr/lib/clang/sparcv9/";
++    }
++    break;
+   case llvm::Triple::x86_64:
+-    GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
+-    GCCLibPath += "/4.5.2/amd64/";
++    if (m32) {
++      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
++      GCCLibPath += "/";
++      moption = "-32";
++      YPPath = "/lib:/usr/lib";
++      ClangLibPath = "/usr/lib/clang/";
++    } else {
++      GCCLibPath = TC.getGCCInternalLibDir().str();
++      GCCLibPath += "/";
+     LibPath += "amd64/";
++      ShortLibPath += "amd64/";
++      moption = "-64";
++      YPPath = "/lib/amd64:/usr/lib/amd64";
++      ClangLibPath = "/usr/lib/clang/amd64/";
++    }
+     break;
++  case llvm::Triple::sparcv9:
++    if (m32) {
++      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
++      GCCLibPath += "/";
++      moption = "-32";
++      YPPath = "/lib:/usr/lib";
++      ClangLibPath = "/usr/lib/clang/";
++    } else {
++      GCCLibPath = TC.getGCCInternalLibDir().str();
++      GCCLibPath += "/";
++      LibPath += "sparcv9/";
++      ShortLibPath += "sparcv9/";
++      moption = "-64";
++      YPPath = "/lib/sparcv9:/usr/lib/sparcv9";
++      ClangLibPath = "/usr/lib/clang/sparcv9/";
++    }
++    break;
+   default:
+-    llvm_unreachable("Unsupported architecture");
++    D.Diag(diag::err_target_unsupported_arch) << T.getArchName()
++      << T.getTriple();
++    break;
+   }
+ 
+   ArgStringList CmdArgs;
+ 
+-  // Demangle C++ names in errors
+-  CmdArgs.push_back("-C");
++  CmdArgs.push_back(Args.MakeArgString("-zignore"));
+ 
+-  if ((!Args.hasArg(options::OPT_nostdlib)) &&
+-      (!Args.hasArg(options::OPT_shared))) {
+-    CmdArgs.push_back("-e");
+-    CmdArgs.push_back("_start");
++  Arg *PIEArg = Args.getLastArg(options::OPT_fPIE, options::OPT_fpie);
++  if (PIEArg) {
++    if (PIEArg->getOption().matches(options::OPT_fPIE) ||
++        PIEArg->getOption().matches(options::OPT_fpie)) {
++      CmdArgs.push_back(Args.MakeArgString("-Qy"));
++      CmdArgs.push_back(Args.MakeArgString("-zdirect"));
++      CmdArgs.push_back(Args.MakeArgString("-ztextwarn"));
++      CmdArgs.push_back(Args.MakeArgString("-ztype=pie"));
++      CmdArgs.push_back(Args.MakeArgString("-zaslr=enable"));
+   }
++  }
+ 
++  // Silence warning for "-g: argument not used during compilation
++  Args.ClaimAllArgs(options::OPT_g_Group);
++
++  // Language options
++  Args.ClaimAllArgs(options::OPT_emit_llvm);
++  Args.ClaimAllArgs(options::OPT_w);
++
++  if (Args.hasArg(options::OPT_s))
++    CmdArgs.push_back("-s");
++
++  const std::vector<std::string> &ExtraOpts = TC.getExtraOpts();
++
++  // Handle extra options
++  if (ExtraOpts.size()) {
++    for (std::vector<std::string>::const_iterator I = ExtraOpts.begin(),
++         E = ExtraOpts.end(); I != E; ++I)
++      CmdArgs.push_back((*I).c_str());
++  }
++
++  // Demangle C++ names
++  if (Linker == "/usr/gnu/bin/ld.bfd" || Linker == "/usr/gnu/bin/ld.gold" ||
++      Linker == "/usr/gnu/bin/ld" || Linker == "/usr/bin/gld")
++    CmdArgs.push_back("--demangle");
++  else if (Linker == "/usr/bin/ld")
++    CmdArgs.push_back("-C");
++
+   if (Args.hasArg(options::OPT_static)) {
+     CmdArgs.push_back("-Bstatic");
+     CmdArgs.push_back("-dn");
+   } else {
+     CmdArgs.push_back("-Bdynamic");
++    CmdArgs.push_back("-dy");
+     if (Args.hasArg(options::OPT_shared)) {
+       CmdArgs.push_back("-shared");
+     } else {
+@@ -6125,41 +6577,261 @@
+     assert(Output.isNothing() && "Invalid output.");
+   }
+ 
++  const char* Values = "values-Xa.o";
++  const char* Xpg = "values-xpg4.o";
++
++  Arg *STDArg = Args.getLastArg(options::OPT_std_EQ);
++  if (STDArg) {
++    if (STDArg->getOption().matches(options::OPT_std_EQ)) {
++      std::string Lang = STDArg->getValue();
++      if ((Lang == "c99") || (Lang == "c11") ||
++          (Lang == "c++11") || (Lang == "c++14")) {
++        Values = "values-Xc.o";
++        Xpg = "values-xpg6.o";
++      }
++    }
++  }
++
++  const char *gldm = 0;
++  if (Linker == "/usr/gnu/bin/ld.bfd" || Linker == "/usr/gnu/bin/ld.gold" ||
++      Linker == "/usr/gnu/bin/ld" || Linker == "/usr/bin/gld") {
++    switch (Arch) {
++    case llvm::Triple::x86:
++      if (m32)
++        gldm = "-m elf_i386";
++      else
++        gldm = "-m elf_x86_64";
++      break;
++    case llvm::Triple::x86_64:
++      if (m32)
++        gldm = "-m elf_i386";
++      else
++        gldm = "-m elf_x86_64";
++      break;
++    case llvm::Triple::sparc:
++      if (m32)
++        gldm = "-m elf32_sparc";
++      else
++        gldm = "-m elf64_sparc";
++      break;
++    case llvm::Triple::sparcv9:
++      if (m32)
++        gldm = "-m elf32_sparc";
++      else
++        gldm = "-m elf64_sparc";
++      break;
++    default:
++      break;
++    }
++
++    if (gldm)
++      CmdArgs.push_back(Args.MakeArgString(StringRef(gldm)));
++
++    if (Linker == "/usr/gnu/bin/ld.gold") {
++      if (Args.hasArg(options::OPT_O))
++        Args.AddAllArgs(CmdArgs, options::OPT_O);
++    }
++  }
++
++  if (Args.hasArg(options::OPT_v))
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-V")));
++
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-Qy")));
++  if (Linker == "/usr/bin/ld") {
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-Y")));
++    CmdArgs.push_back(Args.MakeArgString(StringRef("P," + YPPath)));
++  } else {
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-Y")));
++    CmdArgs.push_back(Args.MakeArgString(StringRef(YPPath)));
++  }
++
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
++
++  std::string P = GCCLibPath;
++  P += "../../..";
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
++
++  std::string crt1o;
++
+   if (!Args.hasArg(options::OPT_nostdlib) &&
+       !Args.hasArg(options::OPT_nostartfiles)) {
+     if (!Args.hasArg(options::OPT_shared)) {
+-      CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
++      switch (Arch) {
++      case llvm::Triple::sparc:
++      case llvm::Triple::sparcv9:
++        crt1o = GCCLibPath;
++        break;
++      case llvm::Triple::x86:
++      case llvm::Triple::x86_64:
++        crt1o = LibPath;
++        break;
++      default:
++        D.Diag(diag::err_target_unsupported_arch) << T.getArchName()
++          << T.getTriple();
++        break;
++      }
++
++      crt1o += "/crt1.o";
++
++      CmdArgs.push_back(Args.MakeArgString(crt1o.c_str()));
+       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
+-      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
++      CmdArgs.push_back(Args.MakeArgString("-L" + P));
+       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
+     } else {
+       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
+-      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
+       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
+     }
+-    if (getToolChain().getDriver().CCCIsCXX())
+-      CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
++  } else if (Args.hasArg(options::OPT_nostdlib) &&
++             !Args.hasArg(options::OPT_nostartfiles)) {
++    if (Args.hasArg(options::OPT_shared)) {
++      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
++      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
++    } else {
++      CmdArgs.push_back(Args.MakeArgString(crt1o.c_str()));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
++      CmdArgs.push_back(Args.MakeArgString("-L" + P));
+   }
++  } else if (!Args.hasArg(options::OPT_nostdlib) &&
++             Args.hasArg(options::OPT_nostartfiles)) {
++    if (Args.hasArg(options::OPT_shared)) {
++      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
++    }
++  }
+ 
+-  CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
++  // Itanium C++ ABI.
++  std::string CXAFinalize;
++  bool HasSystemCXAFinalize = false;
+ 
++  if (!Args.hasArg(options::OPT_shared)) {
++    if (PIEArg) {
++      if (PIEArg->getOption().matches(options::OPT_fPIE) ||
++          PIEArg->getOption().matches(options::OPT_fpie)) {
++        CXAFinalize = ClangLibPath + "cxa_finalize_pic.o";
++      }
++    } else {
++      CXAFinalize = ClangLibPath + "cxa_finalize.o";
++    }
++
++    HasSystemCXAFinalize = llvm::sys::fs::exists(CXAFinalize.c_str());
++
++    if (D.CCCIsCXX() && HasSystemCXAFinalize)
++      CmdArgs.push_back(Args.MakeArgString(CXAFinalize.c_str()));
++  }
++
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L" + GCCLibPath)));
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + ShortLibPath));
++
+   Args.AddAllArgs(CmdArgs, options::OPT_L);
++  const ToolChain::path_list Paths = TC.getFilePaths();
++  for (ToolChain::path_list::const_iterator B = Paths.begin(), E = Paths.end();
++       B != E; ++B) {
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *B));
++
++    // Itanium C++ ABI.
++    if (!Args.hasArg(options::OPT_shared)) {
++      if (D.CCCIsCXX() && !HasSystemCXAFinalize) {
++        if (PIEArg) {
++          if (PIEArg->getOption().matches(options::OPT_fPIE) ||
++              PIEArg->getOption().matches(options::OPT_fpie)) {
++            CXAFinalize = *B + "/cxa_finalize_pic.o";
++          }
++        } else {
++          CXAFinalize = *B + "/cxa_finalize.o";
++        }
++
++        if (llvm::sys::fs::exists(CXAFinalize.c_str()))
++          CmdArgs.push_back(Args.MakeArgString(CXAFinalize.c_str()));
++      }
++    }
++  }
++
+   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
+   Args.AddAllArgs(CmdArgs, options::OPT_e);
++  Args.AddAllArgs(CmdArgs, options::OPT_s);
++  Args.AddAllArgs(CmdArgs, options::OPT_t);
+   Args.AddAllArgs(CmdArgs, options::OPT_r);
+ 
+-  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
++  std::vector<std::string>  zoptions = Args.getAllArgValues(options::OPT_z);
++  std::string zoption;
+ 
++  for (std::vector<std::string>::const_iterator B = zoptions.begin(),
++      E = zoptions.end(); B != E; ++B) {
++    zoption = "-z";
++    zoption += *B;
++    CmdArgs.push_back(Args.MakeArgString(StringRef(zoption)));
++  }
++
++  if (!Args.hasArg(options::OPT_mimpure_text) &&
++      !Args.hasArg(options::OPT_fpie) &&
++      !Args.hasArg(options::OPT_fPIE))
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-ztext")));
++
++  // Itanium C++ ABI.
++  if (D.CCCIsCXX()) {
++    if (!Args.hasArg(options::OPT_shared)) {
++      const char* zfiniarray = "-zfiniarray=__cxa_finalize";
++      CmdArgs.push_back(Args.MakeArgString(zfiniarray));
++    }
++  }
++
++  if (Linker == "/usr/gnu/bin/ld.gold" || Linker == "/usr/gnu/bin/ld" ||
++      Linker == "/usr/gnu/bin/ld.bfd") {
++    CmdArgs.push_back("-plugin");
++    std::string Plugin = D.Dir + "/../lib/LLVMgold.so";
++    CmdArgs.push_back(Args.MakeArgString(Plugin));
++  } else {
++    CmdArgs.push_back(moption);
++  }
++
++  if (Arg *A = Args.getLastArg(options::OPT_rpath)) {
++    StringRef V = A->getValue();
++    if (Linker == "/usr/gnu/bin/ld.gold" || Linker == "/usr/gnu/bin/ld" ||
++        Linker == "/usr/gnu/bin/ld.bfd") {
++      CmdArgs.push_back(Args.MakeArgString("-rpath"));
++      CmdArgs.push_back(Args.MakeArgString(V));
++    } else {
++      CmdArgs.push_back(Args.MakeArgString("-R"));
++      CmdArgs.push_back(Args.MakeArgString(V));
++    }
++  }
++
++  AddLinkerInputs(TC, Inputs, Args, CmdArgs);
++  AddLibgcc(D, CmdArgs, Args, Linker.str());
++
+   if (!Args.hasArg(options::OPT_nostdlib) &&
+       !Args.hasArg(options::OPT_nodefaultlibs)) {
+-    if (getToolChain().getDriver().CCCIsCXX())
+-      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
+-    CmdArgs.push_back("-lgcc_s");
+-    if (!Args.hasArg(options::OPT_shared)) {
+-      CmdArgs.push_back("-lgcc");
++    if (D.CCCIsCXX())
++      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
++
+       CmdArgs.push_back("-lc");
+       CmdArgs.push_back("-lm");
++    CmdArgs.push_back("-lgcc_s");
++
++    if (Args.hasArg(options::OPT_static)) {
++      CmdArgs.push_back("-lgcc");
++      CmdArgs.push_back("-lgcc_eh");
+     }
++  } else if (Args.hasArg(options::OPT_nostdlib) &&
++             (!Args.hasArg(options::OPT_nodefaultlibs))) {
++    CmdArgs.push_back("-lgcc_s");
++
++    if (Args.hasArg(options::OPT_static))
++      CmdArgs.push_back("-lgcc_eh");
+   }
+ 
+   if (!Args.hasArg(options::OPT_nostdlib) &&
+@@ -6166,15 +6838,17 @@
+       !Args.hasArg(options::OPT_nostartfiles)) {
+     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
+   }
++
+   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
+ 
+-  addProfileRT(getToolChain(), Args, CmdArgs);
++  addProfileRT(TC, Args, CmdArgs);
+ 
+-  const char *Exec =
+-    Args.MakeArgString(getToolChain().GetLinkerPath());
+-  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
++  C.addCommand(llvm::make_unique<Command>(JA, *this,
++                                          Args.MakeArgString(Linker),
++                                          CmdArgs));
+ }
+ 
++
+ void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
+                                      const InputInfo &Output,
+                                      const InputInfoList &Inputs,
+@@ -7280,6 +7954,40 @@
+   if (isAndroid && !StaticLibgcc)
+     CmdArgs.push_back("-ldl");
+ }
++
++static void AddLibgcc(const Driver &D, ArgStringList &CmdArgs,
++                      const ArgList &Args, const std::string& Exec) {
++  bool StaticLibgcc = Args.hasArg(options::OPT_static) ||
++    Args.hasArg(options::OPT_static_libgcc);
++  if (!D.CCCIsCXX())
++    CmdArgs.push_back("-lgcc");
++
++  if (StaticLibgcc) {
++    if (D.CCCIsCXX())
++      CmdArgs.push_back("-lgcc");
++  } else {
++    if ((!D.CCCIsCXX()) && ((Exec == "/usr/bin/gld") ||
++                            (Exec == "/usr/gnu/bin/ld") ||
++                            (Exec == "/usr/gnu/bin/ld.bfd") ||
++                            (Exec == "/usr/gnu/bin/ld.gold")))
++      CmdArgs.push_back("--as-needed");
++
++    CmdArgs.push_back("-lgcc_s");
++    if ((!D.CCCIsCXX()) && ((Exec == "/usr/bin/gld") ||
++                            (Exec == "/usr/gnu/bin/ld") ||
++                            (Exec == "/usr/gnu/bin/ld.bfd") ||
++                            (Exec == "/usr/gnu/bin/ld.gold")))
++      CmdArgs.push_back("--no-as-needed");
++  }
++
++  if (StaticLibgcc)
++    CmdArgs.push_back("-lgcc_eh");
++  else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
++    CmdArgs.push_back("-lgcc");
++
++  if (!StaticLibgcc)
++    CmdArgs.push_back("-ldl");
++}
+ 
+ static std::string getLinuxDynamicLinker(const ArgList &Args,
+                                          const toolchains::Linux &ToolChain) {
+--- tools/clang/lib/Driver/ToolChains.h	2015-08-29 19:24:32.064113013 -0700
++++ tools/clang/lib/Driver/ToolChains.h	2015-08-30 12:42:03.657485673 -0700
+@@ -508,16 +508,106 @@
+                              llvm::opt::ArgStringList &CC1Args) const override;
+ };
+ 
+-class LLVM_LIBRARY_VISIBILITY Solaris : public Generic_GCC {
++class LLVM_LIBRARY_VISIBILITY Solaris : public Generic_ELF {
+ public:
+   Solaris(const Driver &D, const llvm::Triple &Triple,
+           const llvm::opt::ArgList &Args);
+ 
+-  bool IsIntegratedAssemblerDefault() const override { return true; }
++  bool IsIntegratedAssemblerDefault() const override { return !UseGnuAs; }
++
++  std::string computeSysRoot() const;
++
++  bool addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
++                                StringRef GCCTriple,
++                                StringRef GCCMultiarchTriple,
++                                StringRef TargetMultiarchTriple,
++                                Twine IncludeSuffix,
++                                const llvm::opt::ArgList &DriverArgs,
++                                llvm::opt::ArgStringList &CC1Args) const;
++
++  void addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
++                                const llvm::opt::ArgList &DriverArgs,
++                                llvm::opt::ArgStringList &CC1Args) const;
++
++  void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
++                                    llvm::opt::ArgStringList &CC1Args) const override;
++
++  void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
++                                 llvm::opt::ArgStringList &CC1Args) const override;
++
++  void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
++                             llvm::opt::ArgStringList &CC1Args) const override;
++
++  void findGCCMajorMinor() const;
++  void findGCCMajorMinorMicro(const llvm::Triple &Triple) const;
++  void findGCCIncludeDirs(const llvm::Triple &Triple,
++                          const llvm::opt::ArgList &Args) const;
++  void findGCCInternalLibDir(const llvm::Triple &Triple,
++                             const llvm::opt::ArgList &Args) const;
++  void findSpecifiedGCCToolchain(const char *StartingPath,
++                                 const llvm::Triple &Triple,
++                                 const llvm::opt::ArgList &Args) const;
++
++  StringRef getAssembler() const { return Assembler.c_str(); }
++  StringRef getLinker() const { return Linker.c_str(); }
++  StringRef getGCCInstallDir() const { return GCCInstallDir.c_str(); }
++  StringRef getGCCMajorMinor() const { return GCCMajorMinor.c_str(); }
++  StringRef getMArch() const { return march.c_str(); }
++  StringRef getMTune() const { return mtune.c_str(); }
++  StringRef getMCpu() const { return mcpu.c_str(); }
++  StringRef getGCCInternalLibDir() const { return GCCInternalLibDir; }
++
++  StringRef getGCCInternalMultiLibDir() const {
++    return GCCInternalMultiLibDir;
++  }
++
++  StringRef getGCCMajorMinorMicro() const {
++    return GCCMajorMinorMicro.c_str();
++  }
++
++  const std::vector<std::string> &getGCCIncludeDirs() const {
++    return GCCIncludeDirs;
++  }
++
++  const std::vector<std::string> &getExtraOpts() const {
++    return ExtraOpts;
++  }
++
++  bool isValid() const { return IsValid; }
++
++  void print(raw_ostream &OS) const;
++
+ protected:
+   Tool *buildAssembler() const override;
+   Tool *buildLinker() const override;
++  void validate();
++
++private:
++  bool UseGnuAs;
++  bool UseGnuLd;
++  bool UseGoldLd;
++  bool UseSunLd;
++  mutable bool UseMediatedGCCToolChainPath;
++  mutable bool UseSpecifiedGCCToolChainPath;
++  bool IsValid;
++
++protected:
++  mutable std::string GCCInstallDir;
++  mutable std::string GCCMajorMinor;
++  mutable std::string GCCMajorMinorMicro;
++  mutable std::string GCCInternalLibDir;
++  mutable std::string GCCInternalMultiLibDir;
++  mutable std::vector<std::string> GCCIncludeDirs;
++
++  mutable std::string Assembler;
++  mutable std::string Linker;
++  mutable std::string mtune;
++  mutable std::string march;
++  mutable std::string mcpu;
+ 
++  mutable std::vector<std::string> ExtraOpts;
++  static const char *MediatedGCCToolChainPath;
++  static const bool SupportsClangLibCPlusPlus;
+ };
+ 
+ 
+--- tools/clang/lib/Driver/ToolChains.cpp	2015-04-27 01:13:25.000000000 -0700
++++ tools/clang/lib/Driver/ToolChains.cpp	2015-08-30 13:11:52.217344511 -0700
+@@ -28,8 +28,10 @@
+ #include "llvm/Support/FileSystem.h"
+ #include "llvm/Support/MemoryBuffer.h"
+ #include "llvm/Support/Path.h"
++#include "llvm/Support/Host.h"
+ #include "llvm/Support/Program.h"
+ #include "llvm/Support/raw_ostream.h"
++
+ #include <cstdlib> // ::getenv
+ #include <system_error>
+ 
+@@ -38,6 +40,19 @@
+ using namespace clang;
+ using namespace llvm::opt;
+ 
++#if defined(LLVM_ON_UNIX)
++#include <cstring>
++#include <cctype>
++#include <sys/types.h>
++#include <sys/stat.h>
++#include <dirent.h>
++#include <unistd.h>
++#endif
++
++/// \brief Get our best guess at the multiarch triple for a target.
++static std::string getMultiarchTriple(const llvm::Triple &TargetTriple,
++                                      StringRef SysRoot);
++
+ MachO::MachO(const Driver &D, const llvm::Triple &Triple,
+                        const ArgList &Args)
+   : ToolChain(D, Triple, Args) {
+@@ -1214,6 +1229,11 @@
+     // If we have a SysRoot, try that first.
+     if (!D.SysRoot.empty()) {
+       Prefixes.push_back(D.SysRoot);
++
++      // Add Solaris-specific GCC locations.
++      if (TargetTriple.getOS() == llvm::Triple::Solaris)
++        Prefixes.push_back("/usr/gcc");
++
+       Prefixes.push_back(D.SysRoot + "/usr");
+     }
+ 
+@@ -1303,20 +1323,24 @@
+   static const char *const ARMebHFTriples[] = { "armeb-linux-gnueabihf",
+                                                 "armebv7hl-redhat-linux-gnueabi" };
+ 
+-  static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
++  static const char *const X86_64LibDirs[] = { "/lib64", "/lib/amd64",
++                                               "/lib/64", "/lib" };
+   static const char *const X86_64Triples[] = {
+     "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
+     "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux",
+     "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux",
+-    "x86_64-linux-android", "x86_64-unknown-linux"
++    "x86_64-linux-android", "x86_64-unknown-linux", "x86_64-pc-solaris2.11",
++    "x86_64-pc-solaris2.12", "x86_64-pc-solaris2.13"
+   };
++
+   static const char *const X32LibDirs[] = { "/libx32" };
+   static const char *const X86LibDirs[] = { "/lib32", "/lib" };
+   static const char *const X86Triples[] = {
+     "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu",
+     "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux",
+     "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux",
+-    "i686-montavista-linux", "i686-linux-android", "i586-linux-gnu"
++    "i686-montavista-linux", "i686-linux-android", "i586-linux-gnu",
++    "i386-pc-solaris2.11", "i386-pc-solaris2.12", "i386-pc-solaris2.13"
+   };
+ 
+   static const char *const MIPSLibDirs[] = { "/lib" };
+@@ -1358,10 +1382,18 @@
+ 
+   static const char *const SPARCv8LibDirs[] = { "/lib32", "/lib" };
+   static const char *const SPARCv8Triples[] = { "sparc-linux-gnu",
+-                                                "sparcv8-linux-gnu" };
+-  static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib" };
++                                                "sparcv8-linux-gnu",
++                                                "sparc-sun-solaris2.11",
++                                                "sparc-sun-solaris2.12",
++                                                "sparc-sun-solaris2.13" };
++
++  static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib/sparcv9",
++    "/lib/64", "/lib" };
+   static const char *const SPARCv9Triples[] = { "sparc64-linux-gnu",
+-                                                "sparcv9-linux-gnu" };
++                                                "sparcv9-linux-gnu",
++                                                "sparcv9-sun-solaris2.11",
++                                                "sparcv9-sun-solaris2.12",
++                                                "sparcv9-sun-solaris2.13" };
+ 
+   static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
+   static const char *const SystemZTriples[] = {
+@@ -2649,16 +2681,703 @@
+ 
+ /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
+ 
++const char *Solaris::MediatedGCCToolChainPath =
++"/path/to/mediated/gcc/toolchain";
++const bool Solaris::SupportsClangLibCPlusPlus = false;
++
+ Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
+-                 const ArgList &Args)
+-  : Generic_GCC(D, Triple, Args) {
++                 const llvm::opt::ArgList &Args)
++  : Generic_ELF(D, Triple, Args),
++  UseGnuAs(true),
++  UseGnuLd(false),
++  UseGoldLd(false),
++  UseSunLd(true),
++  UseMediatedGCCToolChainPath(false),
++  UseSpecifiedGCCToolChainPath(false),
++  IsValid(false),
++  GCCInstallDir("/usr/gcc/"),
++  GCCMajorMinor(""),
++  GCCMajorMinorMicro(""),
++  GCCInternalLibDir(""),
++  GCCInternalMultiLibDir(""),
++  GCCIncludeDirs(),
++  Assembler("/usr/gnu/bin/as"),
++  Linker("/usr/bin/ld"),
++  mtune(""),
++  march(""),
++  mcpu(""),
++  ExtraOpts() {
++    if (Arg *A = Args.getLastArg(options::OPT_gcc_toolchain)) {
++      GCCInstallDir = A->getValue();
++      if (!llvm::sys::fs::exists(GCCInstallDir))
++        D.Diag(diag::err_drv_no_such_file) << GCCInstallDir;
++      else {
++        findSpecifiedGCCToolchain(GCCInstallDir.c_str(), Triple, Args);
+ 
+-  getProgramPaths().push_back(getDriver().getInstalledDir());
++        if (!UseSpecifiedGCCToolChainPath) {
++          D.Diag(diag::err_drv_unsupported_rtlib_for_platform)
++            << GCCInstallDir << Triple.getTriple();
++        } else {
++          findGCCIncludeDirs(Triple, Args);
++          findGCCInternalLibDir(Triple, Args);
++        }
++      }
++    } else if (llvm::sys::fs::exists(Solaris::MediatedGCCToolChainPath)) {
++      GCCInstallDir = Solaris::MediatedGCCToolChainPath;
++      UseMediatedGCCToolChainPath = true;
++    } else {
++      findGCCMajorMinor();
++      findGCCMajorMinorMicro(Triple);
++      findGCCIncludeDirs(Triple, Args);
++      findGCCInternalLibDir(Triple, Args);
++    }
++
++    if (Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
++      Linker = A->getValue();
++      if (Linker == "bfd")
++        Linker = "/usr/gnu/bin/ld";
++      else if (Linker == "gold")
++        Linker = "/usr/gnu/bin/ld.gold";
++
++      if ((Linker == "/usr/gnu/bin/ld") || (Linker == "/usr/gnu/bin/ld.bfd") ||
++          (Linker == "/usr/bin/gld") || (Linker == "/usr/bin/gld.bfd")) {
++        UseGnuLd = true;
++        UseGoldLd = false;
++        UseSunLd = false;
++      } else if ((Linker == "/usr/gnu/bin/ld.gold") ||
++                 (Linker == "/usr/bin/gld.gold") ||
++                 (Linker == "/usr/bin/ld.gold")) {
++        UseGnuLd = false;
++        UseSunLd = false;
++        UseGoldLd = true;
++      }
++    }
++
++    if (Arg *A = Args.getLastArg(options::OPT_fuse_as_EQ)) {
++      Assembler = A->getValue();
++      if (Assembler == "llvm")
++        UseGnuAs = false;
++      else if ((Assembler == "/usr/gnu/bin/as") ||
++               (Assembler == "/usr/bin/gas"))
++        UseGnuAs = true;
++      else if (Assembler == "gas") {
++        Assembler = "/usr/gnu/bin/as";
++        UseGnuAs = true;
++      } else if ((Assembler == "/usr/bin/as") || (Assembler == "sun") ||
++                 (Assembler == "solaris"))
++        D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
++    }
++
++    getProgramPaths().push_back(GCCInstallDir);
+   if (getDriver().getInstalledDir() != getDriver().Dir)
+     getProgramPaths().push_back(getDriver().Dir);
+ 
++    llvm::Triple::ArchType Arch = Triple.getArch();
++
++    switch (Arch) {
++    case llvm::Triple::x86:
++      getFilePaths().push_back(getDriver().Dir + "/../lib");
++      getFilePaths().push_back("/usr/lib");
++      march = mtune = "i686";
++      break;
++    case llvm::Triple::sparc:
++      getFilePaths().push_back(getDriver().Dir + "/../lib");
++      getFilePaths().push_back("/usr/lib");
++      mcpu = "ultrasparc";
++      mtune = "ultrasparc";
++      march = "v8plusa";
++      break;
++    case llvm::Triple::x86_64:
++      getFilePaths().push_back(getDriver().Dir + "/../lib/amd64");
++      getFilePaths().push_back("/usr/lib/amd64");
++      march = mtune = "opteron";
++      break;
++    case llvm::Triple::sparcv9:
++      getFilePaths().push_back(getDriver().Dir + "/../lib/sparcv9");
++      getFilePaths().push_back("/usr/lib/sparcv9");
++      mcpu = "ultrasparc";
++      mtune = "ultrasparc";
++      march = "v9a";
++      break;
++    default:
+   getFilePaths().push_back(getDriver().Dir + "/../lib");
+   getFilePaths().push_back("/usr/lib");
++      break;
++    }
++
++    validate();
++
++    if (Args.hasArg(options::OPT_v))
++      this->print(llvm::errs());
++}
++
++std::string Solaris::computeSysRoot() const {
++  if (!getDriver().SysRoot.empty())
++    return getDriver().SysRoot;
++
++  return std::string("/");
++}
++
++bool Solaris::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
++                                       StringRef GCCTriple,
++                                       StringRef GCCMultiarchTriple,
++                                       StringRef TargetMultiarchTriple,
++                                       Twine IncludeSuffix,
++                                       const llvm::opt::ArgList &DriverArgs,
++                                       llvm::opt::ArgStringList &CC1Args) const {
++  if (!llvm::sys::fs::exists(Base + Suffix))
++        return false;
++
++  addSystemInclude(DriverArgs, CC1Args, Base);
++  addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
++
++  if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
++      llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
++    addSystemInclude(DriverArgs,
++                     CC1Args, Base + Suffix + "/" + GCCTriple + IncludeSuffix);
++  } else {
++    addSystemInclude(DriverArgs, CC1Args,
++                     Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
++    addSystemInclude(DriverArgs, CC1Args,
++                     Base + "/" + TargetMultiarchTriple + Suffix);
++  }
++
++  addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
++  addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
++  return true;
++}
++
++void Solaris::AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
++                                           llvm::opt::ArgStringList &CC1Args) const {
++  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
++      DriverArgs.hasArg(options::OPT_nostdincxx))
++    return;
++
++  const Driver &D = getDriver();
++
++  // Check for Clang libc++
++  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
++    if (!Solaris::SupportsClangLibCPlusPlus) {
++      D.Diag(diag::err_drv_invalid_stdlib_name) << "libc++";
++      return;
++    }
++
++    StringRef IncludePath = "/usr/include/libc++/v1";
++    if (!llvm::sys::fs::exists(IncludePath)) {
++      D.Diag(diag::err_drv_no_such_file) << IncludePath;
++      return;
++    }
++
++    addSystemInclude(DriverArgs, CC1Args, IncludePath);
++    return;
++  }
++
++  for (std::vector<std::string>::const_iterator B =
++      getGCCIncludeDirs().begin(), E = getGCCIncludeDirs().end();
++      B != E; ++B) {
++    llvm::Twine IncludePath((*B));
++    addSystemInclude(DriverArgs, CC1Args, IncludePath);
++  }
++}
++
++void Solaris::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
++                                        ArgStringList &CC1Args) const {
++  const Driver &D = getDriver();
++
++  if (DriverArgs.hasArg(options::OPT_nostdinc))
++    return;
++
++  std::string SysRoot = computeSysRoot();
++
++  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
++    SmallString<PATH_MAX> P(D.ResourceDir);
++    llvm::sys::path::append(P, "/include");
++    addSystemInclude(DriverArgs, CC1Args, P.str());
++  }
++
++  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
++    return;
++
++  StringRef CIncludeDirs(C_INCLUDE_DIRS);
++  if (CIncludeDirs != "") {
++    SmallVector<StringRef, 5> dirs;
++    CIncludeDirs.split(dirs, ":");
++    for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
++         I != E; ++I) {
++      StringRef Prefix =
++        llvm::sys::path::is_absolute(*I) ? StringRef(SysRoot) : "";
++      addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
++    }
++  }
++
++  addExternCSystemInclude(DriverArgs, CC1Args, "/usr/include");
++}
++
++void Solaris::addClangTargetOptions(const ArgList &DriverArgs,
++                                    ArgStringList &CC1Args) const {
++  const llvm::Triple& TT = getTriple();
++  llvm::Triple::ArchType Arch = TT.getArch();
++
++  if (Arg *A = DriverArgs.getLastArg(options::OPT_mtune_EQ)) {
++    StringRef V = A->getValue();
++    if (!V.empty())
++      mtune = V.str();
++
++    // FIXME: Impplement SPARC target features.
++    CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++    if (Arch == llvm::Triple::sparc || Arch == llvm::Triple::sparcv9) {
++      std::string S = "mtune=";
++      S += mtune;
++      CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
++    } else {
++      CC1Args.push_back(DriverArgs.MakeArgString(mtune.c_str()));
++    }
++  }
++
++  if (Arg *A = DriverArgs.getLastArg(options::OPT_march_EQ)) {
++    StringRef V = A->getValue();
++    if (!V.empty())
++      march = V.str();
++
++    CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++
++    if ((Arch == llvm::Triple::sparc) || (Arch == llvm::Triple::sparcv9)) {
++      std::string S = "march=";
++      S += mtune;
++      CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
++    } else {
++      CC1Args.push_back(DriverArgs.MakeArgString(march.c_str()));
++    }
++  }
++
++  if (Arch == llvm::Triple::sparc || Arch == llvm::Triple::sparcv9) {
++    if (Arg *A = DriverArgs.getLastArg(options::OPT_mcpu_EQ)) {
++      StringRef V = A->getValue();
++      if (!V.empty())
++        mcpu = V.str();
++      else
++        mcpu = "ultrasparc";
++    }
++
++    CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++    std::string S = "mcpu=";
++    S += mcpu;
++    CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
++
++    if (Arg *A = DriverArgs.getLastArg(options::OPT_mvis)) {
++      CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++      CC1Args.push_back(DriverArgs.MakeArgString("vis"));
++    } else if (Arg *A = DriverArgs.getLastArg(options::OPT_mvis2)) {
++      CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++      CC1Args.push_back(DriverArgs.MakeArgString("vis2"));
++    } else if (Arg *A = DriverArgs.getLastArg(options::OPT_mvis3)) {
++      CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++      CC1Args.push_back(DriverArgs.MakeArgString("vis3"));
++    }
++  }
++}
++
++void Solaris::findGCCMajorMinor() const {
++  // FIXME: Add 5.2 after testing the ABI.
++  static const char* const GCCMM[] = { "4.8", "4.9" };
++
++  const char* P;
++  std::string Path;
++
++  if (UseMediatedGCCToolChainPath) {
++    // FIXME: IMPLEMENT.
++    // Needs spec.
++  }
++
++  Path.reserve(std::string::size_type(PATH_MAX));
++
++  for (int I = (llvm::array_lengthof(GCCMM) - 1); I >= 0; --I) {
++    if ((P = GCCMM[I]) != NULL) {
++      Path = GCCInstallDir;
++      Path.append(P);
++      Path.append("/");
++
++      if (llvm::sys::fs::exists(Path.c_str())) {
++        GCCMajorMinor = P;
++        break;
++      }
++    }
++  }
++}
++
++void Solaris::findGCCMajorMinorMicro(const llvm::Triple& T) const {
++  // FIXME: Add 5.2.0 after testing the ABI.
++  static const char* const GCCMMM[] = { "4.8.2", "4.8.5", "4.9.3" };
++
++  const char* P;
++  std::string Path;
++  std::string TripleString = llvm::sys::getDefaultTargetTriple();
++  llvm::Triple::ArchType Arch = T.getArch();
++
++  if (UseMediatedGCCToolChainPath) {
++    // FIXME: IMPLEMENT.
++    // Needs spec.
++  }
++
++  Path.reserve(std::string::size_type(PATH_MAX));
++
++  for (int I = (llvm::array_lengthof(GCCMMM) - 1); I >= 0; --I) {
++    if ((P = GCCMMM[I]) != NULL) {
++      if ((P[0] == GCCMajorMinor[0]) && (P[2] == GCCMajorMinor[2])) {
++        Path = GCCInstallDir;
++        Path.append("/");
++        Path.append(GCCMajorMinor);
++        Path.append("/lib/gcc/");
++        Path.append(TripleString);
++        Path.append("/");
++        Path.append(P);
++
++        if (llvm::sys::fs::exists(Path.c_str())) {
++          std::string Test;
++          // Check if this is a real GCC installation and not just
++          // an empty directory tree
++          switch (Arch) {
++              case llvm::Triple::x86:
++              case llvm::Triple::sparc:
++                Test = Path + "/crtbegin.o";
++                break;
++              case llvm::Triple::x86_64:
++                Test = Path + "/amd64/crtbegin.o";
++                break;
++              case llvm::Triple::sparcv9:
++                Test = Path + "/sparcv9/crtbegin.o";
++                break;
++              default:
++                break;
++          }
++
++          if (llvm::sys::fs::exists(Test.c_str())) {
++            GCCMajorMinorMicro = P;
++            break;
++          }
++        }
++      }
++    }
++  }
++}
++
++void Solaris::findSpecifiedGCCToolchain(const char *StartingPath,
++                                        const llvm::Triple &Triple,
++                                        const llvm::opt::ArgList &Args) const {
++  DIR *TopLD = 0;
++  DIR *LibLD = 0;
++  DIR *GccLD = 0;
++  DIR *TripleLD = 0;
++  struct dirent *TopDE = 0;
++  struct dirent *LibDE = 0;
++  struct dirent *GccDE = 0;
++  struct dirent *TripleDE = 0;
++  std::string LibDir;
++  std::string GccDir;
++  std::string TripleDir;
++  std::string TripleVersionDir;
++  const char *DName;
++
++  assert(StartingPath && "Invalid GCC Toolchain starting search path!");
++
++  GCCMajorMinor = "";
++  GCCMajorMinorMicro = "";
++  UseSpecifiedGCCToolChainPath = false;
++
++  LibDir.reserve(std::string::size_type(PATH_MAX));
++  GccDir.reserve(std::string::size_type(PATH_MAX));
++  TripleDir.reserve(std::string::size_type(PATH_MAX));
++  TripleVersionDir.reserve(std::string::size_type(PATH_MAX));
++
++  if (llvm::sys::fs::exists(StartingPath) &&
++      llvm::sys::fs::is_directory(StartingPath)) {
++    TopLD = opendir(StartingPath);
++    assert(TopLD && "Cannot obtain a valid toplevel DIR handle!");
++
++    while ((TopDE = readdir(TopLD)) != NULL) {
++      if (TopDE->d_name[0] == '.')
++        continue;
++
++      DName = reinterpret_cast<const char*>(&TopDE->d_name[0]);
++      if (std::strcmp(DName, "lib") == 0) {
++        LibDir = StartingPath;
++        LibDir.append("/");
++        LibDir.append(DName);
++
++        if (!llvm::sys::fs::is_directory(LibDir.c_str()))
++          continue;
++
++        LibLD = opendir(LibDir.c_str());
++        assert(LibLD && "Could not obtain a valid lib DIR handle!");
++
++        while ((LibDE = readdir(LibLD)) != NULL) {
++          if (LibDE->d_name[0] == '.')
++            continue;
++
++          DName = reinterpret_cast<const char*>(&LibDE->d_name[0]);
++          if (std::strcmp(DName, "gcc") == 0) {
++            GccDir = LibDir;
++            GccDir.append("/");
++            GccDir.append(DName);
++
++            if (!llvm::sys::fs::is_directory(GccDir.c_str()))
++              continue;
++
++            GccLD = opendir(GccDir.c_str());
++            assert(GccLD && "Could not obtain a valid gcc DIR handle!");
++
++            while ((GccDE = readdir(GccLD)) != NULL) {
++              if (GccDE->d_name[0] == '.')
++                continue;
++
++              DName = reinterpret_cast<const char*>(&GccDE->d_name[0]);
++              TripleDir = GccDir;
++              TripleDir.append("/");
++              TripleDir.append(DName);
++
++              if (!llvm::sys::fs::is_directory(TripleDir.c_str()))
++                continue;
++
++              if ((std::strncmp(DName, "sparc", 5) == 0) ||
++                  (std::strncmp(DName, "i386", 4) == 0) ||
++                  (std::strncmp(DName, "sparcv9", 7) == 0) ||
++                  (std::strncmp(DName, "x86_64", 6) == 0)) {
++                TripleLD = opendir(TripleDir.c_str());
++                assert(TripleLD &&
++                       "Could not obtain a valid Triple DIR handle!");
++
++                while ((TripleDE = readdir(TripleLD)) != NULL) {
++                  if (TripleDE->d_name[0] == '.')
++                    continue;
++
++                  DName = reinterpret_cast<const char*>(&TripleDE->d_name[0]);
++                  TripleVersionDir = TripleDir;
++                  TripleVersionDir.append("/");
++                  TripleVersionDir.append(DName);
++
++                  if (!llvm::sys::fs::is_directory(TripleVersionDir.c_str()))
++                    continue;
++
++                  if ((std::isdigit(DName[0])) && (DName[1] == '.') &&
++                      (std::isdigit(DName[2])) && (DName[3] == '.') &&
++                      (std::isdigit(DName[4])) && (DName[5] == '\0')) {
++                    GCCMajorMinorMicro = DName;
++                    GCCMajorMinor = GCCMajorMinorMicro.substr(0, 3);
++                    UseSpecifiedGCCToolChainPath = true;
++                    goto done;
++                  }
++                }
++              }
++            }
++          }
++        }
++      }
++    }
++  }
++
++done:
++  if (TripleLD) {
++    rewinddir(TripleLD);
++    closedir(TripleLD);
++  }
++
++  if (GccLD) {
++    rewinddir(GccLD);
++    closedir(GccLD);
++  }
++
++  if (LibLD) {
++    rewinddir(LibLD);
++    closedir(LibLD);
++  }
++
++  if (TopLD) {
++    rewinddir(TopLD);
++    closedir(TopLD);
++  }
++}
++
++
++
++void Solaris::findGCCIncludeDirs(const llvm::Triple &Triple,
++                                 const llvm::opt::ArgList &Args) const {
++  std::string GCCInstallPath;
++  if (UseSpecifiedGCCToolChainPath)
++    GCCInstallPath = GCCInstallDir;
++  else if (UseMediatedGCCToolChainPath)
++    GCCInstallPath = Solaris::MediatedGCCToolChainPath;
++  else
++    GCCInstallPath = GCCInstallDir + GCCMajorMinor;
++
++  std::string GCCIncludeDir =
++    GCCInstallPath + "/include/c++/" + GCCMajorMinorMicro;
++  GCCIncludeDirs.push_back(GCCIncludeDir);
++
++  llvm::Triple::ArchType Arch = Triple.getArch();
++  GCCIncludeDir += "/";
++
++  switch (Arch) {
++    case llvm::Triple::x86:
++      GCCIncludeDir += Triple.getTriple();
++      if (Arg *A = Args.getLastArg(options::OPT_m64))
++        GCCIncludeDir += "/amd64";
++      break;
++    case llvm::Triple::sparc:
++      GCCIncludeDir += Triple.getTriple();
++      if (Arg *A = Args.getLastArg(options::OPT_m64))
++        GCCIncludeDir += "/sparcv9";
++      break;
++    case llvm::Triple::x86_64:
++      GCCIncludeDir += "i386-pc-";
++      GCCIncludeDir += Triple.getOSName();
++      if (Arg *A = Args.getLastArg(options::OPT_m64))
++        GCCIncludeDir += "/amd64";
++      break;
++    case llvm::Triple::sparcv9:
++      GCCIncludeDir += "sparc-sun-";
++      GCCIncludeDir += Triple.getOSName();
++      if (Arg *A = Args.getLastArg(options::OPT_m64))
++        GCCIncludeDir += "/sparcv9";
++      break;
++    default:
++      getDriver().Diag(diag::err_target_unsupported_arch)
++        << Triple.getArchName() << Triple.getTriple();
++      break;
++  }
++
++  GCCIncludeDirs.push_back(GCCIncludeDir);
++
++  GCCIncludeDir = GCCInstallPath + "/include/c++/" +
++    GCCMajorMinorMicro + "/backward";
++
++  GCCIncludeDirs.push_back(GCCIncludeDir);
++}
++
++void Solaris::findGCCInternalLibDir(const llvm::Triple &Triple,
++                                    const llvm::opt::ArgList &Args) const {
++  std::string GCCInstallPath;
++  if (UseSpecifiedGCCToolChainPath)
++    GCCInstallPath = GCCInstallDir;
++  else if (UseMediatedGCCToolChainPath)
++    GCCInstallPath = Solaris::MediatedGCCToolChainPath;
++  else
++    GCCInstallPath = GCCInstallDir + GCCMajorMinor;
++
++  GCCInternalLibDir = GCCInstallPath + "/lib/gcc/";
++
++  llvm::Triple::ArchType Arch = Triple.getArch();
++
++  switch (Arch) {
++    case llvm::Triple::x86:
++      GCCInternalLibDir += Triple.getTriple();
++      GCCInternalLibDir += "/";
++      GCCInternalLibDir += GCCMajorMinorMicro;
++      if (Arg *A = Args.getLastArg(options::OPT_m64)) {
++        GCCInternalMultiLibDir = GCCInternalLibDir;
++        GCCInternalLibDir += "/amd64";
++      } else if (Arg *A = Args.getLastArg(options::OPT_m32)) {
++        GCCInternalMultiLibDir = GCCInternalLibDir;
++        GCCInternalMultiLibDir += "/amd64";
++      } else {
++        GCCInternalMultiLibDir = GCCInternalLibDir;
++        GCCInternalMultiLibDir += "/amd64";
++      }
++
++      break;
++    case llvm::Triple::sparc:
++      GCCInternalLibDir += Triple.getTriple();
++      GCCInternalLibDir += "/";
++      GCCInternalLibDir += GCCMajorMinorMicro;
++      if (Arg *A = Args.getLastArg(options::OPT_m64)) {
++        GCCInternalMultiLibDir = GCCInternalLibDir;
++        GCCInternalLibDir += "/sparcv9";
++      } else if (Arg *A = Args.getLastArg(options::OPT_m32)) {
++        GCCInternalMultiLibDir = GCCInternalLibDir;
++        GCCInternalMultiLibDir += "/sparcv9";
++      } else {
++        GCCInternalMultiLibDir = GCCInternalLibDir;
++        GCCInternalMultiLibDir += "/sparcv9";
++      }
++      break;
++    case llvm::Triple::x86_64:
++      GCCInternalLibDir += "i386-pc-";
++      GCCInternalLibDir += Triple.getOSName();
++      GCCInternalLibDir += "/";
++      GCCInternalLibDir += GCCMajorMinorMicro;
++      GCCInternalMultiLibDir = GCCInternalLibDir;
++      if (Arg *A = Args.getLastArg(options::OPT_m64))
++        GCCInternalLibDir += "/amd64";
++      else if (Arg *A = Args.getLastArg(options::OPT_m32))
++        GCCInternalMultiLibDir += "/amd64";
++      else
++        GCCInternalLibDir += "/amd64";
++      break;
++    case llvm::Triple::sparcv9:
++      GCCInternalLibDir += "sparc-sun-";
++      GCCInternalLibDir += Triple.getOSName();
++      GCCInternalLibDir += "/";
++      GCCInternalLibDir += GCCMajorMinorMicro;
++      GCCInternalMultiLibDir = GCCInternalLibDir;
++      if (Arg *A = Args.getLastArg(options::OPT_m64))
++        GCCInternalLibDir += "/sparcv9";
++      else if (Arg *A = Args.getLastArg(options::OPT_m32))
++        GCCInternalMultiLibDir += "/sparcv9";
++      else
++        GCCInternalLibDir += "/sparcv9";
++      break;
++    default:
++      getDriver().Diag(diag::err_target_unsupported_arch)
++        << Triple.getArchName() << Triple.getTriple();
++      break;
++  }
++}
++
++void Solaris::print(raw_ostream &OS) const {
++  OS << "UseGnuAs: " << (UseGnuAs ? "true" : "false") << "\n";
++  OS << "UseGnuLd: " << (UseGnuLd ? "true" : "false") << "\n";
++  OS << "UseGoldLd: " << (UseGoldLd ? "true" : "false") << "\n";
++  OS << "UseSunLd: " << (UseSunLd ? "true" : "false") << "\n";
++  OS << "UseMediatedGCCToolChainPath: "
++    << (UseMediatedGCCToolChainPath ? "true" : "false") << "\n";
++  OS << "UseSpecifiedGCCToolChainPath: "
++    << (UseSpecifiedGCCToolChainPath ? "true" : "false") << "\n";
++  OS << "GCCInstallDir: " << GCCInstallDir.c_str() << "\n";
++  OS << "GCCMajorMinor: " << GCCMajorMinor.c_str() << "\n";
++  OS << "GCCMajorMinorMicro: " << GCCMajorMinorMicro.c_str() << "\n";
++  OS << "GCCInternalLibDir: " << GCCInternalLibDir.c_str() << "\n";
++  OS << "GCCInternalMultiLibDir: " << GCCInternalMultiLibDir.c_str() << "\n";
++  OS << "MediatedGCCToolChainPath: " << MediatedGCCToolChainPath << "\n";
++  OS << "GCCIncludeDirs: ";
++
++  if (GCCIncludeDirs.size()) {
++    std::string IncludePath;
++    for (std::vector<std::string>::const_iterator B = GCCIncludeDirs.begin(),
++        E = GCCIncludeDirs.end(); B != E; ++B) {
++      IncludePath = "-I";
++      IncludePath += (*B);
++      OS << IncludePath.c_str() << " ";
++    }
++
++    OS << "\n";
++  }
++
++  OS << "Assembler: " << Assembler.c_str() << "\n";
++  OS << "Linker: " << Linker.c_str() << "\n";
++  OS << "mtune: " << mtune.c_str() << "\n";
++  OS << "march: " << march.c_str() << "\n";
++  OS << "mcpu: " << mcpu.c_str() << "\n";
++
++  if (ExtraOpts.size()) {
++    OS << "ExtraOpts: ";
++    for (std::vector<std::string>::const_iterator B = ExtraOpts.begin(),
++        E = ExtraOpts.end(); B != E; ++B) {
++      OS << (*B).c_str() << " ";
++    }
++
++    OS << "\n";
++  }
++
++  OS << "Valid: " << (IsValid ? "true" : "false") << "\n";
+ }
+ 
+ Tool *Solaris::buildAssembler() const {
+@@ -2669,6 +3388,21 @@
+   return new tools::solaris::Link(*this);
+ }
+ 
++void Solaris::validate() {
++  IsValid = llvm::sys::fs::exists(GCCInstallDir.c_str());
++  if (!IsValid) return;
++  IsValid = llvm::sys::fs::exists(GCCInternalLibDir.c_str());
++  if (!IsValid) return;
++  IsValid = llvm::sys::fs::exists(GCCInternalMultiLibDir.c_str());
++  if (!IsValid) return;
++
++  for (std::vector<std::string>::const_iterator B = GCCIncludeDirs.begin(),
++      E = GCCIncludeDirs.end(); B != E; ++B) {
++    IsValid = llvm::sys::fs::exists((*B).c_str());
++    if (!IsValid) return;
++  }
++}
++
+ /// Distribution (very bare-bones at the moment).
+ 
+ enum Distro {
+@@ -2696,6 +3430,27 @@
+   UbuntuRaring,
+   UbuntuSaucy,
+   UbuntuTrusty,
++  Solaris_11,
++  Solaris_11_1,
++  Solaris_11_2,
++  Solaris_11_3,
++  Solaris_11_4,
++  Solaris_11_5,
++  Solaris_11_6,
++  Solaris_11_7,
++  Solaris_11_8,
++  Solaris_11_9,
++  Solaris_12,
++  Solaris_12_1,
++  Solaris_12_2,
++  Solaris_12_3,
++  Solaris_12_4,
++  Solaris_12_5,
++  Solaris_12_6,
++  Solaris_12_7,
++  Solaris_12_8,
++  Solaris_12_9,
++  Solaris_13,
+   UnknownDistro
+ };
+ 
+@@ -2715,6 +3470,10 @@
+   return Distro >= UbuntuHardy && Distro <= UbuntuTrusty;
+ }
+ 
++static bool IsSolaris(enum Distro Distro) {
++  return Distro >= Solaris_11 && Distro <= Solaris_13;
++}
++
+ static Distro DetectDistro(llvm::Triple::ArchType Arch) {
+   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
+       llvm::MemoryBuffer::getFile("/etc/lsb-release");
+@@ -2774,6 +3533,59 @@
+     return UnknownDistro;
+   }
+ 
++  File = llvm::MemoryBuffer::getFile("/etc/release");
++  if (File) {
++    StringRef Data = File.get()->getBuffer();
++    SmallVector<StringRef, 8> Lines;
++    Data.split(Lines, "\n");
++    for (unsigned I = 0, S = Lines.size(); I != S; ++I) {
++      if (Lines[I].find("Oracle Solaris") != std::string::npos) {
++        if (Lines[I].find("Solaris 11.0") != std::string::npos)
++          return Solaris_11;
++        else if (Lines[I].find("Solaris 11.1") != std::string::npos)
++          return Solaris_11_1;
++        else if (Lines[I].find("Solaris 11.2") != std::string::npos)
++          return Solaris_11_2;
++        else if (Lines[I].find("Solaris 11.3") != std::string::npos)
++          return Solaris_11_3;
++        else if (Lines[I].find("Solaris 11.4") != std::string::npos)
++          return Solaris_11_4;
++        else if (Lines[I].find("Solaris 11.5") != std::string::npos)
++          return Solaris_11_5;
++        else if (Lines[I].find("Solaris 11.6") != std::string::npos)
++          return Solaris_11_6;
++        else if (Lines[I].find("Solaris 11.7") != std::string::npos)
++          return Solaris_11_7;
++        else if (Lines[I].find("Solaris 11.8") != std::string::npos)
++          return Solaris_11_8;
++        else if (Lines[I].find("Solaris 11.9") != std::string::npos)
++          return Solaris_11_9;
++        else if (Lines[I].find("Solaris 12.0") != std::string::npos)
++          return Solaris_12;
++        else if (Lines[I].find("Solaris 12.1") != std::string::npos)
++          return Solaris_12_1;
++        else if (Lines[I].find("Solaris 12.2") != std::string::npos)
++          return Solaris_12_2;
++        else if (Lines[I].find("Solaris 12.3") != std::string::npos)
++          return Solaris_12_3;
++        else if (Lines[I].find("Solaris 12.4") != std::string::npos)
++          return Solaris_12_4;
++        else if (Lines[I].find("Solaris 12.5") != std::string::npos)
++          return Solaris_12_5;
++        else if (Lines[I].find("Solaris 12.6") != std::string::npos)
++          return Solaris_12_6;
++        else if (Lines[I].find("Solaris 12.7") != std::string::npos)
++          return Solaris_12_7;
++        else if (Lines[I].find("Solaris 12.8") != std::string::npos)
++          return Solaris_12_8;
++        else if (Lines[I].find("Solaris 12.9") != std::string::npos)
++          return Solaris_12_9;
++      }
++    }
++
++    return UnknownDistro;
++  }
++
+   if (llvm::sys::fs::exists("/etc/SuSE-release"))
+     return OpenSUSE;
+ 
+--- tools/llvm-shlib/Makefile	Sat Jul 18 11:44:45 2015
++++ tools/llvm-shlib/Makefile	Thu Aug 20 23:40:28 2015
+@@ -74,6 +74,7 @@
+     LLVMLibsOptions := -Wl,-z -Wl,rescan -Wl,-z -Wl,allextract $(LLVMLibsOptions)
+     LLVMLibsOptions += -Wl,-h -Wl,lib$(LIBRARYNAME)$(SHLIBEXT)
+     LLVMLibsOptions += -Wl,-z -Wl,defaultextract -Wl,-z -Wl,defs
++    LLVMLibsOptions += -lkstat
+ endif
+ 
+ ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+--- tools/clang/lib/Basic/Targets.cpp	2015-08-26 11:44:48.659904739 -0700
++++ tools/clang/lib/Basic/Targets.cpp	2015-08-26 11:47:36.318310023 -0700
+@@ -530,28 +530,60 @@
+ template<typename Target>
+ class SolarisTargetInfo : public OSTargetInfo<Target> {
+ protected:
+-  void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
++  virtual void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
+                     MacroBuilder &Builder) const override {
+     DefineStd(Builder, "sun", Opts);
+     DefineStd(Builder, "unix", Opts);
+     Builder.defineMacro("__ELF__");
+     Builder.defineMacro("__svr4__");
+     Builder.defineMacro("__SVR4");
+-    // Solaris headers require _XOPEN_SOURCE to be set to 600 for C99 and
+-    // newer, but to 500 for everything else.  feature_test.h has a check to
+-    // ensure that you are not using C99 with an old version of X/Open or C89
+-    // with a new version.
+-    if (Opts.C99)
++
++    if (Opts.C99 || Opts.CPlusPlus11) {
++      if (Opts.C99) {
+       Builder.defineMacro("_XOPEN_SOURCE", "600");
+-    else
++        Builder.defineMacro("_XPG6", "1");
++      }
++
++      Builder.defineMacro("__STDC_VERSION__", "199901L");
++      Builder.defineMacro("_STDC_C99", "1");
++      Builder.defineMacro("__C99FEATURES__", "1");
++    }
++
++    if (Opts.CPlusPlus11)
++      Builder.defineMacro("__cplusplus", "201103L");
++    else if (Opts.CPlusPlus14)
++      Builder.defineMacro("__cplusplus", "201402L");
++
++    if (Opts.CPlusPlus11) {
++      Builder.defineMacro("_STDC_C11", "1");
++      Builder.defineMacro("_STDC_C11_BCI", "1");
++      Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
++      Builder.defineMacro("_XPG7", "1");
++      Builder.defineMacro("_XOPEN_SOURCE", "700");
++    } else if (Opts.C11 || Opts.CPlusPlus14) {
++      Builder.defineMacro("__STDC_VERSION__", "201112L");
++      Builder.defineMacro("_STDC_C11", "1");
++      Builder.defineMacro("_STDC_C11_BCI", "1");
++      Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
++      Builder.defineMacro("_XPG7", "1");
++      Builder.defineMacro("_XOPEN_SOURCE", "700");
++    } else {
+       Builder.defineMacro("_XOPEN_SOURCE", "500");
+-    if (Opts.CPlusPlus)
+-      Builder.defineMacro("__C99FEATURES__");
++      Builder.defineMacro("__STDC_VERSION__", "199409L");
++      if (Opts.CPlusPlus && !Opts.CPlusPlus11 && !Opts.CPlusPlus14)
++        Builder.defineMacro("__cplusplus", "199711L");
++    }
++
++    if ((Triple.getArchName() == "i386") || (Triple.getArchName() == "sparc"))
+     Builder.defineMacro("_LARGEFILE_SOURCE");
++    else if ((Triple.getArchName() == "x86_64") ||
++             (Triple.getArchName() == "sparcv9"))
+     Builder.defineMacro("_LARGEFILE64_SOURCE");
+-    Builder.defineMacro("__EXTENSIONS__");
++
++    Builder.defineMacro("__EXTENSIONS__", "1");
+     Builder.defineMacro("_REENTRANT");
+   }
++
+ public:
+   SolarisTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
+     this->UserLabelPrefix = "";
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/015-llvm-clang-memory-corruption.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,782 @@
+# Memory corruption in LLVM.
+# https://llvm.org/bugs/show_bug.cgi?id=24607
+--- include/llvm/ADT/DenseMap.h	2014-12-06 14:22:44.000000000 -0500
++++ include/llvm/ADT/DenseMap.h	2015-08-25 21:45:36.712994054 -0400
+@@ -254,7 +254,7 @@
+   DenseMapBase() {}
+ 
+   void destroyAll() {
+-    if (getNumBuckets() == 0) // Nothing to do.
++    if ((getNumBuckets() == 0) || empty()) // Nothing to do.
+       return;
+ 
+     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
+--- include/llvm/IR/Attributes.h	2014-09-03 19:38:05.000000000 -0400
++++ include/llvm/IR/Attributes.h	2015-08-25 11:24:38.160033797 -0400
+@@ -406,18 +406,27 @@
+   uint64_t Alignment;
+   uint64_t StackAlignment;
+   uint64_t DerefBytes;
++
+ public:
+-  AttrBuilder() : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {}
++  AttrBuilder() : Attrs(0), TargetDepAttrs(), Alignment(0),
++  StackAlignment(0), DerefBytes(0) {}
++
+   explicit AttrBuilder(uint64_t Val)
+-    : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {
++    : Attrs(0), TargetDepAttrs(), Alignment(0),
++    StackAlignment(0), DerefBytes(0) {
+     addRawValue(Val);
+   }
++
+   AttrBuilder(const Attribute &A)
+-    : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {
++    : Attrs(0), TargetDepAttrs(), Alignment(0), StackAlignment(0),
++    DerefBytes (0) {
+     addAttribute(A);
+   }
++
+   AttrBuilder(AttributeSet AS, unsigned Idx);
+ 
++  ~AttrBuilder() { }
++
+   void clear();
+ 
+   /// \brief Add an attribute to the builder.
+--- include/llvm/IR/Metadata.h	2015-02-08 19:35:35.000000000 -0800
++++ include/llvm/IR/Metadata.h	2015-08-26 21:27:54.937575563 -0700
+@@ -24,6 +24,7 @@
+ #include "llvm/IR/MetadataTracking.h"
+ #include "llvm/IR/Value.h"
+ #include "llvm/Support/ErrorHandling.h"
++#include "llvm/Support/raw_ostream.h"
+ #include <type_traits>
+ 
+ namespace llvm {
+@@ -42,13 +43,15 @@
+ /// This is a root class for typeless data in the IR.
+ class Metadata {
+   friend class ReplaceableMetadataImpl;
++  friend class MDNode;
+ 
+   /// \brief RTTI.
+   const unsigned char SubclassID;
+ 
+ protected:
+   /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
+-  bool IsDistinctInContext : 1;
++  bool IsDistinctInContext;
++
+   // TODO: expose remaining bits to subclasses.
+ 
+   unsigned short SubclassData16;
+@@ -149,7 +152,7 @@
+   SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
+ 
+ public:
+-  ReplaceableMetadataImpl() : NextIndex(0) {}
++  ReplaceableMetadataImpl() : NextIndex(0), UseMap() {}
+   ~ReplaceableMetadataImpl() {
+     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
+   }
+@@ -583,9 +586,11 @@
+ //===----------------------------------------------------------------------===//
+ /// \brief Tuple of metadata.
+ class MDNode : public Metadata {
++  friend class MDNodeFwdDecl;
++  friend class MDTuple;
++
+   MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
+   void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
+-  void *operator new(size_t) LLVM_DELETED_FUNCTION;
+ 
+   LLVMContext &Context;
+   unsigned NumOperands;
+@@ -593,17 +598,21 @@
+ protected:
+   unsigned MDNodeSubclassData;
+ 
+-  void *operator new(size_t Size, unsigned NumOps);
+-  void operator delete(void *Mem);
++  static void *operator new(size_t Size, unsigned NumOps) throw();
++  static void operator delete(void *Mem) throw();
+ 
+   /// \brief Required by std, but never called.
+-  void operator delete(void *, unsigned) {
+-    llvm_unreachable("Constructor throws?");
++  static void operator delete(void *, unsigned) {
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": This should never be called!\n";
++    abort();
+   }
+ 
+   /// \brief Required by std, but never called.
+-  void operator delete(void *, unsigned, bool) {
+-    llvm_unreachable("Constructor throws?");
++  static void operator delete(void *, unsigned, bool) {
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": This should never be called!\n";
++    abort();
+   }
+ 
+   MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs);
+@@ -715,6 +724,8 @@
+ class UniquableMDNode : public MDNode {
+   friend class ReplaceableMetadataImpl;
+   friend class MDNode;
++  friend class MDTuple;
++  friend class MDLocation;
+   friend class LLVMContextImpl;
+ 
+   /// \brief Support RAUW as long as one of its arguments is replaceable.
+@@ -796,10 +807,14 @@
+   static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
+     return getImpl(Context, MDs, /* ShouldCreate */ true);
+   }
++
+   static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
+     return getImpl(Context, MDs, /* ShouldCreate */ false);
+   }
+ 
++  void *operator new(size_t Size, unsigned NumOps) throw();
++  void operator delete(void *Mem) throw();
++
+   /// \brief Return a distinct node.
+   ///
+   /// Return a distinct node -- i.e., a node that is not uniqued.
+@@ -847,6 +862,9 @@
+   void replaceOperandWith(unsigned I, Metadata *New) LLVM_DELETED_FUNCTION;
+ 
+ public:
++  void *operator new(size_t Size, unsigned NumOps) throw();
++  void operator delete(void* Mem) throw();
++
+   static MDLocation *get(LLVMContext &Context, unsigned Line, unsigned Column,
+                          Metadata *Scope, Metadata *InlinedAt = nullptr) {
+     return getImpl(Context, Line, Column, Scope, InlinedAt,
+@@ -885,18 +903,18 @@
+ /// Forward declaration of metadata, in the form of a basic tuple.  Unlike \a
+ /// MDTuple, this class has full support for RAUW, is not owned, is not
+ /// uniqued, and is suitable for forward references.
+-class MDNodeFwdDecl : public MDNode, ReplaceableMetadataImpl {
++class MDNodeFwdDecl : public MDNode, public ReplaceableMetadataImpl {
+   friend class Metadata;
+   friend class ReplaceableMetadataImpl;
+ 
+   MDNodeFwdDecl(LLVMContext &C, ArrayRef<Metadata *> Vals)
+-      : MDNode(C, MDNodeFwdDeclKind, Vals) {}
++  : MDNode(C, MDNodeFwdDeclKind, Vals), ReplaceableMetadataImpl() {}
+ 
+ public:
+   ~MDNodeFwdDecl() { dropAllReferences(); }
+ 
+-  // MSVC doesn't see the alternative: "using MDNode::operator delete".
+-  void operator delete(void *Mem) { MDNode::operator delete(Mem); }
++  void *operator new(size_t Size, unsigned NumOps) throw();
++  void operator delete(void *Mem) throw();
+ 
+   static MDNodeFwdDecl *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
+     return new (MDs.size()) MDNodeFwdDecl(Context, MDs);
+--- lib/IR/Attributes.cpp	2014-09-03 19:38:05.000000000 -0400
++++ lib/IR/Attributes.cpp	2015-08-26 00:21:40.551873740 -0400
+@@ -1004,7 +1004,8 @@
+ //===----------------------------------------------------------------------===//
+ 
+ AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Index)
+-  : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {
++  : Attrs(0), TargetDepAttrs(), Alignment(0),
++  StackAlignment(0), DerefBytes(0) {
+   AttributeSetImpl *pImpl = AS.pImpl;
+   if (!pImpl) return;
+ 
+@@ -1052,7 +1053,9 @@
+ }
+ 
+ AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
+-  TargetDepAttrs[A] = V;
++  std::string AS = A.str();
++  std::string VS = V.str();
++  TargetDepAttrs[AS] = VS;
+   return *this;
+ }
+ 
+@@ -1094,8 +1097,9 @@
+         DerefBytes = 0;
+     } else {
+       assert(Attr.isStringAttribute() && "Invalid attribute type!");
+-      std::map<std::string, std::string>::iterator
+-        Iter = TargetDepAttrs.find(Attr.getKindAsString());
++      std::string AS = Attr.getKindAsString().str();
++      std::map<std::string, std::string>::iterator Iter =
++        TargetDepAttrs.find(AS);
+       if (Iter != TargetDepAttrs.end())
+         TargetDepAttrs.erase(Iter);
+     }
+@@ -1105,7 +1109,8 @@
+ }
+ 
+ AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
+-  std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A);
++  std::map<std::string, std::string>::iterator I =
++    TargetDepAttrs.find(A.str());
+   if (I != TargetDepAttrs.end())
+     TargetDepAttrs.erase(I);
+   return *this;
+@@ -1163,7 +1168,7 @@
+ }
+ 
+ bool AttrBuilder::contains(StringRef A) const {
+-  return TargetDepAttrs.find(A) != TargetDepAttrs.end();
++  return TargetDepAttrs.find(A.str()) != TargetDepAttrs.end();
+ }
+ 
+ bool AttrBuilder::hasAttributes() const {
+@@ -1188,7 +1193,8 @@
+         return true;
+     } else {
+       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
+-      return TargetDepAttrs.find(Attr.getKindAsString())!=TargetDepAttrs.end();
++      std::string AS = Attr.getKindAsString().str();
++      return TargetDepAttrs.find(AS) != TargetDepAttrs.end();
+     }
+   }
+ 
+--- lib/IR/Metadata.cpp	2015-02-08 19:35:35.000000000 -0800
++++ lib/IR/Metadata.cpp	2015-08-28 23:18:08.062765258 -0700
+@@ -379,24 +379,84 @@
+ // MDNode implementation.
+ //
+ 
+-void *MDNode::operator new(size_t Size, unsigned NumOps) {
+-  void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
+-  MDOperand *O = static_cast<MDOperand *>(Ptr);
+-  for (MDOperand *E = O + NumOps; O != E; ++O)
+-    (void)new (O) MDOperand;
+-  return O;
+-}
++void *MDNode::operator new(size_t Size, unsigned NumOps) throw() {
++  assert((Size >= sizeof(MDNode)) && "Insufficient size to operator new!");
++
++  // MDNode wants to construct its ancillary MDOperands ** BEFORE **
++  // itself. 
++  //
++  // Allocate extra space for an uintptr_t at the beginning of the
++  // buffer.  This uintptr_t is where we will store the address of
++  // the memory-aligned storage buffer. It will be plasced immediately
++  // after the last MDOperand.
++  // This address will be computed by the matching operator delete.
++  // The total amount of space allocated must include the Size
++  // parameter passed in. This parameter value is not necessarily
++  // equal to sizeof(MDTuple), it can be greater.
++  std::size_t OSize = NumOps * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++
++  std::size_t RSize = Size + OSize + sizeof(Metadata) + sizeof(uintptr_t);
++  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
++  std::size_t Alignment = llvm::alignOf<uint64_t>();
++
++  void *P;
++
++#if defined(_MSC_VER)
++  P = _aligned_malloc(RSize, Alignment);
++  assert(P && "_aligned_malloc failed!");
++  if (!P) return 0;
++#else
++  int R = posix_memalign(&P, Alignment, RSize);
++  assert((R == 0) && "posix_memalign failed!");
++  if (R != 0) return 0;
++#endif
++
++  (void) std::memset(P, 0, RSize);
++  unsigned char *UC = static_cast<unsigned char*>(P);
++  MDNode *MN = reinterpret_cast<MDNode*>((UC + RSize) - Size);
++
++  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
++  MDOperand *MO;
++
++  for (MDOperand *E = O - NumOps; O != E; --O) {
++    MO = new (O - 1) MDOperand();
++    assert(MO && "MDOperand placement new failed!");
++  }
++
++  // We store the address of the aligned allocated buffer
++  // in the last extra element of the buffer. This address
++  // will be used by the corresponding operator delete to
++  // free the correct address.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++  *U = reinterpret_cast<uintptr_t>(P);
++  return MN;
++}
++
++void MDNode::operator delete(void *Mem) throw() {
++  MDNode *MN = reinterpret_cast<MDNode *>(Mem);
++  Metadata *MTD = static_cast<Metadata*>(MN);
++  std::size_t OSize = MN->NumOperands * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
+ 
+-void MDNode::operator delete(void *Mem) {
+-  MDNode *N = static_cast<MDNode *>(Mem);
+   MDOperand *O = static_cast<MDOperand *>(Mem);
+-  for (MDOperand *E = O - N->NumOperands; O != E; --O)
+-    (O - 1)->~MDOperand();
+-  ::operator delete(O);
++
++  for (MDOperand *E = O - MN->NumOperands; O != E; --O) {
++    MDOperand *MO = (O - 1);
++    MO->~MDOperand();
+ }
+ 
+-MDNode::MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs)
+-    : Metadata(ID), Context(Context), NumOperands(MDs.size()),
++  MTD->~Metadata();
++  MN->~MDNode();
++
++  // This is the address of the allocated buffer in the
++  // extra buffer space allocated by operator new.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++  std::free(reinterpret_cast<void*>(*U));
++}
++
++MDNode::MDNode(LLVMContext &Ctx, unsigned ID, ArrayRef<Metadata *> MDs)
++  : Metadata(ID), Context(Ctx), NumOperands(MDs.size()),
+       MDNodeSubclassData(0) {
+   for (unsigned I = 0, E = MDs.size(); I != E; ++I)
+     setOperand(I, MDs[I]);
+@@ -416,7 +476,7 @@
+ 
+ UniquableMDNode::UniquableMDNode(LLVMContext &C, unsigned ID,
+                                  ArrayRef<Metadata *> Vals, bool AllowRAUW)
+-    : MDNode(C, ID, Vals) {
++  : MDNode(C, ID, Vals), ReplaceableUses() {
+   if (!AllowRAUW)
+     return;
+ 
+@@ -428,7 +488,7 @@
+   if (!NumUnresolved)
+     return;
+ 
+-  ReplaceableUses.reset(new ReplaceableMetadataImpl);
++  ReplaceableUses.reset(new ReplaceableMetadataImpl());
+   SubclassData32 = NumUnresolved;
+ }
+ 
+@@ -577,6 +637,9 @@
+     llvm_unreachable("Invalid subclass of UniquableMDNode");
+ #define HANDLE_UNIQUABLE_LEAF(CLASS)                                           \
+   case CLASS##Kind:                                                            \
++    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
++        llvm::AlignOf<CLASS>::Alignment,                            \
++        "Insufficient alignment for objects prepended to " #CLASS); \
+     delete cast<CLASS>(this);                                                  \
+     break;
+ #include "llvm/IR/Metadata.def"
+@@ -589,6 +652,9 @@
+     llvm_unreachable("Invalid subclass of UniquableMDNode");
+ #define HANDLE_UNIQUABLE_LEAF(CLASS)                                           \
+   case CLASS##Kind:                                                            \
++    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
++        llvm::AlignOf<CLASS>::Alignment,                            \
++        "Insufficient alignment for objects prepended to " #CLASS); \
+     return cast<CLASS>(this)->uniquifyImpl();
+ #include "llvm/IR/Metadata.def"
+   }
+@@ -600,6 +666,9 @@
+     llvm_unreachable("Invalid subclass of UniquableMDNode");
+ #define HANDLE_UNIQUABLE_LEAF(CLASS)                                           \
+   case CLASS##Kind:                                                            \
++    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
++        llvm::AlignOf<CLASS>::Alignment,                            \
++        "Insufficient alignment for objects prepended to " #CLASS); \
+     cast<CLASS>(this)->eraseFromStoreImpl();                                   \
+     break;
+ #include "llvm/IR/Metadata.def"
+@@ -643,7 +712,91 @@
+   return *I;
+ }
+ 
+-void MDTuple::eraseFromStoreImpl() { getContext().pImpl->MDTuples.erase(this); }
++void MDTuple::eraseFromStoreImpl() {
++  getContext().pImpl->MDTuples.erase(this);
++}
++
++void *MDTuple::operator new(size_t Size, unsigned NumOps) throw() {
++  assert((Size >= sizeof(MDTuple)) && "Insufficient size to operator new!");
++
++  std::size_t OSize = NumOps * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++
++  // Allocate extra space for an uintptr_t at the beginning of the
++  // buffer.  This uintptr_t is where we will store the address of
++  // the memory-aligned storage buffer. It will be plasced immediately
++  // after the last MDOperand.
++  // This address will be computed by the matching operator delete.
++  // The total amount of space allocated must include the Size
++  // parameter passed in. This parameter value is not necessarily
++  // equal to sizeof(MDTuple), it can be greater.
++  std::size_t RSize = Size + OSize + sizeof(UniquableMDNode) +
++    sizeof(uintptr_t);
++  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
++  std::size_t Alignment = llvm::alignOf<uint64_t>();
++
++  void *P;
++
++#if defined(_MSC_VER)
++  P = _aligned_malloc(RSize, Alignment);
++  assert(P && "_aligned_malloc failed!");
++  if (!P) return 0;
++#else
++  int R = posix_memalign(&P, Alignment, RSize);
++  assert((R == 0) && "posix_memalign failed!");
++  if (R != 0) return 0;
++#endif
++
++  (void) std::memset(P, 0, RSize);
++
++  // Set a valid pointer to the address which will be returned
++  // by this operator. This will be a pointer to a MDTuple.
++  unsigned char *UC = static_cast<unsigned char*>(P);
++  MDTuple *MDT = reinterpret_cast<MDTuple*>((UC + RSize) - Size);
++  MDNode *MN = static_cast<MDNode*>(MDT);
++
++  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
++  MDOperand *MO;
++
++  for (MDOperand *E = O - NumOps; O != E; --O) {
++    MO = new (O - 1) MDOperand();
++    assert(MO && "MDOperand placement new failed!");
++  }
++
++  // We store the address of the aligned allocated buffer
++  // in the last extra element of the buffer. This address
++  // will be used by the corresponding operator delete to
++  // free the correct address.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++  *U = reinterpret_cast<uintptr_t>(P);
++  return MDT;
++}
++
++void MDTuple::operator delete(void *Mem) throw() {
++  MDTuple *MDT = reinterpret_cast<MDTuple*>(Mem);
++  UniquableMDNode *UMN = static_cast<UniquableMDNode*>(MDT);
++  MDNode *MN = static_cast<MDNode*>(UMN);
++  unsigned NumOperands = MN->getNumOperands();
++
++  std::size_t OSize = NumOperands * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++
++  MDOperand *O =
++    reinterpret_cast<MDOperand*>(reinterpret_cast<void*>(MN));
++  for (MDOperand *E = O - NumOperands; O != E; --O) {
++    MDOperand *MO = (O - 1);
++    MO->~MDOperand();
++  }
++
++  // This is teh address of the allocated buffer in the
++  // extra space allocated by operator new in RSize.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++
++  UMN->~UniquableMDNode();
++  MDT->~MDTuple();
++  std::free(reinterpret_cast<void*>(*U));
++}
++
+ 
+ MDLocation::MDLocation(LLVMContext &C, unsigned Line, unsigned Column,
+                        ArrayRef<Metadata *> MDs, bool AllowRAUW)
+@@ -675,6 +828,88 @@
+     Line = 0;
+ }
+ 
++void *MDLocation::operator new(size_t Size, unsigned NumOps) throw() {
++  assert((Size >= sizeof(MDLocation)) && "Insufficient size to operator new!");
++
++  std::size_t OSize = NumOps * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++
++  // Allocate extra space for an uintptr_t at the beginning of the
++  // buffer.  This uintptr_t is where we will store the address of
++  // the memory-aligned storage buffer. It will be plasced immediately
++  // after the last MDOperand.
++  // This address will be computed by the matching operator delete.
++  // The total amount of space allocated must include the Size
++  // parameter passed in. This parameter value is not necessarily
++  // equal to sizeof(MDLocation), it can be greater.
++  std::size_t RSize =
++    Size + OSize + sizeof(UniquableMDNode) + sizeof(uintptr_t);
++  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
++  std::size_t Alignment = llvm::alignOf<uint64_t>();
++
++  void *P;
++
++#if defined(_MSC_VER)
++  P = _aligned_malloc(RSize, Alignment);
++  assert(P && "_aligned_malloc failed!");
++  if (!P) return 0;
++#else
++  int R = posix_memalign(&P, Alignment, RSize);
++  assert((R == 0) && "posix_memalign failed!");
++  if (R != 0) return 0;
++#endif
++
++  (void) std::memset(P, 0, RSize);
++
++
++  // Set a valid pointer to the address which will be returned
++  // by this operator. This will be a pointer to a MDLocation.
++  unsigned char *UC = static_cast<unsigned char*>(P);
++  MDLocation *MDL = reinterpret_cast<MDLocation*>((UC + RSize) - Size);
++  MDNode *MN = static_cast<MDNode*>(MDL);
++
++  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
++  MDOperand *MO;
++
++  for (MDOperand *E = O - NumOps; O != E; --O) {
++    MO = new (O - 1) MDOperand();
++    assert(MO && "MDOperand placement new failed!");
++  }
++
++  // We store the address of the aligned allocated buffer
++  // in the last extra element of the buffer. This address
++  // will be used by the corresponding operator delete to
++  // free the correct address.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++  *U = reinterpret_cast<uintptr_t>(P);
++  return MDL;
++}
++
++void MDLocation::operator delete(void *Mem) throw() {
++  MDLocation *MDL = reinterpret_cast<MDLocation*>(Mem);
++  UniquableMDNode *UMN = static_cast<UniquableMDNode*>(MDL);
++  MDNode *MN = static_cast<MDNode*>(UMN);
++  unsigned NumOperands = MN->getNumOperands();
++
++  std::size_t OSize = NumOperands * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++
++  MDOperand *O =
++    reinterpret_cast<MDOperand*>(reinterpret_cast<void*>(MN));
++  for (MDOperand *E = O - NumOperands; O != E; --O) {
++    MDOperand *MO = (O - 1);
++    MO->~MDOperand();
++  }
++
++  // This is the address of the allocated buffer in the
++  // extra space allocated by operator new in RSize.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++
++  MDL->~MDLocation();
++  UMN->~UniquableMDNode();
++  std::free(reinterpret_cast<void*>(*U));
++}
++
+ static void adjustColumn(unsigned &Column) {
+   // Set to unknown on overflow.  Still use 8 bits for now.
+   if (Column >= (1u << 8))
+@@ -969,6 +1204,96 @@
+ }
+ 
+ //===----------------------------------------------------------------------===//
++// MDNodeFwdDecl implementation.
++//
++
++void *MDNodeFwdDecl::operator new(size_t Size, unsigned NumOps) throw() {
++  assert((Size >= sizeof(MDNodeFwdDecl)) && "Insufficient space to operator new!");
++
++  std::size_t OSize = NumOps * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++
++  // Allocate extra space for an uintptr_t at the beginning of the
++  // buffer.  This uintptr_t is where we will store the address of
++  // the memory-aligned storage buffer. It will be plasced immediately
++  // after the last MDOperand.
++  // This address will be computed by the matching operator delete.
++  // The total amount of space allocated must include the Size
++  // parameter passed in. This parameter value is not necessarily
++  // equal to sizeof(MDTuple), it can be greater.
++  std::size_t RSize =
++    Size +  OSize + sizeof(MDNode) + sizeof(ReplaceableMetadataImpl) +
++    sizeof(uintptr_t);
++  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
++  std::size_t Alignment = llvm::alignOf<uint64_t>();
++
++  void *P;
++
++#if defined(_MSC_VER)
++  P = _aligned_malloc(RSize, Alignment);
++  assert(P && "_aligned_malloc failed!");
++  if (!P) return 0;
++#else
++  int R = posix_memalign(&P, Alignment, RSize);
++  assert((R == 0) && "posix_memalign failed!");
++  if (R != 0) return 0;
++#endif
++
++  (void) std::memset(P, 0, RSize);
++
++  // Set a valid pointer to the address which will be returned
++  // by this operator. This will be a pointer to a MDNodeFwdDecl.
++  unsigned char *UC = static_cast<unsigned char*>(P);
++  MDNodeFwdDecl *MFD =
++    reinterpret_cast<MDNodeFwdDecl*>((UC + RSize) -
++        (Size + sizeof(ReplaceableMetadataImpl)));
++  MDNode *MN = static_cast<MDNode*>(MFD);
++  ReplaceableMetadataImpl *RMI = static_cast<ReplaceableMetadataImpl*>(MFD);
++
++  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
++  MDOperand *MO;
++
++  for (MDOperand *E = O - NumOps; O != E; --O) {
++    MO = new (O - 1) MDOperand();
++    assert(MO && "MDOperand placement new failed!");
++  }
++
++  // We store the address of the aligned allocated buffer
++  // in the last extra element of the buffer. This address
++  // will be used by the corresponding operator delete to
++  // free the correct address.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++  *U = reinterpret_cast<uintptr_t>(P);
++  return MFD;
++}
++
++void MDNodeFwdDecl::operator delete(void *Mem) throw() {
++  MDNodeFwdDecl *MFD = reinterpret_cast<MDNodeFwdDecl*>(Mem);
++  ReplaceableMetadataImpl *RMI =
++    static_cast<ReplaceableMetadataImpl*>(MFD);
++  MDNode *MN = static_cast<MDNode*>(MFD);
++
++  std::size_t OSize = MN->getNumOperands() * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++
++  MDOperand *O =
++    reinterpret_cast<MDOperand*>(reinterpret_cast<void*>(MN));
++  for (MDOperand *E = O - MN->getNumOperands(); O != E; --O) {
++    MDOperand *MO = (O - 1);
++    MO->~MDOperand();
++  }
++
++  // This is the address of the allocated buffer in the
++  // extra space allocated by operator new in RSize.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++
++  // Do not perform a full canonical destructor sequence here because
++  // MDNodeFwdDecl's are being deleted by ReplaceableMetadataImpl's
++  // destructor, which gets called from MDNode::deleteTemporary().
++  std::free(reinterpret_cast<void*>(*U));
++}
++
++//===----------------------------------------------------------------------===//
+ // NamedMDNode implementation.
+ //
+ 
+--- lib/Support/SmallVector.cpp	2012-08-21 17:11:07.000000000 -0700
++++ lib/Support/SmallVector.cpp	2015-08-26 21:28:23.352666372 -0700
+@@ -11,9 +11,13 @@
+ //
+ //===----------------------------------------------------------------------===//
+ 
++#include "llvm/Support/MathExtras.h"
++#include "llvm/Support/raw_ostream.h"
+ #include "llvm/ADT/SmallVector.h"
+ using namespace llvm;
+ 
++#include <stdlib.h>
++
+ /// grow_pod - This is an implementation of the grow() method which only works
+ /// on POD-like datatypes and is out of line to reduce code duplication.
+ void SmallVectorBase::grow_pod(void *FirstEl, size_t MinSizeInBytes,
+@@ -23,15 +27,42 @@
+   if (NewCapacityInBytes < MinSizeInBytes)
+     NewCapacityInBytes = MinSizeInBytes;
+ 
++  NewCapacityInBytes =
++    llvm::RoundUpToAlignment(NewCapacityInBytes, llvm::alignOf<uint64_t>());
++
+   void *NewElts;
+   if (BeginX == FirstEl) {
+-    NewElts = malloc(NewCapacityInBytes);
++    unsigned Alignment = llvm::alignOf<uint64_t>();
++#if defined(_MSC_VER)
++    NewElts = _aligned_malloc(Alignment, NewCapacityInBytes);
++    assert(NewElts && "_aligned_malloc failed!");
++#else
++    int R = posix_memalign(&NewElts, Alignment, NewCapacityInBytes);
++    assert((R == 0) && "posix_memalign failed!");
++#endif
++
++    assert(NewElts && "Invalid pointer after aligned allocation!");
++    (void) std::memset(NewElts, 0, NewCapacityInBytes);
+ 
+     // Copy the elements over.  No need to run dtors on PODs.
+-    memcpy(NewElts, this->BeginX, CurSizeBytes);
++    (void) std::memcpy(NewElts, this->BeginX, CurSizeBytes);
+   } else {
+     // If this wasn't grown from the inline copy, grow the allocated space.
+-    NewElts = realloc(this->BeginX, NewCapacityInBytes);
++    unsigned Alignment = llvm::alignOf<uint64_t>();
++#if defined(_MSC_VER)
++    NewElts = _aligned_malloc(Alignment, NewCapacityInBytes);
++    assert(NewElts && "_aligned_malloc failed!");
++#else
++    int R = posix_memalign(&NewElts, Alignment, NewCapacityInBytes);
++    assert((R == 0) && "posix_memalign failed!");
++#endif
++
++    assert(NewElts && "Invalid pointer after aligned allocation!");
++    (void) std::memset(NewElts, 0, NewCapacityInBytes);
++
++    // Copy the elements over.  No need to run dtors on PODs.
++    (void) std::memcpy(NewElts, this->BeginX, CurSizeBytes);
++    std::free(this->BeginX);
+   }
+ 
+   this->EndX = (char*)NewElts+CurSizeBytes;
+--- tools/clang/lib/AST/NestedNameSpecifier.cpp	2014-09-25 17:28:20.000000000 -0700
++++ tools/clang/lib/AST/NestedNameSpecifier.cpp	2015-08-26 08:27:36.324291508 -0700
+@@ -437,20 +437,37 @@
+               unsigned &BufferCapacity) {
+     if (BufferSize + (End - Start) > BufferCapacity) {
+       // Reallocate the buffer.
+-      unsigned NewCapacity 
+-      = std::max((unsigned)(BufferCapacity? BufferCapacity * 2 
+-                            : sizeof(void*) * 2),
+-                 (unsigned)(BufferSize + (End - Start)));
+-      char *NewBuffer = static_cast<char *>(malloc(NewCapacity));
+-      memcpy(NewBuffer, Buffer, BufferSize);
++      unsigned NewCapacity =
++        std::max((unsigned)(BufferCapacity? BufferCapacity * 2 
++              : sizeof(void*) * 2), (unsigned)(BufferSize + (End - Start)));
++      NewCapacity =
++        llvm::RoundUpToAlignment(NewCapacity, llvm::alignOf<uint64_t>());
++      unsigned Alignment = ((NewCapacity < 5) ? 4 : 8);
++      if (NewCapacity < Alignment)
++        NewCapacity = Alignment;
+       
+-      if (BufferCapacity)
++      char *NewBuffer;
++#if defined(_MSC_VER)
++      NewBuffer = _aligned_malloc((size_t) NewCapacity, (size_t) Alignment);
++      assert(NewBuffer && "_aligned_malloc failed!");
++#else
++      int R = posix_memalign((void**) &NewBuffer, Alignment, NewCapacity);
++
++      assert((R == 0) && "posix_memalign failed!");
++      assert(NewBuffer && "Memory allocation failed!");
++#endif
++
++      if ((Buffer != 0) && (BufferSize > 0))
++        (void) std::memcpy(NewBuffer, Buffer, BufferSize);
++
++      if ((Buffer != 0) && (BufferSize > 0))
+         free(Buffer);
++
+       Buffer = NewBuffer;
+       BufferCapacity = NewCapacity;
+     }
+     
+-    memcpy(Buffer + BufferSize, Start, End - Start);
++    (void) std::memcpy(Buffer + BufferSize, Start, End - Start);
+     BufferSize += End-Start;
+   }
+   
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/016-llvm-21851513-memory-corruption.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,3107 @@
+# 21851513 severe memory corruption in the LLVM command-line parsing module
+# 21870103 TableGen makes incorrect assumptions about anonymous namespace instantiation
+# 21870087 naming convention for the InputFile key is inconsistent across LLVM utilities
+# 21870099 128 bytes for a filesystem path is definitely not enough
+# clang makes incorrect assumptions about anonymous namespace instantiation order
+# For upstream - maybe.
+--- include/llvm/Support/ThreadLocal.h	2014-12-14 17:04:45.000000000 -0800
++++ include/llvm/Support/ThreadLocal.h	2015-09-16 14:08:58.000000000 -0700
+@@ -21,24 +21,22 @@
+ namespace llvm {
+   namespace sys {
+     // ThreadLocalImpl - Common base class of all ThreadLocal instantiations.
+     // YOU SHOULD NEVER USE THIS DIRECTLY.
+     class ThreadLocalImpl {
+       typedef uint64_t ThreadLocalDataTy;
+       /// \brief Platform-specific thread local data.
+       ///
+       /// This is embedded in the class and we avoid malloc'ing/free'ing it,
+       /// to make this class more safe for use along with CrashRecoveryContext.
+-      union {
+-        char data[sizeof(ThreadLocalDataTy)];
+-        ThreadLocalDataTy align_data;
+-      };
++      uint64_t data[2];
++
+     public:
+       ThreadLocalImpl();
+       virtual ~ThreadLocalImpl();
+       void setInstance(const void* d);
+       void *getInstance();
+       void removeInstance();
+     };
+ 
+     /// ThreadLocal - A class used to abstract thread-local storage.  It holds,
+     /// for each thread, a pointer a single object of type T.
+--- lib/Support/MemoryBuffer.cpp	2014-12-12 14:27:53.000000000 -0800
++++ lib/Support/MemoryBuffer.cpp	2015-09-19 14:20:06.472430028 -0700
+@@ -21,25 +21,29 @@
+ #include "llvm/Support/Path.h"
+ #include "llvm/Support/Process.h"
+ #include "llvm/Support/Program.h"
+ #include <cassert>
+ #include <cerrno>
+ #include <cstdio>
+ #include <cstring>
+ #include <new>
+ #include <sys/types.h>
+ #include <system_error>
++
+ #if !defined(_MSC_VER) && !defined(__MINGW32__)
+ #include <unistd.h>
+ #else
+ #include <io.h>
+ #endif
++
++#include <climits>
++
+ using namespace llvm;
+ 
+ //===----------------------------------------------------------------------===//
+ // MemoryBuffer implementation itself.
+ //===----------------------------------------------------------------------===//
+ 
+ MemoryBuffer::~MemoryBuffer() { }
+ 
+ /// init - Initialize this MemoryBuffer as a reference to externally allocated
+ /// memory, memory that we know is already null terminated.
+@@ -63,21 +67,21 @@
+ }
+ 
+ namespace {
+ struct NamedBufferAlloc {
+   const Twine &Name;
+   NamedBufferAlloc(const Twine &Name) : Name(Name) {}
+ };
+ }
+ 
+ void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
+-  SmallString<256> NameBuf;
++  SmallString<PATH_MAX> NameBuf;
+   StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
+ 
+   char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
+   CopyStringRef(Mem + N, NameRef);
+   return Mem;
+ }
+ 
+ namespace {
+ /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
+ class MemoryBufferMem : public MemoryBuffer {
+@@ -156,21 +160,21 @@
+ MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
+   std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName);
+   if (!SB)
+     return nullptr;
+   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
+   return SB;
+ }
+ 
+ ErrorOr<std::unique_ptr<MemoryBuffer>>
+ MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize) {
+-  SmallString<256> NameBuf;
++  SmallString<PATH_MAX> NameBuf;
+   StringRef NameRef = Filename.toStringRef(NameBuf);
+ 
+   if (NameRef == "-")
+     return getSTDIN();
+   return getFile(Filename, FileSize);
+ }
+ 
+ ErrorOr<std::unique_ptr<MemoryBuffer>>
+ MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize, 
+                            uint64_t Offset) {
+--- lib/Support/Unix/Program.inc	2014-12-01 16:52:01.000000000 -0800
++++ lib/Support/Unix/Program.inc	2015-09-19 15:34:57.144042911 -0700
+@@ -31,23 +31,20 @@
+ #if HAVE_SIGNAL_H
+ #include <signal.h>
+ #endif
+ #if HAVE_FCNTL_H
+ #include <fcntl.h>
+ #endif
+ #if HAVE_UNISTD_H
+ #include <unistd.h>
+ #endif
+ #ifdef HAVE_POSIX_SPAWN
+-#ifdef __sun__
+-#define  _RESTRICT_KYWD
+-#endif
+ #include <spawn.h>
+ #if !defined(__APPLE__)
+   extern char **environ;
+ #else
+ #include <crt_externs.h> // _NSGetEnviron
+ #endif
+ #endif
+ 
+ namespace llvm {
+ 
+--- lib/TableGen/Main.cpp	2014-12-10 23:04:54.000000000 -0800
++++ lib/TableGen/Main.cpp	2015-09-19 18:04:08.147911223 -0700
+@@ -21,97 +21,118 @@
+ #include "llvm/Support/MemoryBuffer.h"
+ #include "llvm/Support/ToolOutputFile.h"
+ #include "llvm/TableGen/Error.h"
+ #include "llvm/TableGen/Main.h"
+ #include "llvm/TableGen/Record.h"
+ #include <algorithm>
+ #include <cstdio>
+ #include <system_error>
+ using namespace llvm;
+ 
+-namespace {
+-  cl::opt<std::string>
+-  OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
+-                 cl::init("-"));
+-
+-  cl::opt<std::string>
+-  DependFilename("d",
+-                 cl::desc("Dependency filename"),
+-                 cl::value_desc("filename"),
+-                 cl::init(""));
+-
+-  cl::opt<std::string>
+-  InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
+-
+-  cl::list<std::string>
+-  IncludeDirs("I", cl::desc("Directory of include files"),
+-              cl::value_desc("directory"), cl::Prefix);
+-}
++static cl::opt<std::string>
++OutputFilename(cl::Prefix, "o",
++               cl::desc("Output filename"),
++               cl::value_desc("filename"),
++               cl::NotHidden,
++               cl::Optional,
++               cl::init("-"),
++               cl::ValueRequired);
++
++static cl::opt<std::string>
++DependFilename(cl::Prefix, "d",
++               cl::desc("Dependency filename"),
++               cl::value_desc("filename"),
++               cl::NotHidden,
++               cl::Optional,
++               cl::init(""),
++               cl::ValueRequired);
++
++static cl::opt<std::string>
++InputFilename(cl::Positional, "<input file>",
++              cl::desc("<input file>"),
++              cl::value_desc("Input filename"),
++              cl::NotHidden,
++              cl::Optional,
++              cl::init("-"),
++              cl::ValuePositionalNoArgs);
++
++static cl::list<std::string>
++IncludeDirs(cl::Prefix, "I",
++            cl::desc("Directory of include files"),
++            cl::value_desc("directory"),
++            cl::NotHidden,
++            cl::ZeroOrMore,
++            cl::ValueRequired);
+ 
+ /// \brief Create a dependency file for `-d` option.
+ ///
+ /// This functionality is really only for the benefit of the build system.
+ /// It is similar to GCC's `-M*` family of options.
+ static int createDependencyFile(const TGParser &Parser, const char *argv0) {
+   if (OutputFilename == "-") {
+     errs() << argv0 << ": the option -d must be used together with -o\n";
+     return 1;
+   }
+   std::error_code EC;
+   tool_output_file DepOut(DependFilename, EC, sys::fs::F_Text);
+   if (EC) {
+     errs() << argv0 << ": error opening " << DependFilename << ":"
+            << EC.message() << "\n";
+     return 1;
+   }
++
+   DepOut.os() << OutputFilename << ":";
++
+   for (const auto &Dep : Parser.getDependencies()) {
+     DepOut.os() << ' ' << Dep.first;
+   }
+   DepOut.os() << "\n";
+   DepOut.keep();
+   return 0;
+ }
+ 
+ namespace llvm {
+ 
+ int TableGenMain(char *argv0, TableGenMainFn *MainFn) {
+   RecordKeeper Records;
+ 
+   // Parse the input file.
++  llvm::Twine TFN(InputFilename);
+   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
+-      MemoryBuffer::getFileOrSTDIN(InputFilename);
++      MemoryBuffer::getFileOrSTDIN(TFN);
++
+   if (std::error_code EC = FileOrErr.getError()) {
+     errs() << "Could not open input file '" << InputFilename
+-           << "': " << EC.message() << "\n";
++      << "': " << EC.message() << "\n";
+     return 1;
+   }
+ 
+   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
+   SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
+ 
+   // Record the location of the include directory so that the lexer can find
+   // it later.
+-  SrcMgr.setIncludeDirs(IncludeDirs);
++  SrcMgr.setIncludeDirs(IncludeDirs.getStorage());
+ 
+   TGParser Parser(SrcMgr, Records);
+ 
+   if (Parser.ParseFile())
+     return 1;
+ 
+   std::error_code EC;
+   tool_output_file Out(OutputFilename, EC, sys::fs::F_Text);
+   if (EC) {
+     errs() << argv0 << ": error opening " << OutputFilename << ":"
+            << EC.message() << "\n";
+     return 1;
+   }
++
+   if (!DependFilename.empty()) {
+     if (int Ret = createDependencyFile(Parser, argv0))
+       return Ret;
+   }
+ 
+   if (MainFn(Out.os(), Records))
+     return 1;
+ 
+   if (ErrorsPrinted > 0) {
+     errs() << argv0 << ": " << ErrorsPrinted << " errors.\n";
+--- utils/TableGen/TableGen.cpp	2014-12-10 23:04:54.000000000 -0800
++++ utils/TableGen/TableGen.cpp	2015-09-14 16:23:45.000000000 -0700
+@@ -37,67 +37,67 @@
+   GenFastISel,
+   GenSubtarget,
+   GenIntrinsic,
+   GenTgtIntrinsic,
+   PrintEnums,
+   PrintSets,
+   GenOptParserDefs,
+   GenCTags
+ };
+ 
+-namespace {
+-  cl::opt<ActionType>
+-  Action(cl::desc("Action to perform:"),
+-         cl::values(clEnumValN(PrintRecords, "print-records",
+-                               "Print all records to stdout (default)"),
+-                    clEnumValN(GenEmitter, "gen-emitter",
+-                               "Generate machine code emitter"),
+-                    clEnumValN(GenRegisterInfo, "gen-register-info",
+-                               "Generate registers and register classes info"),
+-                    clEnumValN(GenInstrInfo, "gen-instr-info",
+-                               "Generate instruction descriptions"),
+-                    clEnumValN(GenCallingConv, "gen-callingconv",
+-                               "Generate calling convention descriptions"),
+-                    clEnumValN(GenAsmWriter, "gen-asm-writer",
+-                               "Generate assembly writer"),
+-                    clEnumValN(GenDisassembler, "gen-disassembler",
+-                               "Generate disassembler"),
+-                    clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
+-                               "Generate pseudo instruction lowering"),
+-                    clEnumValN(GenAsmMatcher, "gen-asm-matcher",
+-                               "Generate assembly instruction matcher"),
+-                    clEnumValN(GenDAGISel, "gen-dag-isel",
+-                               "Generate a DAG instruction selector"),
+-                    clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
+-                               "Generate DFA Packetizer for VLIW targets"),
+-                    clEnumValN(GenFastISel, "gen-fast-isel",
+-                               "Generate a \"fast\" instruction selector"),
+-                    clEnumValN(GenSubtarget, "gen-subtarget",
+-                               "Generate subtarget enumerations"),
+-                    clEnumValN(GenIntrinsic, "gen-intrinsic",
+-                               "Generate intrinsic information"),
+-                    clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
+-                               "Generate target intrinsic information"),
+-                    clEnumValN(PrintEnums, "print-enums",
+-                               "Print enum values for a class"),
+-                    clEnumValN(PrintSets, "print-sets",
+-                               "Print expanded sets for testing DAG exprs"),
+-                    clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
+-                               "Generate option definitions"),
+-                    clEnumValN(GenCTags, "gen-ctags",
+-                               "Generate ctags-compatible index"),
+-                    clEnumValEnd));
++static cl::opt<ActionType>
++Action(cl::desc("Action to perform:"),
++       cl::values(clEnumValN(PrintRecords, "print-records",
++                             "Print all records to stdout (default)"),
++                  clEnumValN(GenEmitter, "gen-emitter",
++                             "Generate machine code emitter"),
++                  clEnumValN(GenRegisterInfo, "gen-register-info",
++                             "Generate registers and register classes info"),
++                  clEnumValN(GenInstrInfo, "gen-instr-info",
++                             "Generate instruction descriptions"),
++                  clEnumValN(GenCallingConv, "gen-callingconv",
++                             "Generate calling convention descriptions"),
++                  clEnumValN(GenAsmWriter, "gen-asm-writer",
++                             "Generate assembly writer"),
++                  clEnumValN(GenDisassembler, "gen-disassembler",
++                             "Generate disassembler"),
++                  clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
++                             "Generate pseudo instruction lowering"),
++                  clEnumValN(GenAsmMatcher, "gen-asm-matcher",
++                             "Generate assembly instruction matcher"),
++                  clEnumValN(GenDAGISel, "gen-dag-isel",
++                             "Generate a DAG instruction selector"),
++                  clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
++                             "Generate DFA Packetizer for VLIW targets"),
++                  clEnumValN(GenFastISel, "gen-fast-isel",
++                             "Generate a \"fast\" instruction selector"),
++                  clEnumValN(GenSubtarget, "gen-subtarget",
++                             "Generate subtarget enumerations"),
++                  clEnumValN(GenIntrinsic, "gen-intrinsic",
++                             "Generate intrinsic information"),
++                  clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
++                             "Generate target intrinsic information"),
++                  clEnumValN(PrintEnums, "print-enums",
++                             "Print enum values for a class"),
++                  clEnumValN(PrintSets, "print-sets",
++                             "Print expanded sets for testing DAG exprs"),
++                  clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
++                             "Generate option definitions"),
++                  clEnumValN(GenCTags, "gen-ctags",
++                             "Generate ctags-compatible index"),
++                  clEnumValEnd));
+ 
+-  cl::opt<std::string>
+-  Class("class", cl::desc("Print Enum list for this class"),
+-          cl::value_desc("class name"));
++static cl::opt<std::string>
++Class("class", cl::desc("Print Enum list for this class"),
++      cl::value_desc("class name"));
+ 
++namespace {
+ bool LLVMTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
+   switch (Action) {
+   case PrintRecords:
+     OS << Records;           // No argument, dump all contents
+     break;
+   case GenEmitter:
+     EmitCodeEmitter(Records, OS);
+     break;
+   case GenRegisterInfo:
+     EmitRegisterInfo(Records, OS);
+--- tools/clang/utils/TableGen/TableGen.cpp	2015-09-19 19:30:26.983452195 -0700
++++ tools/clang/utils/TableGen/TableGen.cpp	2015-09-19 23:12:38.299907988 -0700
+@@ -48,101 +48,99 @@
+   GenClangCommentHTMLTagsProperties,
+   GenClangCommentHTMLNamedCharacterReferences,
+   GenClangCommentCommandInfo,
+   GenClangCommentCommandList,
+   GenArmNeon,
+   GenArmNeonSema,
+   GenArmNeonTest,
+   GenAttrDocs
+ };
+ 
+-namespace {
+-cl::opt<ActionType> Action(
+-    cl::desc("Action to perform:"),
+-    cl::values(
+-        clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
+-                   "Generate clang attribute clases"),
+-        clEnumValN(GenClangAttrParserStringSwitches,
+-                   "gen-clang-attr-parser-string-switches",
+-                   "Generate all parser-related attribute string switches"),
+-        clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl",
+-                   "Generate clang attribute implementations"),
+-        clEnumValN(GenClangAttrList, "gen-clang-attr-list",
+-                   "Generate a clang attribute list"),
+-        clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read",
+-                   "Generate clang PCH attribute reader"),
+-        clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
+-                   "Generate clang PCH attribute writer"),
+-        clEnumValN(GenClangAttrHasAttributeImpl,
+-                   "gen-clang-attr-has-attribute-impl",
+-                   "Generate a clang attribute spelling list"),
+-        clEnumValN(GenClangAttrSpellingListIndex,
+-                   "gen-clang-attr-spelling-index",
+-                   "Generate a clang attribute spelling index"),
+-        clEnumValN(GenClangAttrASTVisitor,
+-                   "gen-clang-attr-ast-visitor",
+-                   "Generate a recursive AST visitor for clang attributes"),
+-        clEnumValN(GenClangAttrTemplateInstantiate,
+-                   "gen-clang-attr-template-instantiate",
+-                   "Generate a clang template instantiate code"),
+-        clEnumValN(GenClangAttrParsedAttrList,
+-                   "gen-clang-attr-parsed-attr-list",
+-                   "Generate a clang parsed attribute list"),
+-        clEnumValN(GenClangAttrParsedAttrImpl,
+-                   "gen-clang-attr-parsed-attr-impl",
+-                   "Generate the clang parsed attribute helpers"),
+-        clEnumValN(GenClangAttrParsedAttrKinds,
+-                   "gen-clang-attr-parsed-attr-kinds",
+-                   "Generate a clang parsed attribute kinds"),
+-        clEnumValN(GenClangAttrDump, "gen-clang-attr-dump",
+-                   "Generate clang attribute dumper"),
+-        clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs",
+-                   "Generate Clang diagnostics definitions"),
+-        clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups",
+-                   "Generate Clang diagnostic groups"),
+-        clEnumValN(GenClangDiagsIndexName, "gen-clang-diags-index-name",
+-                   "Generate Clang diagnostic name index"),
+-        clEnumValN(GenClangCommentNodes, "gen-clang-comment-nodes",
+-                   "Generate Clang AST comment nodes"),
+-        clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes",
+-                   "Generate Clang AST declaration nodes"),
+-        clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes",
+-                   "Generate Clang AST statement nodes"),
+-        clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers",
+-                   "Generate Clang Static Analyzer checkers"),
+-        clEnumValN(GenClangCommentHTMLTags, "gen-clang-comment-html-tags",
+-                   "Generate efficient matchers for HTML tag "
+-                   "names that are used in documentation comments"),
+-        clEnumValN(GenClangCommentHTMLTagsProperties,
+-                   "gen-clang-comment-html-tags-properties",
+-                   "Generate efficient matchers for HTML tag "
+-                   "properties"),
+-        clEnumValN(GenClangCommentHTMLNamedCharacterReferences,
+-                   "gen-clang-comment-html-named-character-references",
+-                   "Generate function to translate named character "
+-                   "references to UTF-8 sequences"),
+-        clEnumValN(GenClangCommentCommandInfo, "gen-clang-comment-command-info",
+-                   "Generate command properties for commands that "
+-                   "are used in documentation comments"),
+-        clEnumValN(GenClangCommentCommandList, "gen-clang-comment-command-list",
+-                   "Generate list of commands that are used in "
+-                   "documentation comments"),
+-        clEnumValN(GenArmNeon, "gen-arm-neon", "Generate arm_neon.h for clang"),
+-        clEnumValN(GenArmNeonSema, "gen-arm-neon-sema",
+-                   "Generate ARM NEON sema support for clang"),
+-        clEnumValN(GenArmNeonTest, "gen-arm-neon-test",
+-                   "Generate ARM NEON tests for clang"),
+-        clEnumValN(GenAttrDocs, "gen-attr-docs",
+-                   "Generate attribute documentation"),
+-        clEnumValEnd));
++static cl::opt<ActionType>
++Action(cl::desc("Action to perform:"),
++       cl::values(clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
++                             "Generate clang attribute clases"),
++                  clEnumValN(GenClangAttrParserStringSwitches,
++                             "gen-clang-attr-parser-string-switches",
++                             "Generate all parser-related attribute string switches"),
++                  clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl",
++                             "Generate clang attribute implementations"),
++                  clEnumValN(GenClangAttrList, "gen-clang-attr-list",
++                             "Generate a clang attribute list"),
++                  clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read",
++                             "Generate clang PCH attribute reader"),
++                  clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
++                             "Generate clang PCH attribute writer"),
++                  clEnumValN(GenClangAttrHasAttributeImpl,
++                             "gen-clang-attr-has-attribute-impl",
++                             "Generate a clang attribute spelling list"),
++                  clEnumValN(GenClangAttrSpellingListIndex,
++                             "gen-clang-attr-spelling-index",
++                             "Generate a clang attribute spelling index"),
++                  clEnumValN(GenClangAttrASTVisitor,
++                             "gen-clang-attr-ast-visitor",
++                             "Generate a recursive AST visitor for clang attributes"),
++                  clEnumValN(GenClangAttrTemplateInstantiate,
++                             "gen-clang-attr-template-instantiate",
++                             "Generate a clang template instantiate code"),
++                  clEnumValN(GenClangAttrParsedAttrList,
++                             "gen-clang-attr-parsed-attr-list",
++                             "Generate a clang parsed attribute list"),
++                  clEnumValN(GenClangAttrParsedAttrImpl,
++                             "gen-clang-attr-parsed-attr-impl",
++                             "Generate the clang parsed attribute helpers"),
++                  clEnumValN(GenClangAttrParsedAttrKinds,
++                             "gen-clang-attr-parsed-attr-kinds",
++                             "Generate a clang parsed attribute kinds"),
++                  clEnumValN(GenClangAttrDump, "gen-clang-attr-dump",
++                             "Generate clang attribute dumper"),
++                  clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs",
++                             "Generate Clang diagnostics definitions"),
++                  clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups",
++                             "Generate Clang diagnostic groups"),
++                  clEnumValN(GenClangDiagsIndexName, "gen-clang-diags-index-name",
++                             "Generate Clang diagnostic name index"),
++                  clEnumValN(GenClangCommentNodes, "gen-clang-comment-nodes",
++                             "Generate Clang AST comment nodes"),
++                  clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes",
++                             "Generate Clang AST declaration nodes"),
++                  clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes",
++                             "Generate Clang AST statement nodes"),
++                  clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers",
++                             "Generate Clang Static Analyzer checkers"),
++                  clEnumValN(GenClangCommentHTMLTags, "gen-clang-comment-html-tags",
++                             "Generate efficient matchers for HTML tag "
++                             "names that are used in documentation comments"),
++                  clEnumValN(GenClangCommentHTMLTagsProperties,
++                             "gen-clang-comment-html-tags-properties",
++                             "Generate efficient matchers for HTML tag "
++                             "properties"),
++                  clEnumValN(GenClangCommentHTMLNamedCharacterReferences,
++                             "gen-clang-comment-html-named-character-references",
++                             "Generate function to translate named character "
++                             "references to UTF-8 sequences"),
++                  clEnumValN(GenClangCommentCommandInfo, "gen-clang-comment-command-info",
++                             "Generate command properties for commands that "
++                             "are used in documentation comments"),
++                  clEnumValN(GenClangCommentCommandList, "gen-clang-comment-command-list",
++                             "Generate list of commands that are used in "
++                             "documentation comments"),
++                  clEnumValN(GenArmNeon, "gen-arm-neon", "Generate arm_neon.h for clang"),
++                  clEnumValN(GenArmNeonSema, "gen-arm-neon-sema",
++                             "Generate ARM NEON sema support for clang"),
++                  clEnumValN(GenArmNeonTest, "gen-arm-neon-test",
++                             "Generate ARM NEON tests for clang"),
++                  clEnumValN(GenAttrDocs, "gen-attr-docs",
++                             "Generate attribute documentation"),
++                  clEnumValEnd));
+ 
+-cl::opt<std::string>
++static cl::opt<std::string>
+ ClangComponent("clang-component",
+                cl::desc("Only use warnings from specified component"),
+                cl::value_desc("component"), cl::Hidden);
+ 
+ bool ClangTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
+   switch (Action) {
+   case GenClangAttrClasses:
+     EmitClangAttrClass(Records, OS);
+     break;
+   case GenClangAttrParserStringSwitches:
+@@ -230,21 +228,20 @@
+   case GenArmNeonTest:
+     EmitNeonTest(Records, OS);
+     break;
+   case GenAttrDocs:
+     EmitClangAttrDocs(Records, OS);
+     break;
+   }
+ 
+   return false;
+ }
+-}
+ 
+ int main(int argc, char **argv) {
+   sys::PrintStackTraceOnErrorSignal();
+   PrettyStackTraceProgram X(argc, argv);
+   cl::ParseCommandLineOptions(argc, argv);
+ 
+   return TableGenMain(argv[0], &ClangTableGenMain);
+ }
+ 
+ #ifdef __has_feature
+--- lib/IR/LegacyPassManager.cpp	2015-01-28 09:39:35.000000000 -0800
++++ lib/IR/LegacyPassManager.cpp	2015-10-05 11:01:32.789436446 -0700
+@@ -40,15 +40,18 @@
+ // pass name to be printed before it executes.
+ //
+ 
+-namespace {
+ // Different debug levels that can be enabled...
+ enum PassDebugLevel {
+-  Disabled, Arguments, Structure, Executions, Details
++  Disabled,
++  Arguments,
++  Structure,
++  Executions,
++  Details
+ };
+-}
+ 
+ static cl::opt<enum PassDebugLevel>
+-PassDebugging("debug-pass", cl::Hidden,
++PassDebugging("debug-pass",
++              cl::Hidden,
+                   cl::desc("Print PassManager debugging information"),
+                   cl::values(
+   clEnumVal(Disabled  , "disable debug output"),
+@@ -58,36 +61,44 @@
+   clEnumVal(Details   , "print pass details when it is executed"),
+                              clEnumValEnd));
+ 
+-namespace {
+-typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
+-PassOptionList;
+-}
+-
+ // Print IR out before/after specified passes.
+-static PassOptionList
+-PrintBefore("print-before",
+-            llvm::cl::desc("Print IR before specified passes"),
+-            cl::Hidden);
+-
+-static PassOptionList
+-PrintAfter("print-after",
+-           llvm::cl::desc("Print IR after specified passes"),
+-           cl::Hidden);
++static llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
++PrintBefore(cl::Prefix, "print-before",
++            cl::desc("Print IR before specified passes"),
++            cl::value_desc("Print IR before specified passes"),
++            cl::Hidden,
++            cl::ZeroOrMore);
++
++static llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
++PrintAfter(cl::Prefix, "print-after",
++           cl::desc("Print IR after specified passes"),
++           cl::value_desc("Print IR after specified passes"),
++           cl::Hidden,
++           cl::ZeroOrMore);
+ 
+ static cl::opt<bool>
+-PrintBeforeAll("print-before-all",
++PrintBeforeAll(cl::NormalFormatting, "print-before-all",
+                llvm::cl::desc("Print IR before each pass"),
++               llvm::cl::value_desc("Print IR before each pass"),
++               cl::Hidden,
++               cl::Optional,
+                cl::init(false));
++
+ static cl::opt<bool>
+-PrintAfterAll("print-after-all",
++PrintAfterAll(cl::NormalFormatting, "print-after-all",
+               llvm::cl::desc("Print IR after each pass"),
++              llvm::cl::value_desc("Print IR after each pass"),
++              cl::Hidden,
++              cl::Optional,
+               cl::init(false));
+ 
+ /// This is a helper to determine whether to print IR before or
+ /// after a pass.
+ 
+-static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
+-                                         PassOptionList &PassesToPrint) {
++static bool
++ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
++                             llvm::cl::list<const llvm::PassInfo *, bool,
++                                            PassNameParser> &PassesToPrint) {
+   for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
+     const llvm::PassInfo *PassInf = PassesToPrint[i];
+     if (PassInf)
+--- lib/Support/CommandLine.cpp	2015-01-13 11:14:20.000000000 -0800
++++ lib/Support/CommandLine.cpp	2016-01-19 10:13:33.212967353 -0800
+@@ -41,6 +41,8 @@
+ 
+ #define DEBUG_TYPE "commandline"
+ 
++#include <iostream>
++
+ //===----------------------------------------------------------------------===//
+ // Template instantiations and anchors.
+ //
+@@ -85,7 +87,7 @@
+ 
+ // Globals for name and overview of program.  Program name is not a string to
+ // avoid static ctor/dtor issues.
+-static char ProgramName[80] = "<premain>";
++static std::string ProgramName("<premain>");
+ static const char *ProgramOverview = nullptr;
+ 
+ // This collects additional help to be printed.
+@@ -102,14 +104,14 @@
+ 
+ /// RegisteredOptionList - This is the list of the command line options that
+ /// have statically constructed themselves.
+-static Option *RegisteredOptionList = nullptr;
++Option *Option::RegisteredOptionList = nullptr;
+ 
+ void Option::addArgument() {
+   assert(!NextRegistered && "argument multiply registered!");
++  Option *O = dynamic_cast<Option*>(this);
++  assert(O && "Cannot dynamic_cast to correct type!");
+ 
+-  NextRegistered = RegisteredOptionList;
+-  RegisteredOptionList = this;
+-  MarkOptionsChanged();
++  Option::registerOption(O);
+ }
+ 
+ void Option::removeArgument() {
+@@ -149,24 +151,26 @@
+ 
+ /// GetOptionInfo - Scan the list of registered options, turning them into data
+ /// structures that are easier to handle.
+-static void GetOptionInfo(SmallVectorImpl<Option *> &PositionalOpts,
+-                          SmallVectorImpl<Option *> &SinkOpts,
++static void GetOptionInfo(std::vector<Option *> &PositionalOpts,
++                          std::vector<Option *> &SinkOpts,
+                           StringMap<Option *> &OptionsMap) {
+   bool HadErrors = false;
+-  SmallVector<const char *, 16> OptionNames;
++  std::vector<const char *> OptionNames;
+   Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
+-  for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
++  for (Option *O = Option::getRegisteredOptionList(); O;
++       O = O->getNextRegisteredOption()) {
+     // If this option wants to handle multiple option names, get the full set.
+     // This handles enum options like "-O1 -O2" etc.
+     O->getExtraOptionNames(OptionNames);
+-    if (O->ArgStr[0])
++
++    if (O->ArgStr && *O->ArgStr)
+       OptionNames.push_back(O->ArgStr);
+ 
+     // Handle named options.
+     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
+       // Add argument to the argument map!
+       if (!OptionsMap.insert(std::make_pair(OptionNames[i], O)).second) {
+-        errs() << ProgramName << ": CommandLine Error: Option '"
++        errs() << ProgramName.c_str() << ": CommandLine Error: Option '"
+                << OptionNames[i] << "' registered more than once!\n";
+         HadErrors = true;
+       }
+@@ -201,6 +205,24 @@
+     report_fatal_error("inconsistency in registered CommandLine options");
+ }
+ 
++/// HandleSpecialPrefixOptions - certain options need special handling
++/// of their Argyment/Value pair, because there will be no space separator
++/// between the two. For example -O<N> (optimization level).
++static void HandleSpecialPrefixOptions(StringRef &ArgName, StringRef &Value) {
++  if (ArgName.empty())
++    return;
++
++  char AN = ArgName.front();
++  switch (AN) {
++  default:
++    break;
++  case 'O':
++    Value = ArgName.substr(1, 1);
++    ArgName = ArgName.substr(0, 1);
++    break;
++  }
++}
++
+ /// LookupOption - Lookup the option specified by the specified option on the
+ /// command line.  If there is a value specified (after an equal sign) return
+ /// that as well.  This assumes that leading dashes have already been stripped.
+@@ -210,12 +232,35 @@
+   if (Arg.empty())
+     return nullptr;
+ 
++  HandleSpecialPrefixOptions(Arg, Value);
++
+   size_t EqualPos = Arg.find('=');
+ 
+   // If we have an equals sign, remember the value.
+   if (EqualPos == StringRef::npos) {
++    StringRef InputFile;
++
+     // Look up the option.
+     StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
++
++    // TableGen
++    if (I == OptionsMap.end()) {
++      InputFile = "<input file>";
++      I = OptionsMap.find(InputFile);
++    }
++
++    // lli && llc
++    if (I == OptionsMap.end()) {
++      InputFile = "<input bitcode>";
++      I = OptionsMap.find(InputFile);
++    }
++
++    // opt
++    if (I == OptionsMap.end()) {
++      InputFile = "<input bitcode file>";
++      I = OptionsMap.find(InputFile);
++    }
++
+     return I != OptionsMap.end() ? I->second : nullptr;
+   }
+ 
+@@ -254,7 +299,7 @@
+                                            ie = OptionsMap.end();
+        it != ie; ++it) {
+     Option *O = it->second;
+-    SmallVector<const char *, 16> OptionNames;
++    std::vector<const char *> OptionNames;
+     O->getExtraOptionNames(OptionNames);
+     if (O->ArgStr[0])
+       OptionNames.push_back(O->ArgStr);
+@@ -322,9 +367,11 @@
+   // Enforce value requirements
+   switch (Handler->getValueExpectedFlag()) {
+   case ValueRequired:
+-    if (!Value.data()) { // No value specified?
++    if (Value.empty()) { // No value specified?
+       if (i + 1 >= argc)
+-        return Handler->error("requires a value!");
++        return
++          Handler->error("argument requires a value but none was provided!");
++
+       // Steal the next argument, like for '-o filename'
+       assert(argv && "null check");
+       Value = argv[++i];
+@@ -335,11 +382,17 @@
+       return Handler->error("multi-valued option specified"
+                             " with ValueDisallowed modifier!");
+ 
+-    if (Value.data())
++    if (!Value.empty())
+       return Handler->error("does not allow a value! '" + Twine(Value) +
+                             "' specified.");
+     break;
+   case ValueOptional:
++  case ValuePositionalNoArgs:
++    break;
++  case ValuePositionalWithArgs:
++    break;
++  default:
++    return Handler->error("Unknown/invalid Option type!");
+     break;
+   }
+ 
+@@ -373,7 +426,15 @@
+ 
+ static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
+   int Dummy = i;
+-  return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
++  bool R = ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
++  return R;
++}
++
++static bool ProvidePositionalOptionWithArgs(Option *Handler, StringRef Arg,
++                                            int i, unsigned &ValNo,
++                                            unsigned &NumPositionsRequired) {
++  // FIXME: IMPLEMENT
++  return false;
+ }
+ 
+ // Option predicates...
+@@ -416,7 +477,7 @@
+ /// see if this is a prefix or grouped option.  If so, split arg into output an
+ /// Arg/Value pair and return the Option to parse it with.
+ static Option *
+-HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
++HandlePrefixedOrGroupedOption(std::string &Arg, std::string &Value,
+                               bool &ErrorParsing,
+                               const StringMap<Option *> &OptionsMap) {
+   if (Arg.size() == 1)
+@@ -465,7 +526,10 @@
+ 
+ static bool RequiresValue(const Option *O) {
+   return O->getNumOccurrencesFlag() == cl::Required ||
+-         O->getNumOccurrencesFlag() == cl::OneOrMore;
++         O->getNumOccurrencesFlag() == cl::OneOrMore ||
++         O->getValueExpectedFlag() == cl::ValueRequired ||
++         O->getValueExpectedFlag() == cl::ValuePositionalNoArgs ||
++         O->getValueExpectedFlag() == cl::ValuePositionalWithArgs;
+ }
+ 
+ static bool EatsUnboundedNumberOfValues(const Option *O) {
+@@ -480,9 +544,9 @@
+ static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
+ 
+ void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
+-                                SmallVectorImpl<const char *> &NewArgv,
++                                std::vector<const char *> &NewArgv,
+                                 bool MarkEOLs) {
+-  SmallString<128> Token;
++  SmallString<PATH_MAX> Token;
+   for (size_t I = 0, E = Src.size(); I != E; ++I) {
+     // Consume runs of whitespace.
+     if (Token.empty()) {
+@@ -556,7 +620,7 @@
+ ///    consumed in this case.
+ ///
+ ///  * Otherwise, backslashes are interpreted literally.
+-static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
++static size_t parseBackslash(StringRef Src, size_t I, SmallString<256> &Token) {
+   size_t E = Src.size();
+   int BackslashCount = 0;
+   // Skip the backslashes.
+@@ -578,9 +642,9 @@
+ }
+ 
+ void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
+-                                    SmallVectorImpl<const char *> &NewArgv,
++                                    std::vector<const char *> &NewArgv,
+                                     bool MarkEOLs) {
+-  SmallString<128> Token;
++  SmallString<256> Token;
+ 
+   // This is a small state machine to consume characters until it reaches the
+   // end of the source string.
+@@ -657,7 +721,7 @@
+ 
+ static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
+                                TokenizerCallback Tokenizer,
+-                               SmallVectorImpl<const char *> &NewArgv,
++                               std::vector<const char *> &NewArgv,
+                                bool MarkEOLs = false) {
+   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
+       MemoryBuffer::getFile(FName);
+@@ -684,7 +748,7 @@
+ /// \brief Expand response files on a command line recursively using the given
+ /// StringSaver and tokenization strategy.
+ bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
+-                             SmallVectorImpl<const char *> &Argv,
++                             std::vector<const char *> &Argv,
+                              bool MarkEOLs) {
+   unsigned RspFiles = 0;
+   bool AllExpanded = true;
+@@ -711,7 +775,7 @@
+     // contents.  Nested response files are expanded in subsequent iterations.
+     // FIXME: If a nested response file uses a relative path, is it relative to
+     // the cwd of the process or the response file?
+-    SmallVector<const char *, 0> ExpandedArgv;
++    std::vector<const char *> ExpandedArgv;
+     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
+                             MarkEOLs)) {
+       // We couldn't read this file, so we leave it in the argument stream and
+@@ -764,7 +828,7 @@
+ 
+   // Get program's "name", which we wouldn't know without the caller
+   // telling us.
+-  SmallVector<const char *, 20> newArgv;
++  std::vector<const char *> newArgv;
+   StrDupSaver Saver;
+   newArgv.push_back(Saver.SaveString(progName));
+ 
+@@ -778,27 +842,25 @@
+ void cl::ParseCommandLineOptions(int argc, const char *const *argv,
+                                  const char *Overview) {
+   // Process all registered options.
+-  SmallVector<Option *, 4> PositionalOpts;
+-  SmallVector<Option *, 4> SinkOpts;
++  std::vector<Option*> PositionalOpts;
++  std::vector<Option*> SinkOpts;
+   StringMap<Option *> Opts;
+   GetOptionInfo(PositionalOpts, SinkOpts, Opts);
+ 
+   assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!");
+ 
+   // Expand response files.
+-  SmallVector<const char *, 20> newArgv;
++  std::vector<const char*> newArgv;
++
+   for (int i = 0; i != argc; ++i)
+     newArgv.push_back(argv[i]);
++
+   StrDupSaver Saver;
+   ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
+   argv = &newArgv[0];
+   argc = static_cast<int>(newArgv.size());
+ 
+-  // Copy the program name into ProgName, making sure not to overflow it.
+-  StringRef ProgName = sys::path::filename(argv[0]);
+-  size_t Len = std::min(ProgName.size(), size_t(79));
+-  memcpy(ProgramName, ProgName.data(), Len);
+-  ProgramName[Len] = '\0';
++  ProgramName = sys::path::filename(argv[0]).str();
+ 
+   ProgramOverview = Overview;
+   bool ErrorParsing = false;
+@@ -810,6 +872,7 @@
+   bool HasUnlimitedPositionals = false;
+ 
+   Option *ConsumeAfterOpt = nullptr;
++
+   if (!PositionalOpts.empty()) {
+     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
+       assert(PositionalOpts.size() > 1 &&
+@@ -819,8 +882,7 @@
+ 
+     // Calculate how many positional values are _required_.
+     bool UnboundedFound = false;
+-    for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size(); i != e;
+-         ++i) {
++    for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
+       Option *Opt = PositionalOpts[i];
+       if (RequiresValue(Opt))
+         ++NumPositionalRequired;
+@@ -844,13 +906,14 @@
+       }
+       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
+     }
++
+     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
+   }
+ 
+   // PositionalVals - A vector of "positional" arguments we accumulate into
+   // the process at the end.
+   //
+-  SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
++  std::vector<std::pair<StringRef, unsigned> > PositionalVals;
+ 
+   // If the program has named positional arguments, and the name has been run
+   // across, keep track of which positional argument was named.  Otherwise put
+@@ -862,39 +925,25 @@
+   for (int i = 1; i < argc; ++i) {
+     Option *Handler = nullptr;
+     Option *NearestHandler = nullptr;
++    Option *PrefixOrGroupHandler = nullptr;
+     std::string NearestHandlerString;
+-    StringRef Value;
++    StringRef Value = "";
+     StringRef ArgName = "";
+ 
+-    // If the option list changed, this means that some command line
+-    // option has just been registered or deregistered.  This can occur in
+-    // response to things like -load, etc.  If this happens, rescan the options.
+-    if (OptionListChanged) {
+-      PositionalOpts.clear();
+-      SinkOpts.clear();
+-      Opts.clear();
+-      GetOptionInfo(PositionalOpts, SinkOpts, Opts);
+-      OptionListChanged = false;
+-    }
+-
+     // Check to see if this is a positional argument.  This argument is
+     // considered to be positional if it doesn't start with '-', if it is "-"
+     // itself, or if we have seen "--" already.
+     //
+-    if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
+-      // Positional argument!
+-      if (ActivePositionalArg) {
+-        ProvidePositionalOption(ActivePositionalArg, argv[i], i);
+-        continue; // We are done!
+-      }
+-
++    if (((argv[i][0] != '-') && (argv[i][1] != '\0')) ||
++        ((argv[i][0] == '-') && (argv[i][1] == '\0')) || DashDashFound) {
+       if (!PositionalOpts.empty()) {
+         PositionalVals.push_back(std::make_pair(argv[i], i));
+ 
+         // All of the positional arguments have been fulfulled, give the rest to
+         // the consume after option... if it's specified...
+         //
+-        if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
++        if ((PositionalVals.size() >= NumPositionalRequired) &&
++            ConsumeAfterOpt) {
+           for (++i; i < argc; ++i)
+             PositionalVals.push_back(std::make_pair(argv[i], i));
+           break; // Handle outside of the argument processing loop...
+@@ -913,6 +962,7 @@
+       // option is another positional argument.  If so, treat it as an argument,
+       // otherwise feed it to the eating positional.
+       ArgName = argv[i] + 1;
++
+       // Eat leading dashes.
+       while (!ArgName.empty() && ArgName[0] == '-')
+         ArgName = ArgName.substr(1);
+@@ -924,17 +974,32 @@
+       }
+ 
+     } else { // We start with a '-', must be an argument.
+-      ArgName = argv[i] + 1;
++      // ArgName = i == (argc - 1) ? argv[i] : argv[i] + 1;
++      ArgName = argv[i];
++
+       // Eat leading dashes.
+       while (!ArgName.empty() && ArgName[0] == '-')
+         ArgName = ArgName.substr(1);
+ 
+       Handler = LookupOption(ArgName, Value, Opts);
+-
+-      // Check to see if this "option" is really a prefixed or grouped argument.
+-      if (!Handler)
+-        Handler =
+-            HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, Opts);
++      if (Handler) {
++        enum FormattingFlags FF = Handler->getFormattingFlag();
++        if ((FF == llvm::cl::Prefix) || (FF == llvm::cl::Grouping)) {
++          if (Value.empty())
++            Value = argv[++i];
++
++          std::string SA = ArgName.str();
++          std::string SV = Value.str();
++          SA.append(SV);
++
++          // Check to see if this "option" is really a prefixed or
++          // grouped argument.
++          PrefixOrGroupHandler =
++            HandlePrefixedOrGroupedOption(SA, SV, ErrorParsing, Opts);
++          if (PrefixOrGroupHandler)
++            Handler = PrefixOrGroupHandler;
++        }
++      }
+ 
+       // Otherwise, look for the closest available option to report to the user
+       // in the upcoming error.
+@@ -945,22 +1010,23 @@
+ 
+     if (!Handler) {
+       if (SinkOpts.empty()) {
+-        errs() << ProgramName << ": Unknown command line argument '" << argv[i]
+-               << "'.  Try: '" << argv[0] << " -help'\n";
++        errs() << ProgramName.c_str()
++          << ": Unknown command line argument '" << argv[i]
++          << "'.  Try: '" << argv[0] << " -help'\n";
+ 
+         if (NearestHandler) {
+           // If we know a near match, report it as well.
+-          errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
+-                 << "'?\n";
++          errs() << ProgramName.c_str()
++            << ": Did you mean '-" << NearestHandlerString << "'?\n";
+         }
+ 
+         ErrorParsing = true;
+       } else {
+-        for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
+-                                                 E = SinkOpts.end();
+-             I != E; ++I)
++        for (std::vector<Option *>::iterator I = SinkOpts.begin(),
++             E = SinkOpts.end(); I != E; ++I)
+           (*I)->addOccurrence(i, "", argv[i]);
+       }
++
+       continue;
+     }
+ 
+@@ -974,50 +1040,77 @@
+ 
+   // Check and handle positional arguments now...
+   if (NumPositionalRequired > PositionalVals.size()) {
+-    errs() << ProgramName
+-           << ": Not enough positional command line arguments specified!\n"
+-           << "Must specify at least " << NumPositionalRequired
+-           << " positional arguments: See: " << argv[0] << " -help\n";
++    errs() << ProgramName.c_str()
++      << ": Not enough positional command line arguments specified!\n"
++      << "Must specify at least " << NumPositionalRequired
++      << " positional arguments: See: " << argv[0] << " -help\n";
+ 
+     ErrorParsing = true;
+   } else if (!HasUnlimitedPositionals &&
+              PositionalVals.size() > PositionalOpts.size()) {
+-    errs() << ProgramName << ": Too many positional arguments specified!\n"
+-           << "Can specify at most " << PositionalOpts.size()
+-           << " positional arguments: See: " << argv[0] << " -help\n";
++    errs() << ProgramName.c_str()
++      << ": Too many positional arguments specified!\n"
++      << "Can specify at most " << PositionalOpts.size()
++      << " positional arguments: See: " << argv[0] << " -help\n";
+     ErrorParsing = true;
+ 
+   } else if (!ConsumeAfterOpt) {
+     // Positional args have already been handled if ConsumeAfter is specified.
+-    unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
++    unsigned ValNo = 0;
++    unsigned NumVals = static_cast<unsigned>(PositionalVals.size());
+     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
+-      if (RequiresValue(PositionalOpts[i])) {
+-        ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
++      Option *PO = PositionalOpts[i];
++      if (RequiresValue(PO)) {
++        ProvidePositionalOption(PO, PositionalVals[ValNo].first,
+                                 PositionalVals[ValNo].second);
+         ValNo++;
+         --NumPositionalRequired; // We fulfilled our duty...
+       }
+ 
++      enum llvm::cl::ValueExpected VE = PO->getValueExpectedFlag();
++
++      // If it's a positional argument, provide it.
++      if ((NumVals - ValNo) > NumPositionalRequired) {
++        if (VE == llvm::cl::ValuePositionalNoArgs) {
++          ProvidePositionalOption(PO, PositionalVals[ValNo].first,
++                                  PositionalVals[ValNo].second);
++          ++ValNo;
++          --NumPositionalRequired;
++          continue;
++        } else if (VE == llvm::cl::ValuePositionalWithArgs) {
++          ProvidePositionalOptionWithArgs(PO, PositionalVals[ValNo].first,
++                                          PositionalVals[ValNo].second,
++                                          ValNo,
++                                          NumPositionalRequired);
++          continue;
++        }
++      }
++
+       // If we _can_ give this option more arguments, do so now, as long as we
+       // do not give it values that others need.  'Done' controls whether the
+       // option even _WANTS_ any more.
+       //
+-      bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
+-      while (NumVals - ValNo > NumPositionalRequired && !Done) {
+-        switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
++      bool Done =
++        ((PO->getNumOccurrencesFlag() == cl::Required) &&
++         (VE != llvm::cl::ValuePositionalNoArgs));
++
++      while (((NumVals - ValNo) > NumPositionalRequired)  && !Done) {
++        switch (PO->getNumOccurrencesFlag()) {
+         case cl::Optional:
+           Done = true; // Optional arguments want _at most_ one value
+         // FALL THROUGH
++          break;
+         case cl::ZeroOrMore: // Zero or more will take all they can get...
+         case cl::OneOrMore:  // One or more will take all they can get...
+-          ProvidePositionalOption(PositionalOpts[i],
+-                                  PositionalVals[ValNo].first,
++          ProvidePositionalOption(PO, PositionalVals[ValNo].first,
+                                   PositionalVals[ValNo].second);
+           ValNo++;
+           break;
+         default:
+-          llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
+-                           "positional argument processing!");
++          assert(0 && "Internal Compiler Error: "
++                 "unexpected NumOccurrences flag "
++                 "in positional argument processing!");
++          break;
+         }
+       }
+     }
+@@ -1029,7 +1122,7 @@
+         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
+                                                 PositionalVals[ValNo].first,
+                                                 PositionalVals[ValNo].second);
+-        ValNo++;
++        ++ValNo;
+       }
+ 
+     // Handle the case where there is just one positional option, and it's
+@@ -1041,7 +1134,7 @@
+       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
+                                               PositionalVals[ValNo].first,
+                                               PositionalVals[ValNo].second);
+-      ValNo++;
++      ++ValNo;
+     }
+ 
+     // Handle over all of the rest of the arguments to the
+@@ -1061,7 +1154,7 @@
+         Opt.second->error("must be specified at least once!");
+         ErrorParsing = true;
+       }
+-    // Fall through
++      break;
+     default:
+       break;
+     }
+@@ -1095,7 +1188,7 @@
+   if (ArgName.empty())
+     errs() << HelpStr; // Be nice for positional arguments
+   else
+-    errs() << ProgramName << ": for the -" << ArgName;
++    errs() << ProgramName.c_str() << ": for the -" << ArgName;
+ 
+   errs() << " option: " << Message << "\n";
+   return true;
+@@ -1106,7 +1199,9 @@
+   if (!MultiArg)
+     NumOccurrences++; // Increment the number of times we have been seen
+ 
+-  switch (getNumOccurrencesFlag()) {
++  llvm::cl::NumOccurrencesFlag NOF = getNumOccurrencesFlag();
++
++  switch (NOF) {
+   case Optional:
+     if (NumOccurrences > 1)
+       return error("may only occur zero or one times!", ArgName);
+@@ -1121,7 +1216,11 @@
+     break;
+   }
+ 
+-  return handleOccurrence(pos, ArgName, Value);
++  std::string SAN = ArgName;
++  std::string SV = Value;
++
++  bool R = handleOccurrence(pos, SAN.c_str(), SV.c_str());
++  return R;
+ }
+ 
+ // getValueStr - Get the value description string, using "DefaultMsg" if nothing
+@@ -1402,11 +1501,12 @@
+ PRINT_OPT_DIFF(float)
+ PRINT_OPT_DIFF(char)
+ 
+-void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
++void parser<std::string>::printOptionDiff(const Option &O,
++                                          const std::string &V,
+                                           OptionValue<std::string> D,
+                                           size_t GlobalWidth) const {
+   printOptionName(O, GlobalWidth);
+-  outs() << "= " << V;
++  outs() << "= " << V.c_str();
+   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
+   outs().indent(NumSpaces) << " (default: ";
+   if (D.hasValue())
+@@ -1427,20 +1527,22 @@
+ // -help and -help-hidden option implementation
+ //
+ 
+-static int OptNameCompare(const void *LHS, const void *RHS) {
+-  typedef std::pair<const char *, Option *> pair_ty;
+-
+-  return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
+-}
++template<typename Ty>
++struct OptNameCompare : public std::binary_function<Ty, Ty, bool> {
++  inline bool operator()(const Ty& LHS, const Ty& RHS) const {
++    return std::strcmp(LHS.first, RHS.first) <= 0;
++  }
++};
+ 
+ // Copy Options into a vector so we can sort them as we like.
+ static void sortOpts(StringMap<Option *> &OptMap,
+-                     SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
++                     std::vector<std::pair<const char*, Option*> > &Opts,
+                      bool ShowHidden) {
+   SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
+ 
+   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
+        I != E; ++I) {
++
+     // Ignore really-hidden options.
+     if (I->second->getOptionHiddenFlag() == ReallyHidden)
+       continue;
+@@ -1453,12 +1555,13 @@
+     if (!OptionSet.insert(I->second).second)
+       continue;
+ 
+-    Opts.push_back(
+-        std::pair<const char *, Option *>(I->getKey().data(), I->second));
++    std::pair<const char*, Option*> KVP(I->getKey().data(), I->second);
++    Opts.push_back(KVP);
+   }
+ 
+   // Sort the options list alphabetically.
+-  qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
++  OptNameCompare<std::pair<const char*, Option*> >  ONC;
++  std::sort(Opts.begin(), Opts.end(), ONC);
+ }
+ 
+ namespace {
+@@ -1466,8 +1569,9 @@
+ class HelpPrinter {
+ protected:
+   const bool ShowHidden;
+-  typedef SmallVector<std::pair<const char *, Option *>, 128>
++  typedef std::vector<std::pair<const char *, Option *> >
+       StrOptionPairVector;
++
+   // Print the options. Opts is assumed to be alphabetically sorted.
+   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
+     for (size_t i = 0, e = Opts.size(); i != e; ++i)
+@@ -1484,8 +1588,8 @@
+       return;
+ 
+     // Get all the options.
+-    SmallVector<Option *, 4> PositionalOpts;
+-    SmallVector<Option *, 4> SinkOpts;
++    std::vector<Option *> PositionalOpts;
++    std::vector<Option *> SinkOpts;
+     StringMap<Option *> OptMap;
+     GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
+ 
+@@ -1495,7 +1599,7 @@
+     if (ProgramOverview)
+       outs() << "OVERVIEW: " << ProgramOverview << "\n";
+ 
+-    outs() << "USAGE: " << ProgramName << " [options]";
++    outs() << "USAGE: " << ProgramName.c_str() << " [options]";
+ 
+     // Print out the positional options.
+     Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
+@@ -1710,12 +1814,12 @@
+     return;
+ 
+   // Get all the options.
+-  SmallVector<Option *, 4> PositionalOpts;
+-  SmallVector<Option *, 4> SinkOpts;
++  std::vector<Option *> PositionalOpts;
++  std::vector<Option *> SinkOpts;
+   StringMap<Option *> OptMap;
+   GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
+ 
+-  SmallVector<std::pair<const char *, Option *>, 128> Opts;
++  std::vector<std::pair<const char *, Option *> > Opts;
+   sortOpts(OptMap, Opts, /*ShowHidden*/ true);
+ 
+   // Compute the maximum argument length...
+@@ -1825,8 +1929,8 @@
+ 
+ void cl::getRegisteredOptions(StringMap<Option *> &Map) {
+   // Get all the options.
+-  SmallVector<Option *, 4> PositionalOpts; // NOT USED
+-  SmallVector<Option *, 4> SinkOpts; // NOT USED
++  std::vector<Option *> PositionalOpts; // NOT USED
++  std::vector<Option *> SinkOpts; // NOT USED
+   assert(Map.size() == 0 && "StringMap must be empty");
+   GetOptionInfo(PositionalOpts, SinkOpts, Map);
+   return;
+--- lib/Support/PluginLoader.cpp	2012-12-03 08:50:05.000000000 -0800
++++ lib/Support/PluginLoader.cpp	2016-01-24 11:02:33.000000000 -0800
+@@ -34,6 +34,21 @@
+   }
+ }
+ 
++bool PluginLoader::operator==(const std::string &Filename) const {
++  sys::SmartScopedLock<true> Lock(*PluginsLock);
++  for (std::vector<std::string>::const_iterator I = Plugins->begin(),
++       E = Plugins->end(); I != E; ++I) {
++    if (*I == Filename)
++      return true;
++  }
++
++  return false;
++}
++
++bool PluginLoader::operator!=(const std::string &Filename) const {
++  return !this->operator==(Filename);
++}
++
+ unsigned PluginLoader::getNumPlugins() {
+   sys::SmartScopedLock<true> Lock(*PluginsLock);
+   return Plugins.isConstructed() ? Plugins->size() : 0;
+--- include/llvm/Support/CommandLine.h	2015-01-13 11:14:20.000000000 -0800
++++ include/llvm/Support/CommandLine.h	2016-01-19 11:56:32.087336770 -0800
+@@ -24,6 +24,7 @@
+ #include "llvm/ADT/StringMap.h"
+ #include "llvm/ADT/Twine.h"
+ #include "llvm/Support/Compiler.h"
++#include "llvm/Support/raw_ostream.h"
+ #include <cassert>
+ #include <climits>
+ #include <cstdarg>
+@@ -97,9 +98,11 @@
+ 
+ enum ValueExpected { // Is a value required for the option?
+   // zero reserved for the unspecified value
+-  ValueOptional = 0x01,  // The value can appear... or not
+-  ValueRequired = 0x02,  // The value is required to appear!
+-  ValueDisallowed = 0x03 // A value may not be specified (for flags)
++  ValueOptional = 0x01,           // The value can appear... or not
++  ValueRequired = 0x02,           // The value is required to appear!
++  ValueDisallowed = 0x03,         // A value may not be specified (for flags)
++  ValuePositionalNoArgs = 0x04,   // Positional Argument, no additional args
++  ValuePositionalWithArgs = 0x05  // Positional Argument, with additional args
+ };
+ 
+ enum OptionHidden {   // Control whether -help shows this option
+@@ -137,6 +140,36 @@
+ };
+ 
+ //===----------------------------------------------------------------------===//
++// Generic Filename Locations
++//
++struct GenericFilenameLocation {
++  GenericFilenameLocation() : Value("") { }
++  GenericFilenameLocation(const std::string &S) : Value(S) { }
++
++  void operator=(const std::string &S) {
++    if (!S.empty())
++      Value = S;
++  }
++
++  std::string Value;
++};
++
++struct GenericFilenameLocations {
++  GenericFilenameLocations() : Value() { }
++  GenericFilenameLocations(const std::string &S)
++  : Value() {
++    Value.push_back(S);
++  }
++
++  void operator=(const std::string &S) {
++    if (!S.empty())
++      Value.push_back(S);
++  }
++
++  std::vector<std::string> Value;
++};
++
++//===----------------------------------------------------------------------===//
+ // Option Category class
+ //
+ class OptionCategory {
+@@ -162,9 +195,15 @@
+ // Option Base class
+ //
+ class alias;
++
+ class Option {
+   friend class alias;
+ 
++protected:
++  /// RegisteredOptionList - This is the list of the command line options
++  /// that have statically constructed themselves.
++  static Option *RegisteredOptionList;
++
+   // handleOccurrences - Overriden by subclasses to handle the value passed into
+   // an argument.  Should return true if there was an error processing the
+   // argument and the program should exit.
+@@ -182,13 +221,13 @@
+   int NumOccurrences; // The number of times specified
+   // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
+   // problems with signed enums in bitfields.
+-  unsigned Occurrences : 3; // enum NumOccurrencesFlag
++  unsigned Occurrences; // enum NumOccurrencesFlag
+   // not using the enum type for 'Value' because zero is an implementation
+   // detail representing the non-value
+-  unsigned Value : 2;
+-  unsigned HiddenFlag : 2; // enum OptionHidden
+-  unsigned Formatting : 2; // enum FormattingFlags
+-  unsigned Misc : 3;
++  unsigned Value;
++  unsigned HiddenFlag; // enum OptionHidden
++  unsigned Formatting; // enum FormattingFlags
++  unsigned Misc;
+   unsigned Position;       // Position of last occurrence of the option
+   unsigned AdditionalVals; // Greater than 0 for multi-valued option.
+   Option *NextRegistered;  // Singly linked list of registered options.
+@@ -200,23 +239,28 @@
+   OptionCategory *Category; // The Category this option belongs to
+ 
+   inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
+-    return (enum NumOccurrencesFlag)Occurrences;
++    return static_cast<enum NumOccurrencesFlag>(Occurrences);
+   }
++
+   inline enum ValueExpected getValueExpectedFlag() const {
+-    return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
++    return Value ?  static_cast<enum ValueExpected>(Value) :
++      static_cast<enum ValueExpected>(getValueExpectedFlagDefault());
+   }
++
+   inline enum OptionHidden getOptionHiddenFlag() const {
+-    return (enum OptionHidden)HiddenFlag;
++    return static_cast<enum OptionHidden>(HiddenFlag);
+   }
++
+   inline enum FormattingFlags getFormattingFlag() const {
+-    return (enum FormattingFlags)Formatting;
++    return static_cast<enum FormattingFlags>(Formatting);
+   }
++
+   inline unsigned getMiscFlags() const { return Misc; }
+   inline unsigned getPosition() const { return Position; }
+   inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
+ 
+   // hasArgStr - Return true if the argstr != ""
+-  bool hasArgStr() const { return ArgStr[0] != 0; }
++  bool hasArgStr() const { return ArgStr && *ArgStr != '\0'; }
+ 
+   //-------------------------------------------------------------------------===
+   // Accessor functions set by OptionModifiers
+@@ -233,16 +277,78 @@
+   void setCategory(OptionCategory &C) { Category = &C; }
+ 
+ protected:
++  Option() : NumOccurrences(0), Occurrences(0), Value(0), HiddenFlag(0),
++  Formatting(0), Misc(0), Position(0), AdditionalVals(0),
++  NextRegistered(0), ArgStr(""), HelpStr(""), ValueStr(""),
++  Category(0) { }
+   explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
+                   enum OptionHidden Hidden)
+-      : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
+-        HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
+-        AdditionalVals(0), NextRegistered(nullptr), ArgStr(""), HelpStr(""),
+-        ValueStr(""), Category(&GeneralCategory) {}
++    : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
++    HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
++    AdditionalVals(0), NextRegistered(nullptr), ArgStr(""), HelpStr(""),
++    ValueStr(""), Category(&GeneralCategory) {}
+ 
+   inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
+ 
+ public:
++  Option(const Option &RHS)
++  : NumOccurrences(RHS.NumOccurrences), Occurrences(RHS.Occurrences),
++  Value(RHS.Value), HiddenFlag(RHS.HiddenFlag),
++  Formatting(RHS.Formatting), Misc(RHS.Misc),
++  Position(RHS.Position), AdditionalVals(RHS.AdditionalVals),
++  NextRegistered(RHS.NextRegistered), ArgStr(RHS.ArgStr),
++  HelpStr(RHS.HelpStr), ValueStr(RHS.ValueStr),
++  Category(RHS.Category) { }
++
++  Option(Option &&RHS)
++  : NumOccurrences(RHS.NumOccurrences), Occurrences(RHS.Occurrences),
++  Value(RHS.Value), HiddenFlag(RHS.HiddenFlag),
++  Formatting(RHS.Formatting), Misc(RHS.Misc),
++  Position(RHS.Position), AdditionalVals(RHS.AdditionalVals),
++  NextRegistered(RHS.NextRegistered), ArgStr(RHS.ArgStr),
++  HelpStr(RHS.HelpStr), ValueStr(RHS.ValueStr),
++  Category(RHS.Category) { }
++
++  Option &operator=(const Option &RHS) {
++    if (this != &RHS) {
++      NumOccurrences = RHS.NumOccurrences;
++      Occurrences = RHS.Occurrences;
++      Value = RHS.Value;
++      HiddenFlag = RHS.HiddenFlag;
++      Formatting = RHS.Formatting;
++      Misc = RHS.Misc;
++      Position = RHS.Position;
++      AdditionalVals = RHS.AdditionalVals;
++      NextRegistered = RHS.NextRegistered;
++      ArgStr = RHS.ArgStr;
++      HelpStr = RHS.HelpStr;
++      ValueStr = RHS.ValueStr;
++      Category = RHS.Category;
++    }
++
++    return *this;
++  }
++
++  const Option &operator=(Option &&RHS) {
++    if (this != &RHS) {
++      NumOccurrences = RHS.NumOccurrences;
++      Occurrences = RHS.Occurrences;
++      Value = RHS.Value;
++      HiddenFlag = RHS.HiddenFlag;
++      Formatting = RHS.Formatting;
++      Misc = RHS.Misc;
++      Position = RHS.Position;
++      AdditionalVals = RHS.AdditionalVals;
++      NextRegistered = RHS.NextRegistered;
++      ArgStr = RHS.ArgStr;
++      HelpStr = RHS.HelpStr;
++      ValueStr = RHS.ValueStr;
++      Category = RHS.Category;
++    }
++
++    return *this;
++  }
++
+   // addArgument - Register this argument with the commandline system.
+   //
+   void addArgument();
+@@ -253,8 +359,20 @@
+   /// For testing purposes only.
+   void removeArgument();
+ 
++  static void registerOption(Option *O) {
++    assert(O && "Invalid argument!");
++
++    O->NextRegistered = RegisteredOptionList;
++    RegisteredOptionList = O;
++    MarkOptionsChanged();
++  }
++
+   Option *getNextRegisteredOption() const { return NextRegistered; }
+ 
++  static Option *getRegisteredOptionList() {
++    return Option::RegisteredOptionList;
++  }
++
+   // Return the width of the option tag for printing...
+   virtual size_t getOptionWidth() const = 0;
+ 
+@@ -265,7 +383,7 @@
+ 
+   virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
+ 
+-  virtual void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
++  virtual void getExtraOptionNames(std::vector<const char*> &V) { }
+ 
+   // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
+   //
+@@ -277,7 +395,7 @@
+ 
+ public:
+   inline int getNumOccurrences() const { return NumOccurrences; }
+-  virtual ~Option() {}
++  virtual ~Option() { }
+ };
+ 
+ //===----------------------------------------------------------------------===//
+@@ -304,29 +422,39 @@
+ // the default constructor for the argument type does not give you what you
+ // want.  This is only valid on "opt" arguments, not on "list" arguments.
+ //
+-template <class Ty> struct initializer {
++template <typename Ty> struct initializer {
+   const Ty &Init;
+-  initializer(const Ty &Val) : Init(Val) {}
+ 
+-  template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
++  initializer(const Ty &Val) : Init(Val) { }
++  initializer(const initializer &RHS) : Init(RHS.Init) { }
++  initializer(initializer &&RHS) : Init(RHS.Init) { }
++
++  template <typename Opt>
++  void apply(Opt &O) const { O.setInitialValue(Init); }
+ };
+ 
+-template <class Ty> initializer<Ty> init(const Ty &Val) {
+-  return initializer<Ty>(Val);
++template<typename Ty>
++initializer<Ty> init(const Ty &Val) {
++  llvm::cl::initializer<Ty> I(Val);
++  return I;
+ }
+ 
+ // location - Allow the user to specify which external variable they want to
+ // store the results of the command line argument processing into, if they don't
+ // want to store it in the option itself.
+ //
+-template <class Ty> struct LocationClass {
++template <typename Ty> struct LocationClass {
+   Ty &Loc;
+-  LocationClass(Ty &L) : Loc(L) {}
+ 
+-  template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
++  LocationClass(Ty &L) : Loc(L) { }
++  LocationClass(const LocationClass &RHS) : Loc(RHS.Loc) { }
++  LocationClass(LocationClass &&RHS) : Loc(RHS.Loc) { }
++
++  template<typename Opt>
++  void apply(Opt &O) const { O.setLocation(O, Loc); }
+ };
+ 
+-template <class Ty> LocationClass<Ty> location(Ty &L) {
++template <typename Ty> LocationClass<Ty> location(Ty &L) {
+   return LocationClass<Ty>(L);
+ }
+ 
+@@ -334,17 +462,22 @@
+ // to.
+ struct cat {
+   OptionCategory &Category;
+-  cat(OptionCategory &c) : Category(c) {}
+ 
+-  template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
++  cat(OptionCategory &c) : Category(c) { }
++  cat(const cat &RHS) : Category(RHS.Category) { }
++  virtual ~cat() { }
++
++  template <typename Opt>
++  void apply(Opt &O) const { O.setCategory(Category); }
+ };
+ 
+ //===----------------------------------------------------------------------===//
+ // OptionValue class
+ 
+ // Support value comparison outside the template.
+-struct GenericOptionValue {
+-  virtual ~GenericOptionValue() {}
++class GenericOptionValue {
++public:
++  virtual ~GenericOptionValue() { }
+   virtual bool compare(const GenericOptionValue &V) const = 0;
+ 
+ private:
+@@ -458,57 +591,6 @@
+ };
+ 
+ //===----------------------------------------------------------------------===//
+-// Enum valued command line option
+-//
+-#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
+-#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
+-#define clEnumValEnd (reinterpret_cast<void *>(0))
+-
+-// values - For custom data types, allow specifying a group of values together
+-// as the values that go into the mapping that the option handler uses.  Note
+-// that the values list must always have a 0 at the end of the list to indicate
+-// that the list has ended.
+-//
+-template <class DataType> class ValuesClass {
+-  // Use a vector instead of a map, because the lists should be short,
+-  // the overhead is less, and most importantly, it keeps them in the order
+-  // inserted so we can print our option out nicely.
+-  SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
+-  void processValues(va_list Vals);
+-
+-public:
+-  ValuesClass(const char *EnumName, DataType Val, const char *Desc,
+-              va_list ValueArgs) {
+-    // Insert the first value, which is required.
+-    Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
+-
+-    // Process the varargs portion of the values...
+-    while (const char *enumName = va_arg(ValueArgs, const char *)) {
+-      DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
+-      const char *EnumDesc = va_arg(ValueArgs, const char *);
+-      Values.push_back(std::make_pair(enumName, // Add value to value map
+-                                      std::make_pair(EnumVal, EnumDesc)));
+-    }
+-  }
+-
+-  template <class Opt> void apply(Opt &O) const {
+-    for (size_t i = 0, e = Values.size(); i != e; ++i)
+-      O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
+-                                     Values[i].second.second);
+-  }
+-};
+-
+-template <class DataType>
+-ValuesClass<DataType> LLVM_END_WITH_NULL
+-values(const char *Arg, DataType Val, const char *Desc, ...) {
+-  va_list ValueArgs;
+-  va_start(ValueArgs, Desc);
+-  ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
+-  va_end(ValueArgs);
+-  return Vals;
+-}
+-
+-//===----------------------------------------------------------------------===//
+ // parser class - Parameterizable parser for different data types.  By default,
+ // known data types (string, int, bool) have specialized parsers, that do what
+ // you would expect.  The default parser, used for data types that are not
+@@ -519,18 +601,23 @@
+ // generic_parser_base - This class holds all the non-generic code that we do
+ // not need replicated for every instance of the generic parser.  This also
+ // allows us to put stuff into CommandLine.cpp
++// Moved here for an obvious reason.
+ //
+ class generic_parser_base {
+ protected:
+   class GenericOptionInfo {
+   public:
+     GenericOptionInfo(const char *name, const char *helpStr)
+-        : Name(name), HelpStr(helpStr) {}
++      : Name(name), HelpStr(helpStr) {}
++    virtual ~GenericOptionInfo() { }
++
+     const char *Name;
+     const char *HelpStr;
+   };
+ 
+ public:
++  generic_parser_base() : hasArgStr(false) { }
++
+   virtual ~generic_parser_base() {} // Base class should have virtual-dtor
+ 
+   // getNumOptions - Virtual function implemented by generic subclass to
+@@ -576,7 +663,7 @@
+     hasArgStr = O.hasArgStr();
+   }
+ 
+-  void getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) {
++  void getExtraOptionNames(std::vector<const char *> &OptionNames) {
+     // If there has been no argstr specified, that means that we need to add an
+     // argument for every possible option.  This ensures that our options are
+     // vectored to us.
+@@ -612,34 +699,48 @@
+   bool hasArgStr;
+ };
+ 
++
+ // Default parser implementation - This implementation depends on having a
+ // mapping of recognized options to values of some sort.  In addition to this,
+ // each entry in the mapping also tracks a help message that is printed with the
+ // command line option for -help.  Because this is a simple mapping parser, the
+ // data type can be any unsupported type.
+ //
+-template <class DataType> class parser : public generic_parser_base {
++template <typename DataType>
++class parser : public generic_parser_base {
+ protected:
+   class OptionInfo : public GenericOptionInfo {
+   public:
+-    OptionInfo(const char *name, DataType v, const char *helpStr)
+-        : GenericOptionInfo(name, helpStr), V(v) {}
++    OptionInfo(const char *Name, DataType DT, const char *helpStr)
++      : GenericOptionInfo(Name, helpStr), V(DT) {}
++    ~OptionInfo() { }
++
+     OptionValue<DataType> V;
+   };
+-  SmallVector<OptionInfo, 8> Values;
++
++  std::vector<OptionInfo> Values;
+ 
+ public:
+   typedef DataType parser_data_type;
+ 
++  parser<DataType>() : generic_parser_base(), Values() { }
++  virtual ~parser<DataType>() { }
++
+   // Implement virtual functions needed by generic_parser_base
+-  unsigned getNumOptions() const override { return unsigned(Values.size()); }
+-  const char *getOption(unsigned N) const override { return Values[N].Name; }
+-  const char *getDescription(unsigned N) const override {
++  virtual unsigned getNumOptions() const override {
++    return static_cast<unsigned>(Values.size());
++  }
++
++  virtual const char *getOption(unsigned N) const override {
++    return Values[N].Name;
++  }
++
++  virtual const char *getDescription(unsigned N) const override {
+     return Values[N].HelpStr;
+   }
+ 
+   // getOptionValue - Return the value of option name N.
+-  const GenericOptionValue &getOptionValue(unsigned N) const override {
++  virtual const GenericOptionValue &getOptionValue(unsigned N) const override {
+     return Values[N].V;
+   }
+ 
+@@ -662,7 +763,7 @@
+ 
+   /// addLiteralOption - Add an entry to the mapping table.
+   ///
+-  template <class DT>
++  template<typename DT>
+   void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
+     assert(findOption(Name) == Values.size() && "Option already exists!");
+     OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
+@@ -670,6 +771,14 @@
+     MarkOptionsChanged();
+   }
+ 
++  void addLiteralOption(const char *Name, const DataType &V,
++                        const char *HelpStr) {
++    assert(findOption(Name) == Values.size() && "Option already exists!");
++    OptionInfo X(Name, V, HelpStr);
++    Values.push_back(X);
++    MarkOptionsChanged();
++  }
++
+   /// removeLiteralOption - Remove the specified option.
+   ///
+   void removeLiteralOption(const char *Name) {
+@@ -679,18 +788,95 @@
+   }
+ };
+ 
++//===----------------------------------------------------------------------===//
++// Enum valued command line option
++//
++#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
++#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
++#define clEnumValEnd (reinterpret_cast<void *>(0))
++
++// values - For custom data types, allow specifying a group of values together
++// as the values that go into the mapping that the option handler uses.  Note
++// that the values list must always have a 0 at the end of the list to indicate
++// that the list has ended.
++//
++template <typename DataType>
++class ValuesClass {
++  // Use a vector instead of a map, because the lists should be short,
++  // the overhead is less, and most importantly, it keeps them in the order
++  // inserted so we can print our option out nicely.
++  std::vector<std::pair<const char*, std::pair<int, const char*> > > Values;
++  void processValues(va_list Vals);
++
++public:
++  ValuesClass(const char *EnumName, DataType Val, const char *Desc,
++              va_list ValueArgs) : Values() {
++    // Insert the first value, which is required.
++    Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
++
++    // Process the varargs portion of the values...
++    while (const char *enumName = va_arg(ValueArgs, const char *)) {
++      DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
++      const char *EnumDesc = va_arg(ValueArgs, const char *);
++
++      Values.push_back(std::make_pair(enumName, // Add value to value map
++                                      std::make_pair(EnumVal, EnumDesc)));
++    }
++  }
++
++  ValuesClass(const ValuesClass &RHS)
++  : Values(RHS.Values) { }
++
++  ValuesClass(ValuesClass &&RHS)
++  : Values(RHS.Values) { }
++
++  ValuesClass &operator=(const ValuesClass &RHS) {
++    if (this != &RHS)
++      Values.operator=(RHS.Values);
++
++    return *this;
++  }
++
++  ValuesClass &operator=(ValuesClass &&RHS) {
++    if (this != &RHS)
++      Values.operator=(RHS.Values);
++
++    return *this;
++  }
++
++  ~ValuesClass() { }
++
++  template <typename Opt> void apply(Opt &O) const {
++    for (size_t i = 0, e = Values.size(); i != e; ++i) {
++      O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
++                                     Values[i].second.second);
++    }
++  }
++};
++
++template <class DataType>
++ValuesClass<DataType> LLVM_END_WITH_NULL
++values(const char *Arg, DataType Val, const char *Desc, ...) {
++  va_list ValueArgs;
++  va_start(ValueArgs, Desc);
++  ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
++  va_end(ValueArgs);
++  return Vals;
++}
++
+ //--------------------------------------------------
+ // basic_parser - Super class of parsers to provide boilerplate code
+ //
+ class basic_parser_impl { // non-template implementation of basic_parser<t>
+ public:
++  basic_parser_impl() { }
+   virtual ~basic_parser_impl() {}
+ 
+   enum ValueExpected getValueExpectedFlagDefault() const {
+     return ValueRequired;
+   }
+ 
+-  void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
++  void getExtraOptionNames(std::vector<const char *> &V) { }
+ 
+   void initialize(Option &) {}
+ 
+@@ -720,10 +906,46 @@
+ // basic_parser - The real basic parser is just a template wrapper that provides
+ // a typedef for the provided data type.
+ //
+-template <class DataType> class basic_parser : public basic_parser_impl {
++template <typename DataType>
++class basic_parser : public basic_parser_impl {
+ public:
++  basic_parser<DataType>() : basic_parser_impl(), Values() { }
++  ~basic_parser<DataType>() { }
++
++  unsigned getNumOptions() const {
++    return static_cast<unsigned>(Values.size());
++  }
++
++  const char *getOption(unsigned I) {
++    assert(I < static_cast<unsigned>(Values.size()) &&
++           "Index is out-of-range!");
++    return Values[I].Name;
++  }
++
++  const char *getDescription(unsigned I) {
++    assert(I < static_cast<unsigned>(Values.size()) &&
++           "Index is out-of-range!");
++    return Values[I].Help;
++  }
++
+   typedef DataType parser_data_type;
+   typedef OptionValue<DataType> OptVal;
++
++protected:
++  template<typename SameDataType>
++  class OptionInfo {
++  public:
++    OptionInfo(const char *NameStr, SameDataType DT, const char *HelpStr)
++    : Name(NameStr), Help(HelpStr), V(DT) { }
++
++    ~OptionInfo() { }
++
++    const char *Name;
++    const char *Help;
++    OptionValue<SameDataType> V;
++  };
++
++  std::vector<OptionInfo<DataType> > Values;
+ };
+ 
+ //--------------------------------------------------
+@@ -733,6 +955,9 @@
+   const char *ArgStr;
+ 
+ public:
++  parser<bool>() : basic_parser<bool>() { }
++  virtual ~parser<bool>() { }
++
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
+ 
+@@ -745,11 +970,17 @@
+   // getValueName - Do not print =<value> at all.
+   const char *getValueName() const override { return nullptr; }
+ 
++  void addLiteralOption(const char *Name, bool V, const char *HelpStr) {
++    OptionInfo<bool> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++    MarkOptionsChanged();
++  }
++
+   void printOptionDiff(const Option &O, bool V, OptVal Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+ EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
+@@ -758,6 +989,9 @@
+ // parser<boolOrDefault>
+ template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
+ public:
++  parser<boolOrDefault>() : basic_parser<boolOrDefault>() { }
++  virtual ~parser<boolOrDefault>() { }
++
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
+ 
+@@ -772,7 +1006,7 @@
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+ EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
+@@ -782,12 +1016,21 @@
+ //
+ template <> class parser<int> : public basic_parser<int> {
+ public:
++  parser<int>() : basic_parser<int>() { }
++  virtual ~parser<int>() { }
++
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
+ 
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "int"; }
+ 
++  void addLiteralOption(const char *Name, int V, const char *HelpStr) {
++    OptionInfo<int> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++    MarkOptionsChanged();
++  }
++
+   void printOptionDiff(const Option &O, int V, OptVal Default,
+                        size_t GlobalWidth) const;
+ 
+@@ -802,12 +1045,21 @@
+ //
+ template <> class parser<unsigned> : public basic_parser<unsigned> {
+ public:
++  parser<unsigned>() : basic_parser<unsigned>() { }
++  virtual ~parser<unsigned>() { }
++
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
+ 
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "uint"; }
+ 
++  void addLiteralOption(const char *Name, unsigned V, const char *HelpStr) {
++    OptionInfo<unsigned> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++    MarkOptionsChanged();
++  }
++
+   void printOptionDiff(const Option &O, unsigned V, OptVal Default,
+                        size_t GlobalWidth) const;
+ 
+@@ -823,6 +1075,9 @@
+ template <>
+ class parser<unsigned long long> : public basic_parser<unsigned long long> {
+ public:
++  parser<unsigned long long>() : basic_parser<unsigned long long>() { }
++  virtual ~parser<unsigned long long>() { }
++
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg,
+              unsigned long long &Val);
+@@ -844,6 +1099,9 @@
+ //
+ template <> class parser<double> : public basic_parser<double> {
+ public:
++  parser<double>() : basic_parser<double>() { }
++  virtual ~parser<double>() { }
++
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
+ 
+@@ -864,6 +1122,9 @@
+ //
+ template <> class parser<float> : public basic_parser<float> {
+ public:
++  parser<float>() : basic_parser<float>() { }
++  virtual ~parser<float>() { }
++
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
+ 
+@@ -884,6 +1145,9 @@
+ //
+ template <> class parser<std::string> : public basic_parser<std::string> {
+ public:
++  parser<std::string>() : basic_parser<std::string>() { }
++  virtual ~parser<std::string>() { }
++
+   // parse - Return true on error.
+   bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
+     Value = Arg.str();
+@@ -893,7 +1157,13 @@
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "string"; }
+ 
+-  void printOptionDiff(const Option &O, StringRef V, OptVal Default,
++  void addLiteralOption(const char *Name, int V, const char *HelpStr) {
++    OptionInfo<std::string> OI(Name, std::to_string(V), HelpStr);
++    Values.push_back(OI);
++    MarkOptionsChanged();
++  }
++
++  void printOptionDiff(const Option &O, const std::string &V, OptVal Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+@@ -907,6 +1177,9 @@
+ //
+ template <> class parser<char> : public basic_parser<char> {
+ public:
++  parser<char>() : basic_parser<char>() { }
++  virtual ~parser<char>() { }
++
+   // parse - Return true on error.
+   bool parse(Option &, StringRef, StringRef Arg, char &Value) {
+     Value = Arg[0];
+@@ -916,6 +1189,12 @@
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "char"; }
+ 
++  void addLiteralOption(const char *Name, char V, const char *HelpStr) {
++    OptionInfo<char> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++    MarkOptionsChanged();
++  }
++
+   void printOptionDiff(const Option &O, char V, OptVal Default,
+                        size_t GlobalWidth) const;
+ 
+@@ -976,8 +1255,9 @@
+ // not correctly respond to the apply method).  Because the syntax to use this
+ // is a pain, we have the 'apply' method below to handle the nastiness...
+ //
+-template <class Mod> struct applicator {
+-  template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
++template <typename Mod> struct applicator {
++  template <typename Opt>
++  static void opt(const Mod &M, Opt &O) { M.apply(O); }
+ };
+ 
+ // Handle const char* as a special case...
+@@ -1039,11 +1319,16 @@
+   }
+ 
+ public:
+-  opt_storage() : Location(nullptr) {}
++  opt_storage() : Location(nullptr), Default() { }
++  opt_storage(const opt_storage &RHS)
++  : Location(RHS.Location), Default(RHS.Default) { }
++  opt_storage(opt_storage &&RHS)
++  : Location(RHS.Location), Default(RHS.Default) { }
+ 
+   bool setLocation(Option &O, DataType &L) {
+     if (Location)
+       return O.error("cl::location(x) specified more than once!");
++
+     Location = &L;
+     Default = L;
+     return false;
+@@ -1077,8 +1362,47 @@
+ template <class DataType>
+ class opt_storage<DataType, false, true> : public DataType {
+ public:
++  opt_storage() : DataType(), Location(nullptr), Default() { }
++  opt_storage(const opt_storage &RHS)
++  : DataType(RHS), Location(RHS.Location), Default(RHS.Default) { }
++  opt_storage(opt_storage &&RHS)
++  : DataType(RHS), Location(RHS.Location), Default(RHS.Default) { }
++
++  opt_storage<DataType, false, true>
++  &operator=(const opt_storage<DataType, false, true> &RHS) {
++    if (this != &RHS) {
++      DataType::operator=(RHS);
++      Location = RHS.Location;
++      Default = RHS.Default;
++    }
++
++    return *this;
++  }
++
++  opt_storage<DataType, false, true>
++  &operator=(opt_storage<DataType, false, true> &&RHS) {
++    if (this != &RHS) {
++      DataType::operator=(RHS);
++      Location = RHS.Location;
++      Default = RHS.Default;
++    }
++
++    return *this;
++  }
++
++
++  DataType *Location;
+   OptionValue<DataType> Default;
+ 
++  bool setLocation(Option &O, DataType &L) {
++    if (Location)
++      return O.error("cl::location(x) specified more than once!");
++
++    Location = &L;
++    Default = L;
++    return false;
++  }
++
+   template <class T> void setValue(const T &V, bool initial = false) {
+     DataType::operator=(V);
+     if (initial)
+@@ -1102,13 +1426,45 @@
+ 
+   // Make sure we initialize the value with the default constructor for the
+   // type.
+-  opt_storage() : Value(DataType()), Default(DataType()) {}
++  opt_storage() : Value(DataType()), Default(DataType()) { }
++  opt_storage(const opt_storage &RHS)
++  : Value(RHS.Value), Default(RHS.Default) { }
++  opt_storage(opt_storage &&RHS)
++  : Value(RHS.Location), Default(RHS.Default) { }
++
++  opt_storage<DataType, false, false>
++  &operator=(const opt_storage<DataType, false, false> &RHS) {
++    if (this != &RHS) {
++      Value = RHS.Value;
++      Default = RHS.Default;
++    }
++
++    return *this;
++  }
++
++  opt_storage<DataType, false, false>
++  &operator=(opt_storage<DataType, false, false> &&RHS) {
++    if (this != &RHS) {
++      Value = RHS.Value;
++      Default = RHS.Default;
++    }
++
++    return *this;
++  }
++
++
++  bool setLocation(Option &O, DataType &L) {
++    Value = L;
++    Default = Value;
++    return false;
++  }
+ 
+   template <class T> void setValue(const T &V, bool initial = false) {
+     Value = V;
+     if (initial)
+       Default = V;
+   }
++
+   DataType &getValue() { return Value; }
+   DataType getValue() const { return Value; }
+ 
+@@ -1123,19 +1479,21 @@
+ //===----------------------------------------------------------------------===//
+ // opt - A scalar command line option.
+ //
+-template <class DataType, bool ExternalStorage = false,
+-          class ParserClass = parser<DataType>>
++template <typename DataType, bool ExternalStorage = false,
++          typename ParserClass = parser<DataType> >
+ class opt : public Option,
+             public opt_storage<DataType, ExternalStorage,
+                                std::is_class<DataType>::value> {
+   ParserClass Parser;
+ 
+-  bool handleOccurrence(unsigned pos, StringRef ArgName,
+-                        StringRef Arg) override {
++protected:
++  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
++                                StringRef Arg) override {
+     typename ParserClass::parser_data_type Val =
+         typename ParserClass::parser_data_type();
+     if (Parser.parse(*this, ArgName, Arg, Val))
+       return true; // Parse error!
++
+     this->setValue(Val);
+     this->setPosition(pos);
+     return false;
+@@ -1145,7 +1503,7 @@
+     return Parser.getValueExpectedFlagDefault();
+   }
+   void
+-  getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
++  getExtraOptionNames(std::vector<const char *> &OptionNames) override {
+     return Parser.getExtraOptionNames(OptionNames);
+   }
+ 
+@@ -1170,11 +1528,33 @@
+   }
+ 
+ public:
++  opt() : Option(), opt_storage<DataType, ExternalStorage,
++                                std::is_class<DataType>::value>(),
++          Parser() { }
++
++  opt(const opt &RHS) : Option(RHS),
++  opt_storage<DataType, ExternalStorage,
++              std::is_class<DataType>::value>(RHS),
++  Parser(RHS.Parser) { }
++
++  ~opt() { }
++
+   // setInitialValue - Used by the cl::init modifier...
+   void setInitialValue(const DataType &V) { this->setValue(V, true); }
+ 
+   ParserClass &getParser() { return Parser; }
+ 
++  bool setLocation(Option &O, DataType &L) {
++    bool R = opt_storage<DataType, ExternalStorage,
++                         std::is_class<DataType>::value>::setLocation(O, L);
++    return R;
++  }
++
++  void addArgument() {
++    assert(!NextRegistered && "argument multiply registered!");
++    Option::registerOption(this);
++  }
++
+   template <class T> DataType &operator=(const T &Val) {
+     this->setValue(Val);
+     return this->getValue();
+@@ -1271,6 +1651,23 @@
+     apply(M7, this);
+     done();
+   }
++  // Nine options...
++  template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
++            class M6t, class M7t, class M8t>
++  opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4,
++      const M5t &M5, const M6t &M6, const M7t &M7, const M8t &M8)
++      : Option(Optional, NotHidden) {
++    apply(M0, this);
++    apply(M1, this);
++    apply(M2, this);
++    apply(M3, this);
++    apply(M4, this);
++    apply(M5, this);
++    apply(M6, this);
++    apply(M7, this);
++    apply(M8, this);
++    done();
++  }
+ };
+ 
+ EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
+@@ -1291,10 +1688,12 @@
+ 
+ public:
+   list_storage() : Location(0) {}
++  virtual ~list_storage() { }
+ 
+   bool setLocation(Option &O, StorageClass &L) {
+     if (Location)
+       return O.error("cl::location(x) specified more than once!");
++
+     Location = &L;
+     return false;
+   }
+@@ -1312,9 +1711,38 @@
+ //
+ template <class DataType>
+ class list_storage<DataType, bool> : public std::vector<DataType> {
++private:
++  list_storage<DataType, bool>(list_storage<DataType, bool> &&RHS) LLVM_DELETED_FUNCTION;
++  list_storage<DataType, bool>
++  &&operator=(list_storage<DataType, bool> &&RHS) LLVM_DELETED_FUNCTION;
++
+ public:
++  list_storage<DataType, bool>() : std::vector<DataType>() { }
++  list_storage<DataType, bool>(const list_storage<DataType, bool> &RHS)
++    : std::vector<DataType>(RHS) { }
++  list_storage<DataType, bool>
++  &operator=(const list_storage<DataType, bool> &RHS) {
++    if (this != &RHS)
++      std::vector<DataType>::operator=(RHS);
++
++    return *this;
++  }
++
++  virtual ~list_storage<DataType, bool>() { }
++
+   template <class T> void addValue(const T &V) {
+-    std::vector<DataType>::push_back(V);
++    T LV(V);
++    this->push_back(LV);
++  }
++
++  void addValue(const DataType &V) {
++    DataType LV(V);
++    std::vector<DataType> &VEC = static_cast<std::vector<DataType>& >(*this);
++    VEC.push_back(LV);
++  }
++
++  const std::vector<DataType> &getStorage() const {
++    return static_cast<const std::vector<DataType>& >(*this);
+   }
+ };
+ 
+@@ -1324,40 +1752,47 @@
+ template <class DataType, class Storage = bool,
+           class ParserClass = parser<DataType>>
+ class list : public Option, public list_storage<DataType, Storage> {
++  friend class Option;
++
+   std::vector<unsigned> Positions;
+   ParserClass Parser;
+ 
+-  enum ValueExpected getValueExpectedFlagDefault() const override {
++protected:
++  virtual enum ValueExpected getValueExpectedFlagDefault() const override {
+     return Parser.getValueExpectedFlagDefault();
+   }
+-  void
+-  getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
++
++  virtual void
++  getExtraOptionNames(std::vector<const char *> &OptionNames) override {
+     return Parser.getExtraOptionNames(OptionNames);
+   }
+ 
+-  bool handleOccurrence(unsigned pos, StringRef ArgName,
+-                        StringRef Arg) override {
++  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
++                                StringRef Arg) override {
+     typename ParserClass::parser_data_type Val =
+         typename ParserClass::parser_data_type();
++
+     if (Parser.parse(*this, ArgName, Arg, Val))
+       return true; // Parse Error!
+-    list_storage<DataType, Storage>::addValue(Val);
++
++    this->addValue(Val);
+     setPosition(pos);
+     Positions.push_back(pos);
+     return false;
+   }
+ 
+   // Forward printing stuff to the parser...
+-  size_t getOptionWidth() const override {
++  virtual size_t getOptionWidth() const override {
+     return Parser.getOptionWidth(*this);
+   }
+-  void printOptionInfo(size_t GlobalWidth) const override {
++
++  virtual void printOptionInfo(size_t GlobalWidth) const override {
+     Parser.printOptionInfo(*this, GlobalWidth);
+   }
+ 
+   // Unimplemented: list options don't currently store their default value.
+-  void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
+-  }
++  virtual void
++  printOptionValue(size_t GlobalWidth, bool Force) const override { }
+ 
+   void done() {
+     addArgument();
+@@ -1365,8 +1800,26 @@
+   }
+ 
+ public:
++  list() : Option(), list_storage<DataType, Storage>(),
++  Positions(), Parser(ParserClass()) { }
++
++  list(const Option &O)
++  : Option(O), list_storage<DataType, Storage>(),
++  Positions(), Parser(ParserClass()) { }
++
++  list(Option *O)
++  : Option(*O), list_storage<DataType, Storage>(),
++  Positions(), Parser(ParserClass()) { }
++
++  ~list() { }
++
+   ParserClass &getParser() { return Parser; }
+ 
++  void addArgument() {
++    assert(!NextRegistered && "argument multiply registered!");
++    Option::registerOption(this);
++  }
++
+   unsigned getPosition(unsigned optnum) const {
+     assert(optnum < this->size() && "Invalid option index");
+     return Positions[optnum];
+@@ -1500,6 +1953,7 @@
+   bool setLocation(Option &O, unsigned &L) {
+     if (Location)
+       return O.error("cl::location(x) specified more than once!");
++
+     Location = &L;
+     return false;
+   }
+@@ -1551,12 +2005,12 @@
+     return Parser.getValueExpectedFlagDefault();
+   }
+   void
+-  getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
++  getExtraOptionNames(std::vector<const char *> &OptionNames) override {
+     return Parser.getExtraOptionNames(OptionNames);
+   }
+ 
+-  bool handleOccurrence(unsigned pos, StringRef ArgName,
+-                        StringRef Arg) override {
++  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
++                                StringRef Arg) override {
+     typename ParserClass::parser_data_type Val =
+         typename ParserClass::parser_data_type();
+     if (Parser.parse(*this, ArgName, Arg, Val))
+@@ -1690,14 +2144,17 @@
+ 
+ class alias : public Option {
+   Option *AliasFor;
+-  bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
+-                        StringRef Arg) override {
++  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
++                                StringRef Arg) override {
++
+     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
+   }
+-  bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
+-                     bool MultiArg = false) override {
++
++  virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
++                             bool MultiArg = false) override {
+     return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
+   }
++
+   // Handle printing stuff...
+   size_t getOptionWidth() const override;
+   void printOptionInfo(size_t GlobalWidth) const override;
+@@ -1847,7 +2304,7 @@
+ /// lines and end of the response file to be marked with a nullptr string.
+ /// \param [out] NewArgv All parsed strings are appended to NewArgv.
+ void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
+-                            SmallVectorImpl<const char *> &NewArgv,
++                            std::vector<const char *> &NewArgv,
+                             bool MarkEOLs = false);
+ 
+ /// \brief Tokenizes a Windows command line which may contain quotes and escaped
+@@ -1862,13 +2319,13 @@
+ /// lines and end of the response file to be marked with a nullptr string.
+ /// \param [out] NewArgv All parsed strings are appended to NewArgv.
+ void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
+-                                SmallVectorImpl<const char *> &NewArgv,
++                                std::vector<const char *> &NewArgv,
+                                 bool MarkEOLs = false);
+ 
+ /// \brief String tokenization function type.  Should be compatible with either
+ /// Windows or Unix command line tokenizers.
+ typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
+-                                  SmallVectorImpl<const char *> &NewArgv,
++                                  std::vector<const char *> &NewArgv,
+                                   bool MarkEOLs);
+ 
+ /// \brief Expand response files on a command line recursively using the given
+@@ -1886,7 +2343,7 @@
+ /// with nullptrs in the Argv vector.
+ /// \return true if all @files were expanded successfully or there were none.
+ bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
+-                         SmallVectorImpl<const char *> &Argv,
++                         std::vector<const char *> &Argv,
+                          bool MarkEOLs = false);
+ 
+ } // End namespace cl
+--- include/llvm/Support/FileSystem.h	2014-12-15 19:10:29.000000000 -0800
++++ include/llvm/Support/FileSystem.h	2016-01-24 21:14:49.000000000 -0800
+@@ -680,10 +680,35 @@
+ 
+ public:
+   explicit directory_entry(const Twine &path, file_status st = file_status())
+-    : Path(path.str())
+-    , Status(st) {}
++    : Path(path.str()), Status(st) { }
+ 
+-  directory_entry() {}
++  directory_entry() : Path(""), Status(file_status()) { }
++
++  directory_entry(const directory_entry &rhs)
++  : Path(rhs.Path), Status(rhs.Status) { }
++
++  directory_entry(directory_entry &&rhs)
++  : Path(rhs.Path), Status(rhs.Status) { }
++
++  ~directory_entry() { }
++
++  directory_entry &operator=(const directory_entry &rhs) {
++    if (this != &rhs) {
++      Path = rhs.Path;
++      Status = rhs.Status;
++    }
++
++    return *this;
++  }
++
++  directory_entry &operator=(directory_entry &&rhs) {
++    if (this != &rhs) {
++      Path = rhs.Path;
++      Status = rhs.Status;
++    }
++
++    return *this;
++  }
+ 
+   void assign(const Twine &path, file_status st = file_status()) {
+     Path = path.str();
+--- include/llvm/Support/PluginLoader.h	2007-12-29 11:59:42.000000000 -0800
++++ include/llvm/Support/PluginLoader.h	2016-01-24 11:01:53.000000000 -0800
+@@ -22,6 +22,8 @@
+ namespace llvm {
+   struct PluginLoader {
+     void operator=(const std::string &Filename);
++    bool operator==(const std::string &Filename) const;
++    bool operator!=(const std::string &Filename) const;
+     static unsigned getNumPlugins();
+     static std::string& getPlugin(unsigned num);
+   };
+--- utils/TableGen/AsmMatcherEmitter.cpp	2015-01-03 00:16:29.000000000 -0800
++++ utils/TableGen/AsmMatcherEmitter.cpp	2016-01-26 14:57:52.000000000 -0800
+@@ -121,7 +121,7 @@
+ #define DEBUG_TYPE "asm-matcher-emitter"
+ 
+ static cl::opt<std::string>
+-MatchPrefix("match-prefix", cl::init(""),
++MatchPrefix("match-prefix", cl::init(std::string("")),
+             cl::desc("Only match instructions with the given prefix"));
+ 
+ namespace {
+--- tools/llc/llc.cpp	2014-12-11 23:52:06.000000000 -0800
++++ tools/llc/llc.cpp	2016-01-26 14:44:02.000000000 -0800
+@@ -50,13 +50,14 @@
+ // and back-end code generation options are specified with the target machine.
+ //
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
++InputFilename(cl::Positional, cl::desc("<input bitcode>"),
++              cl::init(std::string("-")));
+ 
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
+ 
+ static cl::opt<unsigned>
+-TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
++TimeCompilations("time-compilations", cl::Hidden, cl::init(1U),
+                  cl::value_desc("N"),
+                  cl::desc("Repeat compilation N times for timing"));
+ 
+@@ -65,13 +66,15 @@
+                       cl::desc("Disable integrated assembler"));
+ 
+ // Determine optimization level.
++// ORIGINAL:
+ static cl::opt<char>
+ OptLevel("O",
+          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
+                   "(default = '-O2')"),
+          cl::Prefix,
+-         cl::ZeroOrMore,
+-         cl::init(' '));
++         cl::Optional,
++         cl::ValueRequired,
++         cl::init('2'));
+ 
+ static cl::opt<std::string>
+ TargetTriple("mtriple", cl::desc("Override target triple for module"));
+--- tools/llvm-as/llvm-as.cpp	2014-08-25 11:16:47.000000000 -0700
++++ tools/llvm-as/llvm-as.cpp	2016-01-26 15:07:18.000000000 -0800
+@@ -15,6 +15,8 @@
+ //
+ //===----------------------------------------------------------------------===//
+ 
++#include "llvm/Support/CommandLine.h"
++
+ #include "llvm/IR/LLVMContext.h"
+ #include "llvm/AsmParser/Parser.h"
+ #include "llvm/Bitcode/ReaderWriter.h"
+@@ -28,11 +30,21 @@
+ #include "llvm/Support/SourceMgr.h"
+ #include "llvm/Support/SystemUtils.h"
+ #include "llvm/Support/ToolOutputFile.h"
+-#include <memory>
+ using namespace llvm;
+ 
++#include <memory>
++#include <string>
++
++static cl::opt<std::string>
++HiddenOption("h", cl::Hidden, cl::desc("hidden option"),
++             cl::init(""));
++
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input .llvm file>"), cl::init("-"));
++InputFilename(cl::Positional, cl::desc("<input file>"),
++              cl::NotHidden,
++              cl::Optional,
++              cl::init(std::string("-")),
++              cl::ValuePositionalNoArgs);
+ 
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Override output filename"),
+--- tools/llvm-dis/llvm-dis.cpp	2015-01-09 16:07:30.000000000 -0800
++++ tools/llvm-dis/llvm-dis.cpp	2016-02-01 12:08:04.531107200 -0800
+@@ -38,7 +38,8 @@
+ using namespace llvm;
+ 
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
++InputFilename(cl::Positional, cl::desc("<input bitcode>"),
++              cl::init(std::string("-")));
+ 
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Override output filename"),
+--- tools/bugpoint/OptimizerDriver.cpp	2014-11-07 13:30:36.000000000 -0800
++++ tools/bugpoint/OptimizerDriver.cpp	2016-01-26 15:51:53.000000000 -0800
+@@ -46,7 +46,7 @@
+   // ChildOutput - This option captures the name of the child output file that
+   // is set up by the parent bugpoint process
+   cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden);
+-  cl::opt<std::string> OptCmd("opt-command", cl::init(""),
++  cl::opt<std::string> OptCmd("opt-command", cl::init(std::string("")),
+                               cl::desc("Path to opt. (default: search path "
+                                        "for 'opt'.)"));
+ }
+--- tools/opt/opt.cpp	2014-12-11 23:52:14.000000000 -0800
++++ tools/opt/opt.cpp	2016-01-26 14:43:37.000000000 -0800
+@@ -72,7 +72,7 @@
+ //
+ static cl::opt<std::string>
+ InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
+-    cl::init("-"), cl::value_desc("filename"));
++    cl::init(std::string("-")), cl::value_desc("filename"));
+ 
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Override output filename"),
+@@ -175,7 +175,7 @@
+ static cl::opt<std::string>
+ DefaultDataLayout("default-data-layout",
+           cl::desc("data layout string to use if not specified by module"),
+-          cl::value_desc("layout-string"), cl::init(""));
++          cl::value_desc("layout-string"), cl::init(std::string("")));
+ 
+ 
+ 
+--- unittests/Support/CommandLineTest.cpp	2014-08-22 12:29:17.000000000 -0700
++++ unittests/Support/CommandLineTest.cpp	2016-01-27 11:20:39.000000000 -0800
+@@ -7,12 +7,17 @@
+ //
+ //===----------------------------------------------------------------------===//
+ 
++#ifndef SKIP_ENVIRONMENT_TESTS
++#define SKIP_ENVIRONMENT_TESTS 1
++#endif
++
+ #include "llvm/ADT/STLExtras.h"
+ #include "llvm/Config/config.h"
+ #include "llvm/Support/CommandLine.h"
+ #include "gtest/gtest.h"
+ #include <stdlib.h>
+ #include <string>
++#include <vector>
+ 
+ using namespace llvm;
+ 
+@@ -47,21 +52,23 @@
+   typedef cl::opt<T> Base;
+ public:
+   // One option...
+-  template<class M0t>
+-  explicit StackOption(const M0t &M0) : Base(M0) {}
++  template<typename T0>
++  explicit StackOption(const T0 &M0) : cl::opt<T>(M0) { }
+ 
+   // Two options...
+-  template<class M0t, class M1t>
+-  StackOption(const M0t &M0, const M1t &M1) : Base(M0, M1) {}
++  template<typename T0, typename T1>
++  explicit StackOption(const T0 &M0, const T1 &M1) : cl::opt<T>(M0, M1) { }
+ 
+   // Three options...
+-  template<class M0t, class M1t, class M2t>
+-  StackOption(const M0t &M0, const M1t &M1, const M2t &M2) : Base(M0, M1, M2) {}
++  template<typename T0, typename T1, typename T2>
++  explicit StackOption(const T0 &M0, const T1 &M1, const T2 &M2)
++  : cl::opt<T>(M0, M1, M2) { }
+ 
+   // Four options...
+-  template<class M0t, class M1t, class M2t, class M3t>
+-  StackOption(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
+-    : Base(M0, M1, M2, M3) {}
++  template<typename T0, typename T1, typename T2, typename T3>
++  explicit StackOption(const T0 &M0, const T1 &M1,
++                       const T2 &M2, const T3 &M3)
++  : cl::opt<T>(M0, M1, M2, M3) { }
+ 
+   ~StackOption() {
+     this->removeArgument();
+@@ -112,7 +119,7 @@
+ 
+ const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS";
+ 
+-cl::opt<std::string> EnvironmentTestOption("env-test-opt");
++static cl::opt<std::string> EnvironmentTestOption("env-test-opt");
+ TEST(CommandLineTest, ParseEnvironment) {
+   TempEnvVar TEV(test_env_var, "-env-test-opt=hello");
+   EXPECT_EQ("", EnvironmentTestOption);
+@@ -153,12 +160,13 @@
+ };
+ 
+ typedef void ParserFunction(StringRef Source, llvm::cl::StringSaver &Saver,
+-                            SmallVectorImpl<const char *> &NewArgv,
++                            std::vector<const char*> &NewArgv,
+                             bool MarkEOLs);
+ 
+ void testCommandLineTokenizer(ParserFunction *parse, const char *Input,
+-                              const char *const Output[], size_t OutputSize) {
+-  SmallVector<const char *, 0> Actual;
++                              std::vector<const char*> &Output,
++                              size_t OutputSize) {
++  std::vector<const char*> Actual;
+   StrDupSaver Saver;
+   parse(Input, Saver, Actual, /*MarkEOLs=*/false);
+   EXPECT_EQ(OutputSize, Actual.size());
+@@ -175,7 +183,12 @@
+   const char *const Output[] = { "foo bar", "foo bar", "foo bar", "foo\\bar",
+                                  "foobarbaz", "C:\\src\\foo.cpp",
+                                  "C:\\src\\foo.cpp" };
+-  testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
++
++  std::vector<const char*> OutputVector;
++  for (unsigned I = 0; I < array_lengthof(Output); ++I)
++    OutputVector.push_back(Output[I]);
++
++  testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, OutputVector,
+                            array_lengthof(Output));
+ }
+ 
+@@ -184,10 +197,17 @@
+                       "\"st \\\"u\" \\v";
+   const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
+                                  "lmn", "o", "pqr", "st \"u", "\\v" };
+-  testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
++
++  std::vector<const char*> OutputVector;
++  for (unsigned I = 0; I < array_lengthof(Output); ++I)
++    OutputVector.push_back(Output[I]);
++
++  testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, OutputVector,
+                            array_lengthof(Output));
+ }
+ 
++#ifndef ALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
++// This test case is 100% broken.
+ TEST(CommandLineTest, AliasesWithArguments) {
+   static const size_t ARGC = 3;
+   const char *const Inputs[][ARGC] = {
+@@ -201,7 +221,6 @@
+     StackOption<std::string> Actual("actual");
+     StackOption<bool> Extra("extra");
+     StackOption<std::string> Input(cl::Positional);
+-
+     cl::alias Alias("alias", llvm::cl::aliasopt(Actual));
+ 
+     cl::ParseCommandLineOptions(ARGC, Inputs[i]);
+@@ -211,6 +230,7 @@
+     Alias.removeArgument();
+   }
+ }
++#endif
+ 
+ void testAliasRequired(int argc, const char *const *argv) {
+   StackOption<std::string> Option("option", cl::Required);
+--- utils/FileCheck/FileCheck.cpp	2014-11-18 18:56:00.000000000 -0800
++++ utils/FileCheck/FileCheck.cpp	2016-02-01 13:52:04.699904440 -0800
+@@ -40,7 +40,8 @@
+ 
+ static cl::opt<std::string>
+ InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
+-              cl::init("-"), cl::value_desc("filename"));
++              cl::value_desc("filename"),
++              cl::init(std::string("-")));
+ 
+ static cl::list<std::string>
+ CheckPrefixes("check-prefix",
+--- include/llvm/LinkAllPasses.h	2015-01-14 03:23:27.000000000 -0800
++++ include/llvm/LinkAllPasses.h	2016-02-01 09:24:47.493918163 -0800
+@@ -15,6 +15,7 @@
+ #ifndef LLVM_LINKALLPASSES_H
+ #define LLVM_LINKALLPASSES_H
+ 
++#include "llvm/Analysis/AliasAnalysis.h"
+ #include "llvm/Analysis/AliasSetTracker.h"
+ #include "llvm/Analysis/CallPrinter.h"
+ #include "llvm/Analysis/DomPrinter.h"
+@@ -35,10 +36,12 @@
+ #include "llvm/Transforms/Utils/SymbolRewriter.h"
+ #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
+ #include "llvm/Transforms/Vectorize.h"
++
+ #include <cstdlib>
+ 
+ namespace {
+   struct ForcePassLinking {
++    __attribute__((used, noinline))
+     ForcePassLinking() {
+       // We must reference the passes in such a way that compilers will not
+       // delete it all as dead code, even with whole program optimization,
+@@ -47,6 +50,8 @@
+       if (std::getenv("bar") != (char*) -1)
+         return;
+ 
++      asm("");
++
+       (void) llvm::createAAEvalPass();
+       (void) llvm::createAggressiveDCEPass();
+       (void) llvm::createAliasAnalysisCounterPass();
+@@ -148,9 +153,13 @@
+       (void) llvm::createMetaRenamerPass();
+       (void) llvm::createFunctionAttrsPass();
+       (void) llvm::createMergeFunctionsPass();
+-      (void) llvm::createPrintModulePass(*(llvm::raw_ostream*)nullptr);
+-      (void) llvm::createPrintFunctionPass(*(llvm::raw_ostream*)nullptr);
+-      (void) llvm::createPrintBasicBlockPass(*(llvm::raw_ostream*)nullptr);
++
++      std::string S;
++      llvm::raw_string_ostream RSO(S);
++
++      (void) llvm::createPrintModulePass(RSO);
++      (void) llvm::createPrintFunctionPass(RSO);
++      (void) llvm::createPrintBasicBlockPass(RSO);
+       (void) llvm::createModuleDebugInfoPrinterPass();
+       (void) llvm::createPartialInliningPass();
+       (void) llvm::createLintPass();
+@@ -167,13 +176,20 @@
+       (void) llvm::createSeparateConstOffsetFromGEPPass();
+       (void) llvm::createRewriteSymbolsPass();
+ 
+-      (void)new llvm::IntervalPartition();
+-      (void)new llvm::ScalarEvolution();
+-      ((llvm::Function*)nullptr)->viewCFGOnly();
++      llvm::IntervalPartition *LIP = new llvm::IntervalPartition();
++      (void) LIP;
++
++      llvm::ScalarEvolution *LSE = new llvm::ScalarEvolution();
++      (void) LSE;
++
++      llvm::Function *F =
++        llvm::Function::Create(nullptr, llvm::GlobalValue::ExternalLinkage);
++      F->viewCFGOnly();
++
+       llvm::RGPassManager RGM;
+-      ((llvm::RegionPass*)nullptr)->runOnRegion((llvm::Region*)nullptr, RGM);
+-      llvm::AliasSetTracker X(*(llvm::AliasAnalysis*)nullptr);
+-      X.add(nullptr, 0, llvm::AAMDNodes()); // for -print-alias-sets
++      llvm::AliasAnalysis LAA;
++      llvm::AliasSetTracker LAST(LAA);
++      LAST.add(nullptr, 0, llvm::AAMDNodes()); // for -print-alias-sets
+     }
+   } ForcePassLinking; // Force link by creating a global definition.
+ }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/017-lli-21870067.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,229 @@
+# 21870067 lli makes incorrect assumptions about anonymous namespace instantiation order
+# 21870087 naming convention for the InputFile key is inconsistent across LLVM utilities
+# For upstream - maybe.
+--- tools/lli/lli.cpp	2014-12-02 16:51:19.000000000 -0800
++++ tools/lli/lli.cpp	2015-09-20 10:37:39.445573121 -0700
+@@ -63,21 +63,22 @@
+ 
+ #define DEBUG_TYPE "lli"
+ 
+-namespace {
+-  cl::opt<std::string>
++static cl::opt<std::string>
+   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
+ 
+-  cl::list<std::string>
++static cl::list<std::string>
+   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
+ 
+-  cl::opt<bool> ForceInterpreter("force-interpreter",
++static cl::opt<bool>
++ForceInterpreter("force-interpreter",
+                                  cl::desc("Force interpretation: disable JIT"),
+                                  cl::init(false));
+ 
+   // The MCJIT supports building for a target address space separate from
+   // the JIT compilation process. Use a forked process and a copying
+   // memory manager with IPC to execute using this functionality.
+-  cl::opt<bool> RemoteMCJIT("remote-mcjit",
++static cl::opt<bool>
++RemoteMCJIT("remote-mcjit",
+     cl::desc("Execute MCJIT'ed code in a separate process."),
+     cl::init(false));
+ 
+@@ -85,7 +86,7 @@
+   // the simulated remote execution that allocates address space for child
+   // execution. The child process will be executed and will communicate with
+   // lli via stdin/stdout pipes.
+-  cl::opt<std::string>
++static cl::opt<std::string>
+   ChildExecPath("mcjit-remote-process",
+                 cl::desc("Specify the filename of the process to launch "
+                          "for remote MCJIT execution.  If none is specified,"
+@@ -93,7 +94,7 @@
+                 cl::value_desc("filename"), cl::init(""));
+ 
+   // Determine optimization level.
+-  cl::opt<char>
++static cl::opt<char>
+   OptLevel("O",
+            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
+                     "(default = '-O2')"),
+@@ -101,73 +102,73 @@
+            cl::ZeroOrMore,
+            cl::init(' '));
+ 
+-  cl::opt<std::string>
++static cl::opt<std::string>
+   TargetTriple("mtriple", cl::desc("Override target triple for module"));
+ 
+-  cl::opt<std::string>
++static cl::opt<std::string>
+   MArch("march",
+         cl::desc("Architecture to generate assembly for (see --version)"));
+ 
+-  cl::opt<std::string>
++static cl::opt<std::string>
+   MCPU("mcpu",
+        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
+        cl::value_desc("cpu-name"),
+        cl::init(""));
+ 
+-  cl::list<std::string>
++static cl::list<std::string>
+   MAttrs("mattr",
+          cl::CommaSeparated,
+          cl::desc("Target specific attributes (-mattr=help for details)"),
+          cl::value_desc("a1,+a2,-a3,..."));
+ 
+-  cl::opt<std::string>
++static cl::opt<std::string>
+   EntryFunc("entry-function",
+             cl::desc("Specify the entry function (default = 'main') "
+                      "of the executable"),
+             cl::value_desc("function"),
+             cl::init("main"));
+ 
+-  cl::list<std::string>
++static cl::list<std::string>
+   ExtraModules("extra-module",
+          cl::desc("Extra modules to be loaded"),
+          cl::value_desc("input bitcode"));
+ 
+-  cl::list<std::string>
++static cl::list<std::string>
+   ExtraObjects("extra-object",
+          cl::desc("Extra object files to be loaded"),
+          cl::value_desc("input object"));
+ 
+-  cl::list<std::string>
++static cl::list<std::string>
+   ExtraArchives("extra-archive",
+          cl::desc("Extra archive files to be loaded"),
+          cl::value_desc("input archive"));
+ 
+-  cl::opt<bool>
++static cl::opt<bool>
+   EnableCacheManager("enable-cache-manager",
+         cl::desc("Use cache manager to save/load mdoules"),
+         cl::init(false));
+ 
+-  cl::opt<std::string>
++static cl::opt<std::string>
+   ObjectCacheDir("object-cache-dir",
+                   cl::desc("Directory to store cached object files "
+                            "(must be user writable)"),
+                   cl::init(""));
+ 
+-  cl::opt<std::string>
++static cl::opt<std::string>
+   FakeArgv0("fake-argv0",
+             cl::desc("Override the 'argv[0]' value passed into the executing"
+                      " program"), cl::value_desc("executable"));
+ 
+-  cl::opt<bool>
++static cl::opt<bool>
+   DisableCoreFiles("disable-core-files", cl::Hidden,
+                    cl::desc("Disable emission of core files if possible"));
+ 
+-  cl::opt<bool>
++static cl::opt<bool>
+   NoLazyCompilation("disable-lazy-compilation",
+                   cl::desc("Disable JIT lazy compilation"),
+                   cl::init(false));
+ 
+-  cl::opt<Reloc::Model>
++static cl::opt<Reloc::Model>
+   RelocModel("relocation-model",
+              cl::desc("Choose relocation model"),
+              cl::init(Reloc::Default),
+@@ -182,7 +183,7 @@
+                        "Relocatable external references, non-relocatable code"),
+             clEnumValEnd));
+ 
+-  cl::opt<llvm::CodeModel::Model>
++static cl::opt<llvm::CodeModel::Model>
+   CMModel("code-model",
+           cl::desc("Choose code model"),
+           cl::init(CodeModel::JITDefault),
+@@ -198,12 +199,12 @@
+                                 "Large code model"),
+                      clEnumValEnd));
+ 
+-  cl::opt<bool>
++static cl::opt<bool>
+   GenerateSoftFloatCalls("soft-float",
+     cl::desc("Generate software floating point library calls"),
+     cl::init(false));
+ 
+-  cl::opt<llvm::FloatABI::ABIType>
++static cl::opt<llvm::FloatABI::ABIType>
+   FloatABIForCalls("float-abi",
+                    cl::desc("Choose float ABI type"),
+                    cl::init(FloatABI::Default),
+@@ -215,7 +216,7 @@
+                      clEnumValN(FloatABI::Hard, "hard",
+                                 "Hard float ABI (uses FP registers)"),
+                      clEnumValEnd));
+-  cl::opt<bool>
++static cl::opt<bool>
+ // In debug builds, make this default to true.
+ #ifdef NDEBUG
+ #define EMIT_DEBUG false
+@@ -232,7 +233,6 @@
+     cl::Hidden,
+     cl::desc("Emit debug info objfiles to disk"),
+     cl::init(false));
+-}
+ 
+ //===----------------------------------------------------------------------===//
+ // Object cache
+--- tools/lli/lli.cpp	2015-10-05 11:01:32.000000000 -0700
++++ tools/lli/lli.cpp	2016-01-26 14:44:39.000000000 -0800
+@@ -64,7 +64,8 @@
+ #define DEBUG_TYPE "lli"
+ 
+ static cl::opt<std::string>
+-  InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
++  InputFile(cl::desc("<input bitcode>"), cl::Positional,
++            cl::init(std::string("-")));
+ 
+ static cl::list<std::string>
+   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
+@@ -91,7 +92,8 @@
+                 cl::desc("Specify the filename of the process to launch "
+                          "for remote MCJIT execution.  If none is specified,"
+                          "\n\tremote execution will be simulated in-process."),
+-                cl::value_desc("filename"), cl::init(""));
++                cl::value_desc("filename"),
++                cl::init(std::string("")));
+ 
+   // Determine optimization level.
+ static cl::opt<char>
+@@ -113,7 +115,7 @@
+   MCPU("mcpu",
+        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
+        cl::value_desc("cpu-name"),
+-       cl::init(""));
++       cl::init(std::string("")));
+ 
+ static cl::list<std::string>
+   MAttrs("mattr",
+@@ -126,7 +128,7 @@
+             cl::desc("Specify the entry function (default = 'main') "
+                      "of the executable"),
+             cl::value_desc("function"),
+-            cl::init("main"));
++            cl::init(std::string("main")));
+ 
+ static cl::list<std::string>
+   ExtraModules("extra-module",
+@@ -152,7 +154,7 @@
+   ObjectCacheDir("object-cache-dir",
+                   cl::desc("Directory to store cached object files "
+                            "(must be user writable)"),
+-                  cl::init(""));
++                  cl::init(std::string("")));
+ 
+ static cl::opt<std::string>
+   FakeArgv0("fake-argv0",
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/018-21870283-llvm-GetArgumentVector.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,49 @@
+# 21870283 - llvm::sys::Process::GetArgumentVector should overload
+# for std::vector
+# For upstream - maybe.
+--- include/llvm/Support/Process.h	2014-12-04 08:59:36.000000000 -0800
++++ include/llvm/Support/Process.h	2015-09-20 16:56:49.207515143 -0700
+@@ -81,20 +81,26 @@
+                                              const std::string& FileName);
+ 
+   /// This function returns a SmallVector containing the arguments passed from
+   /// the operating system to the program.  This function expects to be handed
+   /// the vector passed in from main.
+   static std::error_code
+   GetArgumentVector(SmallVectorImpl<const char *> &Args,
+                     ArrayRef<const char *> ArgsFromMain,
+                     SpecificBumpPtrAllocator<char> &ArgAllocator);
+ 
++  /// Overload the above for a std::vector, and without the
++  // useless SpecificBumpPtrAllocator argument.
++  static std::error_code
++  GetArgumentVector(std::vector<const char *> &ArgsOut,
++                    ArrayRef<const char *> ArgsIn);
++
+   // This functions ensures that the standard file descriptors (input, output,
+   // and error) are properly mapped to a file descriptor before we use any of
+   // them.  This should only be called by standalone programs, library
+   // components should not call this.
+   static std::error_code FixupStandardFileDescriptors();
+ 
+   // This function safely closes a file descriptor.  It is not safe to retry
+   // close(2) when it returns with errno equivalent to EINTR; this is because
+   // *nixen cannot agree if the file descriptor is, in fact, closed when this
+   // occurs.
+--- lib/Support/Unix/Process.inc	2014-12-04 08:59:36.000000000 -0800
++++ lib/Support/Unix/Process.inc	2015-09-20 17:11:29.527153186 -0700
+@@ -180,6 +180,14 @@
+   return std::error_code();
+ }
+ 
++std::error_code
++Process::GetArgumentVector(std::vector<const char *> &ArgsOut,
++                           ArrayRef<const char *> ArgsIn) {
++  ArgsOut.insert(ArgsOut.end(), ArgsIn.begin(), ArgsIn.end());
++
++  return std::error_code();
++}
++
+ namespace {
+ class FDCloser {
+ public:
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/019-21870099-clang.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,174 @@
+# 21870099 - 128 bytes for a filesystem path is definitely not enough
+# 21870283 - llvm::sys::Process::GetArgumentVector should overload for
+# std::vector
+# For upstream - maybe.
+--- tools/clang/tools/driver/driver.cpp	2015-09-20 11:19:37.402058833 -0700
++++ tools/clang/tools/driver/driver.cpp	2015-09-20 17:00:21.850124658 -0700
+@@ -89,21 +89,21 @@
+ ///  and the following argument.
+ ///
+ ///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
+ ///  at the end of the command line.
+ ///
+ /// \param OS - The stream to write edit information to.
+ /// \param Args - The vector of command line arguments.
+ /// \param Edit - The override command to perform.
+ /// \param SavedStrings - Set to use for storing string representations.
+ static void ApplyOneQAOverride(raw_ostream &OS,
+-                               SmallVectorImpl<const char*> &Args,
++                               std::vector<const char*> &Args,
+                                StringRef Edit,
+                                std::set<std::string> &SavedStrings) {
+   // This does not need to be efficient.
+ 
+   if (Edit[0] == '^') {
+     const char *Str =
+       GetStableCStr(SavedStrings, Edit.substr(1));
+     OS << "### Adding argument " << Str << " at beginning\n";
+     Args.insert(Args.begin() + 1, Str);
+   } else if (Edit[0] == '+') {
+@@ -161,21 +161,21 @@
+     }
+     OS << "### Adding argument " << Edit << " at end\n";
+     Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
+   } else {
+     OS << "### Unrecognized edit: " << Edit << "\n";
+   }
+ }
+ 
+ /// ApplyQAOverride - Apply a comma separate list of edits to the
+ /// input argument lists. See ApplyOneQAOverride.
+-static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
++static void ApplyQAOverride(std::vector<const char*> &Args,
+                             const char *OverrideStr,
+                             std::set<std::string> &SavedStrings) {
+   raw_ostream *OS = &llvm::errs();
+ 
+   if (OverrideStr[0] == '#') {
+     ++OverrideStr;
+     OS = &llvm::nulls();
+   }
+ 
+   *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
+@@ -223,21 +223,21 @@
+       {"cl", "--driver-mode=cl"},
+       {"++", "--driver-mode=g++"},
+   };
+ 
+   for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i)
+     if (ProgName.endswith(DriverSuffixes[i].Suffix))
+       return &DriverSuffixes[i];
+   return nullptr;
+ }
+ 
+-static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
++static void ParseProgName(std::vector<const char *> &ArgVector,
+                           std::set<std::string> &SavedStrings) {
+   // Try to infer frontend type and default target from the program name by
+   // comparing it against DriverSuffixes in order.
+ 
+   // If there is a match, the function tries to identify a target as prefix.
+   // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
+   // prefix "x86_64-linux". If such a target prefix is found, is gets added via
+   // -target as implicit first argument.
+ 
+   std::string ProgName =llvm::sys::path::stem(ArgVector[0]);
+@@ -325,39 +325,40 @@
+   // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
+   StringRef ExeBasename(llvm::sys::path::filename(Path));
+   if (ExeBasename.equals_lower("cl.exe"))
+     ExeBasename = "clang-cl.exe";
+   DiagClient->setPrefix(ExeBasename);
+ }
+ 
+ // This lets us create the DiagnosticsEngine with a properly-filled-out
+ // DiagnosticOptions instance.
+ static DiagnosticOptions *
+-CreateAndPopulateDiagOpts(SmallVectorImpl<const char *> &argv) {
+-  auto *DiagOpts = new DiagnosticOptions;
++CreateAndPopulateDiagOpts(std::vector<const char *> &argv) {
++  auto *DiagOpts = new DiagnosticOptions();
+   std::unique_ptr<OptTable> Opts(createDriverOptTable());
+   unsigned MissingArgIndex, MissingArgCount;
+   std::unique_ptr<InputArgList> Args(Opts->ParseArgs(
+-      argv.begin() + 1, argv.end(), MissingArgIndex, MissingArgCount));
++      argv.data() + 1, argv.data() + argv.size(), MissingArgIndex,
++      MissingArgCount));
+   // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
+   // Any errors that would be diagnosed here will also be diagnosed later,
+   // when the DiagnosticsEngine actually exists.
+   (void) ParseDiagnosticArgs(*DiagOpts, *Args);
+   return DiagOpts;
+ }
+ 
+-static void SetInstallDir(SmallVectorImpl<const char *> &argv,
++static void SetInstallDir(std::vector<const char *> &argv,
+                           Driver &TheDriver) {
+   // Attempt to find the original path used to invoke the driver, to determine
+   // the installed path. We do this manually, because we want to support that
+   // path being a symlink.
+-  SmallString<128> InstalledPath(argv[0]);
++  SmallString<PATH_MAX> InstalledPath(argv[0]);
+ 
+   // Do a PATH lookup, if there are no directory components.
+   if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
+     if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
+             llvm::sys::path::filename(InstalledPath.str())))
+       InstalledPath = *Tmp;
+   llvm::sys::fs::make_absolute(InstalledPath);
+   InstalledPath = llvm::sys::path::parent_path(InstalledPath);
+   if (llvm::sys::fs::exists(InstalledPath.c_str()))
+     TheDriver.setInstalledDir(InstalledPath);
+@@ -375,24 +376,26 @@
+   return 1;
+ }
+ 
+ int main(int argc_, const char **argv_) {
+   llvm::sys::PrintStackTraceOnErrorSignal();
+   llvm::PrettyStackTraceProgram X(argc_, argv_);
+ 
+   if (llvm::sys::Process::FixupStandardFileDescriptors())
+     return 1;
+ 
+-  SmallVector<const char *, 256> argv;
++  std::vector<const char*> argv;
+   llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
+-  std::error_code EC = llvm::sys::Process::GetArgumentVector(
+-      argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
++  llvm::ArrayRef<const char*> AAR = llvm::makeArrayRef(argv_, argc_);
++  std::error_code EC =
++    llvm::sys::Process::GetArgumentVector(argv, AAR);
++
+   if (EC) {
+     llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
+     return 1;
+   }
+ 
+   std::set<std::string> SavedStrings;
+   StringSetSaver Saver(SavedStrings);
+ 
+   // Determines whether we want nullptr markers in argv to indicate response
+   // files end-of-lines. We only use this for the /LINK driver argument.
+@@ -459,21 +462,21 @@
+   Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
+   SetInstallDir(argv, TheDriver);
+ 
+   llvm::InitializeAllTargets();
+   ParseProgName(argv, SavedStrings);
+ 
+   SetBackdoorDriverOutputsFromEnvVars(TheDriver);
+ 
+   std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
+   int Res = 0;
+-  SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
++  SmallVector<std::pair<int, const Command *>, 8> FailingCommands;
+   if (C.get())
+     Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
+ 
+   // Force a crash to test the diagnostics.
+   if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) {
+     Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH";
+ 
+     // Pretend that every command failed.
+     FailingCommands.clear();
+     for (const auto &J : C->getJobs())
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/020-21874221-clang-llvm-sparc-assembler.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,1274 @@
+# - https://llvm.org/bugs/show_bug.cgi?id=22623
+# - 22346218 - LLVM's assembler printer on SPARC needs a lot of work
+# - 21874221 - clang C++ does not properly initialize the C++
+# Standard Library's iostreams
+# - 22582382 - Sun ld .init_array/.fini_array handling is incompatible
+# with the GNU Toolchain
+# - 22065707 - LLVM SPARC assembler generator emits wrong ELF Section flags
+# For upstream - maybe.
+--- include/llvm/MC/MCStreamer.h	2014-12-05 18:14:41.000000000 -0800
++++ include/llvm/MC/MCStreamer.h	2015-12-09 15:14:25.413937273 -0800
+@@ -478,6 +478,13 @@
+   ///
+   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
+ 
++  /// EmitELFSize - Emit an ELF .size directive.
++  ///
++  /// This corresponds to an assembler statement such as:
++  ///  .size symbol, expression, but without a temp .label.
++  ///
++  virtual void EmitELFSize(StringRef Name);
++
+   /// \brief Emit a Linker Optimization Hint (LOH) directive.
+   /// \param Args - Arguments of the LOH.
+   virtual void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {}
+--- include/llvm/MC/MCSymbol.h	2014-12-24 02:27:50.000000000 -0800
++++ include/llvm/MC/MCSymbol.h	2015-12-09 14:05:18.864224028 -0800
+@@ -51,23 +51,25 @@
+     /// IsTemporary - True if this is an assembler temporary label, which
+     /// typically does not survive in the .o file's symbol table.  Usually
+     /// "Lfoo" or ".foo".
+-    unsigned IsTemporary : 1;
++    bool IsTemporary;
+ 
+     /// \brief True if this symbol can be redefined.
+-    unsigned IsRedefinable : 1;
++    bool IsRedefinable;
+ 
+     /// IsUsed - True if this symbol has been used.
+-    mutable unsigned IsUsed : 1;
++    mutable bool IsUsed;
+ 
+-  private:  // MCContext creates and uniques these.
++  protected:  // MCContext creates and uniques these.
+     friend class MCExpr;
+     friend class MCContext;
++
+     MCSymbol(StringRef name, bool isTemporary)
+       : Name(name), Section(nullptr), Value(nullptr),
+-        IsTemporary(isTemporary), IsRedefinable(false), IsUsed(false) {}
++      IsTemporary(isTemporary), IsRedefinable(false), IsUsed(false) {}
+ 
+     MCSymbol(const MCSymbol&) LLVM_DELETED_FUNCTION;
+     void operator=(const MCSymbol&) LLVM_DELETED_FUNCTION;
++
+   public:
+     /// getName - Get the symbol name.
+     StringRef getName() const { return Name; }
+--- lib/MC/MCAsmStreamer.cpp	2015-01-14 03:23:27.000000000 -0800
++++ lib/MC/MCAsmStreamer.cpp	2015-12-09 15:14:32.728543403 -0800
+@@ -40,17 +40,18 @@
+ protected:
+   formatted_raw_ostream &OS;
+   const MCAsmInfo *MAI;
++
+ private:
+   std::unique_ptr<MCInstPrinter> InstPrinter;
+   std::unique_ptr<MCCodeEmitter> Emitter;
+   std::unique_ptr<MCAsmBackend> AsmBackend;
+ 
+-  SmallString<128> CommentToEmit;
++  SmallString<256> CommentToEmit;
+   raw_svector_ostream CommentStream;
+ 
+-  unsigned IsVerboseAsm : 1;
+-  unsigned ShowInst : 1;
+-  unsigned UseDwarfDirectory : 1;
++  bool IsVerboseAsm;
++  bool ShowInst;
++  bool UseDwarfDirectory;
+ 
+   void EmitRegisterName(int64_t Register);
+   void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
+@@ -61,10 +62,10 @@
+                 bool isVerboseAsm, bool useDwarfDirectory,
+                 MCInstPrinter *printer, MCCodeEmitter *emitter,
+                 MCAsmBackend *asmbackend, bool showInst)
+-      : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
+-        InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
+-        CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
+-        ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
++    : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
++    InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
++    CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
++    ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
+     if (InstPrinter && IsVerboseAsm)
+       InstPrinter->setCommentStream(CommentStream);
+   }
+@@ -75,8 +76,10 @@
+       OS << '\n';
+       return;
+     }
++
+     EmitCommentsAndEOL();
+   }
++
+   void EmitCommentsAndEOL();
+ 
+   /// isVerboseAsm - Return true if this streamer supports verbose assembly at
+@@ -139,6 +142,7 @@
+   void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
+   void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
+   void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
++  void EmitELFSize(StringRef Name) override;
+   void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                         unsigned ByteAlignment) override;
+ 
+@@ -501,6 +505,11 @@
+   OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
+ }
+ 
++void MCAsmStreamer::EmitELFSize(StringRef Name) {
++  assert(MAI->hasDotTypeDotSizeDirective());
++  OS << "\t.size\t" << Name << ", .-" << Name << '\n';
++}
++
+ void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                                      unsigned ByteAlignment) {
+   // Common symbols do not belong to any actual section.
+@@ -843,7 +852,7 @@
+   if (NumFiles == Table.getMCDwarfFiles().size())
+     return FileNo;
+ 
+-  SmallString<128> FullPathName;
++  SmallString<PATH_MAX> FullPathName;
+ 
+   if (!UseDwarfDirectory && !Directory.empty()) {
+     if (sys::path::is_absolute(Filename))
+--- lib/MC/MCSectionELF.cpp	2014-10-09 14:23:39.000000000 -0700
++++ lib/MC/MCSectionELF.cpp	2016-01-21 10:12:17.006210825 -0800
+@@ -59,8 +59,10 @@
+                                         raw_ostream &OS,
+                                         const MCExpr *Subsection) const {
+ 
++  StringRef SectionName = getSectionName();
++
+   if (ShouldOmitSectionDirective(SectionName, MAI)) {
+-    OS << '\t' << getSectionName();
++    OS << '\t' << SectionName;
+     if (Subsection)
+       OS << '\t' << *Subsection;
+     OS << '\n';
+@@ -68,35 +70,20 @@
+   }
+ 
+   OS << "\t.section\t";
+-  printName(OS, getSectionName());
+-
+-  // Handle the weird solaris syntax if desired.
+-  if (MAI.usesSunStyleELFSectionSwitchSyntax() &&
+-      !(Flags & ELF::SHF_MERGE)) {
+-    if (Flags & ELF::SHF_ALLOC)
+-      OS << ",#alloc";
+-    if (Flags & ELF::SHF_EXECINSTR)
+-      OS << ",#execinstr";
+-    if (Flags & ELF::SHF_WRITE)
+-      OS << ",#write";
+-    if (Flags & ELF::SHF_EXCLUDE)
+-      OS << ",#exclude";
+-    if (Flags & ELF::SHF_TLS)
+-      OS << ",#tls";
+-    OS << '\n';
+-    return;
+-  }
++  printName(OS, SectionName);
+ 
+   OS << ",\"";
+   if (Flags & ELF::SHF_ALLOC)
+     OS << 'a';
+   if (Flags & ELF::SHF_EXCLUDE)
+     OS << 'e';
+-  if (Flags & ELF::SHF_EXECINSTR)
++  if ((Flags & ELF::SHF_EXECINSTR) && (Type != ELF::SHT_INIT_ARRAY) &&
++      (Type != ELF::SHT_FINI_ARRAY) && (Type != ELF::SHT_PREINIT_ARRAY))
+     OS << 'x';
+   if (Flags & ELF::SHF_GROUP)
+     OS << 'G';
+-  if (Flags & ELF::SHF_WRITE)
++  if ((Flags & ELF::SHF_WRITE) || (Type == ELF::SHT_INIT_ARRAY) ||
++      (Type == ELF::SHT_FINI_ARRAY) || (Type == ELF::SHT_PREINIT_ARRAY))
+     OS << 'w';
+   if (Flags & ELF::SHF_MERGE)
+     OS << 'M';
+@@ -144,6 +131,7 @@
+     printName(OS, Group->getName());
+     OS << ",comdat";
+   }
++
+   OS << '\n';
+ 
+   if (Subsection)
+--- lib/MC/MCStreamer.cpp	2014-11-03 04:19:03.000000000 -0800
++++ lib/MC/MCStreamer.cpp	2015-12-09 15:15:14.428496845 -0800
+@@ -636,6 +636,7 @@
+ void MCStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {}
+ void MCStreamer::EmitCOFFSymbolType(int Type) {}
+ void MCStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
++void MCStreamer::EmitELFSize(StringRef Name) {}
+ void MCStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                                        unsigned ByteAlignment) {}
+ void MCStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
+--- tools/clang/lib/CodeGen/CGBlocks.cpp	2015-10-05 11:01:32.352334965 -0700
++++ tools/clang/lib/CodeGen/CGBlocks.cpp	2015-12-07 15:24:59.295683990 -0800
+@@ -1248,8 +1248,8 @@
+ 
+         DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
+                                               Builder, blockInfo,
+-                                              entry_ptr == entry->end()
+-                                              ? nullptr : entry_ptr);
++                                              entry_ptr == entry->end() ?
++                                              nullptr : &*entry_ptr);
+       }
+     }
+     // Recover location if it was changed in the above loop.
+--- tools/clang/lib/CodeGen/CGCall.cpp	2015-10-05 11:01:32.348582888 -0700
++++ tools/clang/lib/CodeGen/CGCall.cpp	2015-12-07 15:26:25.691201743 -0800
+@@ -2230,7 +2230,7 @@
+     if (RetAI.getInAllocaSRet()) {
+       llvm::Function::arg_iterator EI = CurFn->arg_end();
+       --EI;
+-      llvm::Value *ArgStruct = EI;
++      llvm::Value *ArgStruct = &*EI;
+       llvm::Value *SRet =
+           Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
+       RV = Builder.CreateLoad(SRet, "sret");
+@@ -2246,7 +2246,7 @@
+       ComplexPairTy RT =
+         EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
+                           EndLoc);
+-      EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
++      EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
+                          /*isInit*/ true);
+       break;
+     }
+@@ -2255,7 +2255,7 @@
+       break;
+     case TEK_Scalar:
+       EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
+-                        MakeNaturalAlignAddrLValue(AI, RetTy),
++                        MakeNaturalAlignAddrLValue(&*AI, RetTy),
+                         /*isInit*/ true);
+       break;
+     }
+--- tools/clang/lib/CodeGen/CGDeclCXX.cpp	2015-10-05 11:01:32.000000000 -0700
++++ tools/clang/lib/CodeGen/CGDeclCXX.cpp	2016-02-01 09:42:57.409779098 -0800
+@@ -23,6 +23,8 @@
+ using namespace clang;
+ using namespace CodeGen;
+ 
++static unsigned InitPriority = 128;
++
+ static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
+                          llvm::Constant *DeclPtr) {
+   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
+@@ -137,9 +139,9 @@
+                                                bool PerformInit) {
+ 
+   const Expr *Init = D.getInit();
+-  QualType T = D.getType();
++  QualType QT = D.getType();
+ 
+-  if (!T->isReferenceType()) {
++  if (!QT->isReferenceType()) {
+     if (getLangOpts().OpenMP && D.hasAttr<OMPThreadPrivateDeclAttr>())
+       (void)CGM.getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
+           &D, DeclPtr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
+@@ -157,7 +159,7 @@
+          "destruction for reference");
+   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
+   RValue RV = EmitReferenceBindingToExpr(Init);
+-  EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
++  EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, QT);
+ }
+ 
+ /// Create a stub function, suitable for being passed to atexit,
+@@ -166,22 +168,25 @@
+                                                   llvm::Constant *dtor,
+                                                   llvm::Constant *addr) {
+   // Get the destructor function type, void(*)(void).
+-  llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
+-  SmallString<256> FnName;
++  llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
++  SmallString<512> FnName;
+   {
+     llvm::raw_svector_ostream Out(FnName);
+     CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
+   }
+-  llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(),
+-                                                              VD.getLocation());
++
++  llvm::Function *Fn =
++    CGM.CreateGlobalInitOrDestructFunction(FTy, FnName.str(),
++                                           VD.getLocation());
+ 
+   CodeGenFunction CGF(CGM);
+ 
+-  CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn,
+-                    CGM.getTypes().arrangeNullaryFunction(), FunctionArgList());
++  CGF.StartFunction(&VD, CGM.getContext().VoidTy, Fn,
++                    CGM.getTypes().arrangeNullaryFunction(),
++                    FunctionArgList());
+ 
+   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
+- 
++
+  // Make sure the call and the callee agree on calling convention.
+   if (llvm::Function *dtorFn =
+         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
+@@ -189,7 +194,7 @@
+ 
+   CGF.FinishFunction();
+ 
+-  return fn;
++  return Fn;
+ }
+ 
+ /// Register a global destructor using the C atexit runtime function.
+@@ -203,12 +208,12 @@
+   llvm::FunctionType *atexitTy =
+     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
+ 
+-  llvm::Constant *atexit =
++  llvm::Constant *atExit =
+     CGM.CreateRuntimeFunction(atexitTy, "atexit");
+-  if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
++  if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atExit))
+     atexitFn->setDoesNotThrow();
+ 
+-  EmitNounwindRuntimeCall(atexit, dtorStub);
++  EmitNounwindRuntimeCall(atExit, dtorStub);
+ }
+ 
+ void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
+@@ -225,15 +230,29 @@
+   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
+ }
+ 
+-llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
+-    llvm::FunctionType *FTy, const Twine &Name, SourceLocation Loc, bool TLS) {
++llvm::Function*
++CodeGenModule::CreateGlobalInitOrDestructFunction(llvm::FunctionType *FTy,
++                                                  const Twine &Name,
++                                                  SourceLocation Loc,
++                                                  bool TLS) {
+   llvm::Function *Fn =
+     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
+                            Name, &getModule());
++
++  // Set the section if needed.
+   if (!getLangOpts().AppleKext && !TLS) {
+-    // Set the section if needed.
+-    if (const char *Section = getTarget().getStaticInitSectionSpecifier())
+-      Fn->setSection(Section);
++    if (const char *Section = getTarget().getStaticInitSectionSpecifier()) {
++      if (getTriple().getOS() == llvm::Triple::Solaris) {
++        std::string FNm = Fn->getName().str();
++        if ((FNm.find("_GLOBAL__sub_I_") != std::string::npos) &&
++            !CodeGenOpts.UseInitArray)
++          Fn->setSection(Section);
++        else
++          Fn->setSection(".text");
++      } else {
++        Fn->setSection(Section);
++      }
++    }
+   }
+ 
+   Fn->setCallingConv(getRuntimeCC());
+@@ -241,13 +260,16 @@
+   if (!getLangOpts().Exceptions)
+     Fn->setDoesNotThrow();
+ 
+-  if (!isInSanitizerBlacklist(Fn, Loc)) {
+-    if (getLangOpts().Sanitize.has(SanitizerKind::Address))
+-      Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
+-    if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
+-      Fn->addFnAttr(llvm::Attribute::SanitizeThread);
+-    if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
+-      Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
++  // Solaris does not yet support the Sanitizer Libraries.
++  if (getTriple().getOS() != llvm::Triple::Solaris) {
++    if (!isInSanitizerBlacklist(Fn, Loc)) {
++      if (getLangOpts().Sanitize.has(SanitizerKind::Address))
++        Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
++      if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
++        Fn->addFnAttr(llvm::Attribute::SanitizeThread);
++      if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
++        Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
++    }
+   }
+ 
+   return Fn;
+@@ -260,9 +282,21 @@
+                                           llvm::GlobalVariable *GV,
+                                           llvm::Function *InitFunc,
+                                           InitSegAttr *ISA) {
+-  llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
+-      TheModule, InitFunc->getType(), /*isConstant=*/true,
+-      llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
++  std::string GVN("__cxx_init_fn_ptr");
++  if (getTriple().getOS() == llvm::Triple::Solaris) {
++    GVN += "_";
++    GVN += std::to_string(InitPriority++);
++  }
++
++  llvm::GlobalVariable *PtrArray = nullptr;
++
++  PtrArray = new llvm::GlobalVariable(TheModule, InitFunc->getType(),
++                                      /*isConstant=*/ true,
++                                      llvm::GlobalValue::PrivateLinkage,
++                                      InitFunc, GVN);
++
++  assert(PtrArray && "Invalid Function Pointer Array!");
++
+   PtrArray->setSection(ISA->getSection());
+   addUsedGlobal(PtrArray);
+ 
+@@ -283,22 +317,76 @@
+ CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
+                                             llvm::GlobalVariable *Addr,
+                                             bool PerformInit) {
+-  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
++  llvm::FunctionType *FTy = nullptr;
++  std::vector<llvm::Type*> ArgsVec;
++
++  if (getTriple().getOS() == llvm::Triple::Solaris) {
++    ArgsVec.push_back(IntTy);
++    ArgsVec.push_back(IntTy);
++    FTy = llvm::FunctionType::get(VoidTy, ArgsVec, false);
++  } else {
++    FTy = llvm::FunctionType::get(VoidTy, false);
++  }
++
+   SmallString<256> FnName;
+   {
+     llvm::raw_svector_ostream Out(FnName);
+-    getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
++    if (getTriple().getOS() == llvm::Triple::Solaris)
++      getCXXABI().getMangleContext().mangleGCCDynamicInitializer(D, Out);
++    else
++      getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
+   }
+ 
+   // Create a variable initialization function.
+   llvm::Function *Fn =
+       CreateGlobalInitOrDestructFunction(FTy, FnName.str(), D->getLocation());
++  Fn->setDoesNotThrow();
+ 
+   auto *ISA = D->getAttr<InitSegAttr>();
+-  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
+-                                                          PerformInit);
+ 
+-  llvm::GlobalVariable *COMDATKey =
++  if (getTriple().getOS() == llvm::Triple::Solaris) {
++    ASTContext &Ctx = getContext();
++    auto *IPA = D->getAttr<InitPriorityAttr>();
++    if (!IPA) {
++      IPA = InitPriorityAttr::CreateImplicit(Ctx, /* InitPriority */ 65535);
++      VarDecl *DD = const_cast<VarDecl*>(D);
++      DD->addAttr(IPA);
++    }
++
++    if (!ISA && CodeGenOpts.UseInitArray) {
++      ISA = InitSegAttr::CreateImplicit(Ctx, PerformInit ?
++                                        StringRef(".init_array") :
++                                        StringRef(".fini_array"));
++      VarDecl *DD = const_cast<VarDecl*>(D);
++      DD->addAttr(ISA);
++    }
++  }
++
++  FunctionArgList ArgList;
++  ASTContext &Ctx = getContext();
++  // We cannot allocate these dynamically because of a very ill-conceived
++  // operator new overload in DeclBase.h.
++  ImplicitParamDecl IAFirst(Ctx, /*DC=*/ nullptr, D->getLocation(),
++                            /*Id=*/ nullptr, Ctx.UnsignedIntTy);
++  ImplicitParamDecl IASecond(Ctx, /*DC=*/ nullptr, D->getLocation(),
++                             /*Id=*/ nullptr, Ctx.UnsignedIntTy);
++
++  if (getTriple().getOS() == llvm::Triple::Solaris) {
++    // Add Parameters to the Function ArgumentList on Solaris
++    // for compatibility with the GCC C++ Runtime.
++    ArgList.push_back(&IAFirst);
++    ArgList.push_back(&IASecond);
++  }
++
++  CodeGenFunction CGF(*this);
++  CGF.GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr, PerformInit, ArgList);
++
++  llvm::GlobalVariable *COMDATKey;
++
++  if (getTriple().getOS() == llvm::Triple::Solaris)
++    COMDATKey = D->isExternallyVisible() ? Addr : nullptr;
++  else
++    COMDATKey =
+       supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
+ 
+   if (D->getTLSKind()) {
+@@ -370,7 +458,6 @@
+ 
+   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
+ 
+-
+   // Create our global initialization function.
+   if (!PrioritizedCXXGlobalInits.empty()) {
+     SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
+@@ -391,9 +478,10 @@
+       // sure the function names are also ordered as priorities.
+       std::string PrioritySuffix = llvm::utostr(Priority);
+       // Priority is always <= 65535 (enforced by sema).
+-      PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
+-      llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
+-          FTy, "_GLOBAL__I_" + PrioritySuffix);
++      PrioritySuffix =
++        std::string(6 - PrioritySuffix.size(), '0') + PrioritySuffix;
++      llvm::Function *Fn =
++        CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__I_" + PrioritySuffix);
+ 
+       for (; I < PrioE; ++I)
+         LocalCXXGlobalInits.push_back(I->second);
+@@ -403,7 +491,7 @@
+     }
+   }
+ 
+-  SmallString<128> FileName;
++  SmallString<PATH_MAX> FileName;
+   SourceManager &SM = Context.getSourceManager();
+   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
+     // Include the filename in the symbol name. Including "sub_" matches gcc and
+@@ -417,14 +505,15 @@
+   for (size_t i = 0; i < FileName.size(); ++i) {
+     // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
+     // to be the set of C preprocessing numbers.
+-    if (!isPreprocessingNumberBody(FileName[i]))
++    if (!isPreprocessingNumberBody(FileName[i]) || (FileName[i] == '.'))
+       FileName[i] = '_';
+   }
+ 
+   llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
+       FTy, llvm::Twine("_GLOBAL__sub_I_", FileName));
+ 
+-  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
++  CodeGenFunction CGF(*this);
++  CGF.GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
+   AddGlobalCtor(Fn);
+ 
+   CXXGlobalInits.clear();
+@@ -445,28 +534,43 @@
+ }
+ 
+ /// Emit the code necessary to initialize the given global variable.
+-void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
+-                                                       const VarDecl *D,
+-                                                 llvm::GlobalVariable *Addr,
+-                                                       bool PerformInit) {
++void
++CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
++                                                  const VarDecl *D,
++                                                  llvm::GlobalVariable *Addr,
++                                                  bool PerformInit,
++                                                  FunctionArgList ArgList) {
+   // Check if we need to emit debug info for variable initializer.
+   if (D->hasAttr<NoDebugAttr>())
+     DebugInfo = nullptr; // disable debug info indefinitely for this function
+ 
+   CurEHLocation = D->getLocStart();
++  ASTContext &Ctx = getContext();
+ 
+-  StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
+-                getTypes().arrangeNullaryFunction(),
+-                FunctionArgList(), D->getLocation(),
++  FunctionType::ExtInfo ExtInfo;
++  const CGFunctionInfo &FuncInfo =
++    getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, ArgList,
++                                              ExtInfo, /*IsVariadic=*/ false);
++  GlobalDecl GD(D);
++
++  StartFunction(GD, Ctx.VoidTy, Fn, FuncInfo, ArgList, D->getLocation(),
+                 D->getInit()->getExprLoc());
+ 
+-  // Use guarded initialization if the global variable is weak. This
+-  // occurs for, e.g., instantiated static data members and
+-  // definitions explicitly marked weak.
+-  if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
+-    EmitCXXGuardedInit(*D, Addr, PerformInit);
++  if (CGM.getTriple().getOS() == llvm::Triple::Solaris) {
++    if (Addr->hasWeakLinkage()) {
++      EmitCXXGuardedInit(*D, Addr, PerformInit);
++    } else {
++      EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
++    }
+   } else {
+-    EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
++    // Use guarded initialization if the global variable is weak. This
++    // occurs for, e.g., instantiated static data members and
++    // definitions explicitly marked weak.
++    if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
++      EmitCXXGuardedInit(*D, Addr, PerformInit);
++    } else {
++      EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
++    }
+   }
+ 
+   FinishFunction();
+@@ -476,10 +580,21 @@
+ CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
+                                            ArrayRef<llvm::Function *> Decls,
+                                            llvm::GlobalVariable *Guard) {
++  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
++  ASTContext &Ctx = getContext();
++  llvm::LLVMContext &LLVMCtx = CGM.getLLVMContext();
++
+   {
+     ApplyDebugLocation NL(*this);
+-    StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
+-                  getTypes().arrangeNullaryFunction(), FunctionArgList());
++
++    FunctionArgList ArgList;
++    FunctionType::ExtInfo ExtInfo;
++    const CGFunctionInfo &FuncInfo =
++      getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, ArgList,
++                                                ExtInfo,
++                                                /*IsVariadic=*/ false);
++    StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, FuncInfo, ArgList);
++
+     // Emit an artificial location for this function.
+     ArtificialLocation AL(*this);
+ 
+@@ -509,9 +624,27 @@
+       EmitObjCAutoreleasePoolCleanup(token);
+     }
+ 
+-    for (unsigned i = 0, e = Decls.size(); i != e; ++i)
+-      if (Decls[i])
+-        EmitRuntimeCall(Decls[i]);
++    for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
++      if (llvm::Function *FV = Decls[i]) {
++        if (CGM.getTriple().getOS() == llvm::Triple::Solaris) {
++          llvm::Value *Values[2] = { nullptr, nullptr };
++          Values[0] =
++            llvm::ConstantInt::get(llvm::Type::getInt32Ty(LLVMCtx), 1);
++          Values[1] =
++            llvm::ConstantInt::get(llvm::Type::getInt32Ty(LLVMCtx), 65535);
++          ArrayRef<llvm::Value*> ArgValues = llvm::makeArrayRef(Values);
++          llvm::CallInst *CI = EmitRuntimeCall(FV, ArgValues);
++#ifndef NDEBUG
++          llvm::Function *CIF = CI->getCalledFunction();
++          assert (CIF && "Invalid function returned in CallInst!");
++#else
++          (void) CI;
++#endif
++        } else {
++          EmitRuntimeCall(Decls[i]);
++        }
++      }
++    }
+ 
+     Scope.ForceCleanup();
+ 
+@@ -569,8 +702,8 @@
+   StartFunction(VD, getContext().VoidTy, fn, FI, args);
+ 
+   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
+-  
++
+   FinishFunction();
+-  
++
+   return fn;
+ }
+--- tools/clang/lib/CodeGen/CGExprScalar.cpp	2015-10-05 11:01:32.351864633 -0700
++++ tools/clang/lib/CodeGen/CGExprScalar.cpp	2015-12-07 16:39:38.372167280 -0800
+@@ -2319,9 +2319,9 @@
+ 
+   // Branch in case of overflow.
+   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
+-  llvm::Function::iterator insertPt = initialBB;
++  llvm::Function::iterator insertPt = initialBB->getIterator();
+   llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
+-                                                      std::next(insertPt));
++                                                      &*std::next(insertPt));
+   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
+ 
+   Builder.CreateCondBr(overflow, overflowBB, continueBB);
+--- tools/clang/lib/CodeGen/CGExpr.cpp	2015-10-05 11:01:32.356618553 -0700
++++ tools/clang/lib/CodeGen/CGExpr.cpp	2015-12-07 16:36:56.944848497 -0800
+@@ -64,7 +64,7 @@
+                                      llvm::Value *Init) {
+   auto *Store = new llvm::StoreInst(Init, Var);
+   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
+-  Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
++  Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
+ }
+ 
+ llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
+--- tools/clang/lib/CodeGen/CGStmt.cpp	2015-10-05 11:01:32.627209320 -0700
++++ tools/clang/lib/CodeGen/CGStmt.cpp	2015-12-07 16:52:55.040873133 -0800
+@@ -329,7 +329,7 @@
+     return;
+ 
+   // Can only simplify empty blocks.
+-  if (BI != BB->begin())
++  if (BI->getIterator() != BB->begin())
+     return;
+ 
+   BB->replaceAllUsesWith(BI->getSuccessor(0));
+@@ -351,7 +351,7 @@
+   // Place the block after the current block, if possible, or else at
+   // the end of the function.
+   if (CurBB && CurBB->getParent())
+-    CurFn->getBasicBlockList().insertAfter(CurBB, BB);
++    CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
+   else
+     CurFn->getBasicBlockList().push_back(BB);
+   Builder.SetInsertPoint(BB);
+@@ -378,7 +378,8 @@
+   bool inserted = false;
+   for (llvm::User *u : block->users()) {
+     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
+-      CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
++      CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
++                                             block);
+       inserted = true;
+       break;
+     }
+--- tools/clang/lib/CodeGen/CGVTables.cpp	2015-10-05 11:01:32.353244828 -0700
++++ tools/clang/lib/CodeGen/CGVTables.cpp	2015-12-07 17:11:22.736212205 -0800
+@@ -158,12 +158,16 @@
+   // Find the first store of "this", which will be to the alloca associated
+   // with "this".
+   llvm::Value *ThisPtr = &*AI;
+-  llvm::BasicBlock *EntryBB = Fn->begin();
++  llvm::BasicBlock *EntryBB = &Fn->front();
+   llvm::Instruction *ThisStore =
+-      std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
+-    return isa<llvm::StoreInst>(I) && I.getOperand(0) == ThisPtr;
+-  });
++      &*std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I)
++                     {
++                     return isa<llvm::StoreInst>(I) &&
++                     I.getOperand(0) == ThisPtr;
++                     });
++
+   assert(ThisStore && "Store of this should be in entry block?");
++
+   // Adjust "this", if necessary.
+   Builder.SetInsertPoint(ThisStore);
+   llvm::Value *AdjustedThisPtr =
+--- tools/clang/lib/CodeGen/CodeGenFunction.cpp	2015-10-05 11:01:32.357401838 -0700
++++ tools/clang/lib/CodeGen/CodeGenFunction.cpp	2015-12-07 17:13:22.309802713 -0800
+@@ -672,14 +672,14 @@
+     auto AI = CurFn->arg_begin();
+     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
+       ++AI;
+-    ReturnValue = AI;
++    ReturnValue = &*AI;
+   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
+              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
+     // Load the sret pointer from the argument struct and return into that.
+     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
+     llvm::Function::arg_iterator EI = CurFn->arg_end();
+     --EI;
+-    llvm::Value *Addr = Builder.CreateStructGEP(EI, Idx);
++    llvm::Value *Addr = Builder.CreateStructGEP(&*EI, Idx);
+     ReturnValue = Builder.CreateLoad(Addr, "agg.result");
+   } else {
+     ReturnValue = CreateIRTemp(RetTy, "retval");
+--- tools/clang/lib/CodeGen/CodeGenFunction.h	2015-10-05 11:01:32.347172460 -0700
++++ tools/clang/lib/CodeGen/CodeGenFunction.h	2015-10-14 18:25:20.000000000 -0700
+@@ -2572,10 +2572,11 @@
+   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
+                                         const VarDecl *D,
+                                         llvm::GlobalVariable *Addr,
+-                                        bool PerformInit);
++                                        bool PerformInit,
++                                        FunctionArgList ArgList);
+ 
+   void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
+-  
++
+   void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
+                                   const Expr *Exp);
+ 
+--- tools/clang/lib/CodeGen/CodeGenModule.cpp	2015-10-05 11:01:32.354174460 -0700
++++ tools/clang/lib/CodeGen/CodeGenModule.cpp	2016-02-01 09:44:08.493171103 -0800
+@@ -228,7 +228,8 @@
+     OldF->replaceAllUsesWith(Replacement);
+     if (NewF) {
+       NewF->removeFromParent();
+-      OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
++      OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
++                                                       NewF);
+     }
+     OldF->eraseFromParent();
+   }
+@@ -272,8 +273,16 @@
+       Error = true;
+       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
+     } else if (GV->isDeclaration()) {
+-      Error = true;
+-      Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
++      clang::Linkage L = D->getFormalLinkage();
++      const auto *FD = cast<FunctionDecl>(D);
++
++      if (!FD && ((L != clang::ExternalLinkage) &&
++                  (L != clang::UniqueExternalLinkage) &&
++                  (L != clang::InternalLinkage) &&
++                  (L != clang::VisibleNoLinkage))) {
++        Error = true;
++        Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
++      }
+     }
+ 
+     llvm::Constant *Aliasee = Alias->getAliasee();
+@@ -1310,10 +1319,7 @@
+ 
+ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
+   const auto *Global = cast<ValueDecl>(GD.getDecl());
+-
+-  // Weak references don't produce any output by themselves.
+-  if (Global->hasAttr<WeakRefAttr>())
+-    return;
++  assert(Global && "Cast to ValueDecl yields nullptr!");
+ 
+   // If this is an alias definition (which otherwise looks like a declaration)
+   // emit it now.
+@@ -1485,16 +1491,11 @@
+ void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
+   const auto *D = cast<ValueDecl>(GD.getDecl());
+ 
+-  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 
++  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
+                                  Context.getSourceManager(),
+                                  "Generating code for declaration");
+-  
+-  if (isa<FunctionDecl>(D)) {
+-    // At -O0, don't generate IR for functions with available_externally 
+-    // linkage.
+-    if (!shouldEmitFunction(GD))
+-      return;
+ 
++  if (isa<FunctionDecl>(D)) {
+     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
+       CompleteDIClassType(Method);
+       // Make sure to emit the definition(s) before we emit the thunks.
+@@ -1512,13 +1513,18 @@
+       return;
+     }
+ 
+-    return EmitGlobalFunctionDefinition(GD, GV);
++    EmitGlobalFunctionDefinition(GD, GV);
++    return;
++  }
++
++  if (const auto *VD = dyn_cast<VarDecl>(D)) {
++    EmitGlobalVarDefinition(VD);
++    return;
+   }
+ 
+-  if (const auto *VD = dyn_cast<VarDecl>(D))
+-    return EmitGlobalVarDefinition(VD);
+-  
+-  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
++  llvm::errs() << __PRETTY_FUNCTION__
++    << ": Invalid argument to EmitGlobalDefinition()!\n";
++  return;
+ }
+ 
+ /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
+--- tools/clang/lib/CodeGen/CodeGenModule.h	2015-10-05 11:01:32.344046428 -0700
++++ tools/clang/lib/CodeGen/CodeGenModule.h	2015-10-20 21:11:16.000000000 -0700
+@@ -692,7 +692,8 @@
+                                     llvm::GlobalValue::LinkageTypes Linkage);
+ 
+   llvm::Function *
+-  CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
++  CreateGlobalInitOrDestructFunction(llvm::FunctionType *FTy,
++                                     const Twine &Name,
+                                      SourceLocation Loc = SourceLocation(),
+                                      bool TLS = false);
+ 
+--- tools/clang/lib/CodeGen/CodeGenPGO.cpp	2015-10-05 11:01:32.349650190 -0700
++++ tools/clang/lib/CodeGen/CodeGenPGO.cpp	2015-12-08 07:11:06.067357170 -0800
+@@ -788,8 +788,10 @@
+ void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter) {
+   if (!CGM.getCodeGenOpts().ProfileInstrGenerate || !RegionCounterMap)
+     return;
+-  if (!Builder.GetInsertPoint())
++
++  if (!Builder.GetInsertBlock())
+     return;
++
+   auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
+   Builder.CreateCall4(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
+                       llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
+--- tools/clang/lib/Driver/ToolChains.cpp	2016-02-01 14:47:49.483365583 -0800
++++ tools/clang/lib/Driver/ToolChains.cpp	2016-02-01 09:12:57.596182227 -0800
+@@ -2918,6 +2918,11 @@
+   const llvm::Triple& TT = getTriple();
+   llvm::Triple::ArchType Arch = TT.getArch();
+ 
++  if (Arg *A = DriverArgs.getLastArg(options::OPT_fuse_init_array)) {
++    CC1Args.push_back("-fuse-init-array");
++    DriverArgs.ClaimAllArgs(options::OPT_fuse_init_array);
++  }
++
+   if (Arg *A = DriverArgs.getLastArg(options::OPT_mtune_EQ)) {
+     StringRef V = A->getValue();
+     if (!V.empty())
+--- tools/clang/lib/Driver/ToolChains.cpp	2016-02-01 18:49:01.325382261 -0800
++++ tools/clang/lib/Driver/ToolChains.cpp	2016-02-01 19:59:25.420298464 -0800
+@@ -3012,13 +3012,22 @@
+ 
+ void Solaris::findGCCMajorMinorMicro(const llvm::Triple& T) const {
+   // FIXME: Add 5.2.0 after testing the ABI.
+-  static const char* const GCCMMM[] = { "4.8.2", "4.8.5", "4.9.3" };
++  static const char* const GCCMMM[] = { "4.8.2", "4.9.3", "4.9.4" };
+ 
+   const char* P;
+   std::string Path;
+   std::string TripleString = llvm::sys::getDefaultTargetTriple();
+   llvm::Triple::ArchType Arch = T.getArch();
+ 
++  // GCC4 on Solaris is multilib 32/64.
++  // GCC5 (not supported here yet) on Solaris is multilib 64/32.
++  if (GCCMajorMinor[0] == '4') {
++    if (TripleString.find("x86_64") != std::string::npos)
++      TripleString.replace(0U, 6U, std::string("i386"));
++    else if (TripleString.find("sparcv9") != std::string::npos)
++      TripleString.replace(0U, 7U, std::string("sparc"));
++  }
++
+   if (UseMediatedGCCToolChainPath) {
+     // FIXME: IMPLEMENT.
+     // Needs spec.
+--- tools/clang/lib/Driver/Tools.cpp	2015-10-12 22:12:01.440488058 -0700
++++ tools/clang/lib/Driver/Tools.cpp	2016-02-01 10:32:24.767483623 -0800
+@@ -45,6 +45,10 @@
+ using namespace clang;
+ using namespace llvm::opt;
+ 
++#if defined(LLVM_ON_UNIX)
++#include <sys/utsname.h>
++#endif
++
+ static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
+   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
+                                     options::OPT_fpic, options::OPT_fno_pic,
+@@ -4595,8 +4599,10 @@
+   // nice to enable this when doing a crashdump for modules as well.
+   if (Args.hasFlag(options::OPT_frewrite_includes,
+                    options::OPT_fno_rewrite_includes, false) ||
+-      (C.isForDiagnostics() && !HaveModules))
+-    CmdArgs.push_back("-frewrite-includes");
++      (C.isForDiagnostics() && !HaveModules)) {
++    if (getToolChain().getTriple().getOS() != llvm::Triple::Solaris)
++      CmdArgs.push_back("-frewrite-includes");
++  }
+ 
+   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
+   if (Arg *A = Args.getLastArg(options::OPT_traditional,
+@@ -6379,6 +6385,8 @@
+ 
+   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
+                        options::OPT_Xassembler);
++  Args.ClaimAllArgs(options::OPT_Wa_COMMA);
++  Args.ClaimAllArgs(options::OPT_Xassembler);
+ 
+   for (const auto &II : Inputs) {
+     if (II.getType() == types::TY_LLVM_IR ||
+@@ -6517,6 +6525,11 @@
+   ArgStringList CmdArgs;
+ 
+   CmdArgs.push_back(Args.MakeArgString("-zignore"));
++  CmdArgs.push_back(Args.MakeArgString("-zrelax=common"));
++  CmdArgs.push_back(Args.MakeArgString("-zrelax=secadj"));
++  CmdArgs.push_back(Args.MakeArgString("-zrelax=transtls"));
++  if (D.CCCIsCXX())
++    CmdArgs.push_back(Args.MakeArgString("-zrelax=comdat"));
+ 
+   Arg *PIEArg = Args.getLastArg(options::OPT_fPIE, options::OPT_fpie);
+   if (PIEArg) {
+@@ -6527,7 +6540,7 @@
+       CmdArgs.push_back(Args.MakeArgString("-ztextwarn"));
+       CmdArgs.push_back(Args.MakeArgString("-ztype=pie"));
+       CmdArgs.push_back(Args.MakeArgString("-zaslr=enable"));
+-  }
++    }
+   }
+ 
+   // Silence warning for "-g: argument not used during compilation
+@@ -6656,10 +6669,21 @@
+   if (!Args.hasArg(options::OPT_nostdlib) &&
+       !Args.hasArg(options::OPT_nostartfiles)) {
+     if (!Args.hasArg(options::OPT_shared)) {
++      std::string UNM = "5.12";
++
++#if defined(LLVM_ON_UNIX) // Because Windows?
++      struct utsname UTS;
++      if (::uname(&UTS) == 0)
++        UNM = UTS.version;
++#endif
++
+       switch (Arch) {
+       case llvm::Triple::sparc:
+       case llvm::Triple::sparcv9:
+-        crt1o = GCCLibPath;
++        if (UNM == "5.12")
++          crt1o = LibPath;
++        else
++          crt1o = GCCLibPath;
+         break;
+       case llvm::Triple::x86:
+       case llvm::Triple::x86_64:
+@@ -6754,7 +6778,8 @@
+           CXAFinalize = *B + "/cxa_finalize.o";
+         }
+ 
+-        if (llvm::sys::fs::exists(CXAFinalize.c_str()))
++        HasSystemCXAFinalize = llvm::sys::fs::exists(CXAFinalize.c_str());
++        if (D.CCCIsCXX() && HasSystemCXAFinalize)
+           CmdArgs.push_back(Args.MakeArgString(CXAFinalize.c_str()));
+       }
+     }
+@@ -6784,8 +6809,10 @@
+   // Itanium C++ ABI.
+   if (D.CCCIsCXX()) {
+     if (!Args.hasArg(options::OPT_shared)) {
+-      const char* zfiniarray = "-zfiniarray=__cxa_finalize";
+-      CmdArgs.push_back(Args.MakeArgString(zfiniarray));
++      if (HasSystemCXAFinalize) {
++        const char* zfiniarray = "-zfiniarray=__cxa_finalize";
++        CmdArgs.push_back(Args.MakeArgString(zfiniarray));
++      }
+     }
+   }
+ 
+@@ -6843,6 +6870,9 @@
+ 
+   addProfileRT(TC, Args, CmdArgs);
+ 
++  Args.ClaimAllArgs(options::OPT_Wl_COMMA);
++  Args.ClaimAllArgs(options::OPT_Xlinker);
++
+   C.addCommand(llvm::make_unique<Command>(JA, *this,
+                                           Args.MakeArgString(Linker),
+                                           CmdArgs));
+--- tools/clang/lib/Basic/Targets.cpp	2015-10-27 10:02:43.744975392 -0700
++++ tools/clang/lib/Basic/Targets.cpp	2016-02-01 08:33:09.756656790 -0800
+@@ -537,6 +537,10 @@
+     Builder.defineMacro("__ELF__");
+     Builder.defineMacro("__svr4__");
+     Builder.defineMacro("__SVR4");
++    Builder.defineMacro("__SunOS", "1");
++
++    if (Opts.CPlusPlus || Opts.CPlusPlus11 || Opts.CPlusPlus14)
++      Builder.defineMacro("__GTHREADS", "1");
+ 
+     if (Opts.C99 || Opts.CPlusPlus11) {
+       if (Opts.C99) {
+@@ -549,39 +553,51 @@
+       Builder.defineMacro("__C99FEATURES__", "1");
+     }
+ 
+-    if (Opts.CPlusPlus11)
+-      Builder.defineMacro("__cplusplus", "201103L");
+-    else if (Opts.CPlusPlus14)
+-      Builder.defineMacro("__cplusplus", "201402L");
++    if (Opts.CPlusPlus11 || Opts.CPlusPlus14) {
++      Builder.defineMacro("__STDCPP_STRICT_POINTER_SAFETY__", "1");
++      Builder.defineMacro("__STDCPP_THREADS__", "1");
++    }
+ 
+     if (Opts.CPlusPlus11) {
+-      Builder.defineMacro("_STDC_C11", "1");
++      Builder.defineMacro("__STDC_ISO_10646__", "201011L");
++      Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1");
+       Builder.defineMacro("_STDC_C11_BCI", "1");
+       Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
+       Builder.defineMacro("_XPG7", "1");
+       Builder.defineMacro("_XOPEN_SOURCE", "700");
+     } else if (Opts.C11 || Opts.CPlusPlus14) {
++      Builder.defineMacro("__STDC_HOSTED__", "1");
+       Builder.defineMacro("__STDC_VERSION__", "201112L");
+       Builder.defineMacro("_STDC_C11", "1");
+       Builder.defineMacro("_STDC_C11_BCI", "1");
++      Builder.defineMacro("__STDC_ISO_10646__", "201011L");
++      Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1");
++      Builder.defineMacro("__STDC_LIB_EXT1__", "201112L");
++      Builder.defineMacro("__STDC_UTF_16__", "1");
++      Builder.defineMacro("__STDC_UTF_32__", "1");
+       Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
++
++      if (Opts.C11) {
++        Builder.defineMacro("__STDC_ANALYZABLE", "1");
++        Builder.defineMacro("__STDC_IEC_559__", "1");
++        Builder.defineMacro("__STDC_IEC_559_COMPLEX__", "1");
++      }
++
+       Builder.defineMacro("_XPG7", "1");
+       Builder.defineMacro("_XOPEN_SOURCE", "700");
+     } else {
+       Builder.defineMacro("_XOPEN_SOURCE", "500");
+       Builder.defineMacro("__STDC_VERSION__", "199409L");
+-      if (Opts.CPlusPlus && !Opts.CPlusPlus11 && !Opts.CPlusPlus14)
+-        Builder.defineMacro("__cplusplus", "199711L");
+     }
+ 
+     if ((Triple.getArchName() == "i386") || (Triple.getArchName() == "sparc"))
+     Builder.defineMacro("_LARGEFILE_SOURCE");
+     else if ((Triple.getArchName() == "x86_64") ||
+              (Triple.getArchName() == "sparcv9"))
+-    Builder.defineMacro("_LARGEFILE64_SOURCE");
++      Builder.defineMacro("_LARGEFILE64_SOURCE", "1");
+ 
+     Builder.defineMacro("__EXTENSIONS__", "1");
+-    Builder.defineMacro("_REENTRANT");
++    Builder.defineMacro("_REENTRANT", "1");
+   }
+ 
+ public:
+@@ -590,6 +606,10 @@
+     this->WCharType = this->SignedInt;
+     // FIXME: WIntType should be SignedLong
+   }
++
++  virtual const char *getStaticInitSectionSpecifier() const override {
++    return ".init";
++  }
+ };
+ 
+ // Windows target
+--- tools/clang/include/clang/AST/Mangle.h	2014-09-16 08:18:21.000000000 -0700
++++ tools/clang/include/clang/AST/Mangle.h	2015-10-21 08:10:11.000000000 -0700
+@@ -129,6 +129,8 @@
+ 
+   virtual void mangleDynamicInitializer(const VarDecl *D, raw_ostream &) = 0;
+ 
++  virtual void mangleGCCDynamicInitializer(const VarDecl *D, raw_ostream &) = 0;
++
+   virtual void mangleDynamicAtExitDestructor(const VarDecl *D,
+                                              raw_ostream &) = 0;
+ 
+--- tools/clang/lib/AST/ItaniumMangle.cpp	2015-10-05 11:01:32.264807353 -0700
++++ tools/clang/lib/AST/ItaniumMangle.cpp	2016-01-22 19:21:46.574349928 -0800
+@@ -154,6 +154,7 @@
+   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
+   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
+   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
++  void mangleGCCDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
+   void mangleDynamicAtExitDestructor(const VarDecl *D,
+                                      raw_ostream &Out) override;
+   void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
+@@ -3834,6 +3835,17 @@
+   Out << "__cxx_global_var_init";
+ }
+ 
++void ItaniumMangleContextImpl::mangleGCCDynamicInitializer(const VarDecl *MD,
++                                                           raw_ostream &Out) {
++  static unsigned SEQ = 0UL;
++
++  // Mangle GCC's __static_initialiation_and_destruction_<X>
++  // .init_array function.
++  Out << "_Z41" << "__static_initialization_and_destruction_"
++    << SEQ << "ii";
++  ++SEQ;
++}
++
+ void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
+                                                              raw_ostream &Out) {
+   // Prefix the mangling of D with __dtor_.
+--- tools/clang/lib/AST/MicrosoftMangle.cpp	2014-12-21 22:24:49.000000000 -0800
++++ tools/clang/lib/AST/MicrosoftMangle.cpp	2015-10-21 08:12:50.000000000 -0700
+@@ -132,6 +132,7 @@
+                                 raw_ostream &) override;
+   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
+   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
++  void mangleGCCDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
+   void mangleDynamicAtExitDestructor(const VarDecl *D,
+                                      raw_ostream &Out) override;
+   void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
+@@ -2407,6 +2408,11 @@
+   mangleInitFiniStub(D, Out, 'E');
+ }
+ 
++void MicrosoftMangleContextImpl::mangleGCCDynamicInitializer(const VarDecl *D,
++                                                             raw_ostream &Out) {
++  mangleDynamicInitializer(D, Out);
++}
++
+ void
+ MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
+                                                           raw_ostream &Out) {
+--- tools/clang/lib/Frontend/InitPreprocessor.cpp	2016-02-02 07:35:41.701519177 -0800
++++ tools/clang/lib/Frontend/InitPreprocessor.cpp	2016-02-02 08:45:58.127181898 -0800
+@@ -476,9 +476,16 @@
+   if (!LangOpts.MSVCCompat) {
+     // Currently claim to be compatible with GCC 4.2.1-5621, but only if we're
+     // not compiling for MSVC compatibility
++    if (TI.getTriple().getOS() == llvm::Triple::Solaris) {
++      Builder.defineMacro("__GNUC_MINOR__", "8");
++      Builder.defineMacro("__GNUC_PATCHLEVEL__", "0");
++    } else {
+     Builder.defineMacro("__GNUC_MINOR__", "2");
+     Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
++    }
++
+     Builder.defineMacro("__GNUC__", "4");
++
+     // GCC provides a number of C++ ABI Versions in:
+     // ${top_srcdir}/gcc/c-family/c-cppbuiltin.c
+     // Currently valid GXX ABI Versions are documented here:
+--- tools/clang/lib/Driver/ToolChains.cpp	2016-02-02 07:35:42.102842090 -0800
++++ tools/clang/lib/Driver/ToolChains.cpp	2016-02-02 09:01:01.559630875 -0800
+@@ -2923,6 +2923,11 @@
+     DriverArgs.ClaimAllArgs(options::OPT_fuse_init_array);
+   }
+ 
++  if (DriverArgs.getLastArg(options::OPT_fabi_version_EQ) == nullptr)
++    CC1Args.push_back("-fabi-version=4");
++  else
++    DriverArgs.ClaimAllArgs(options::OPT_fabi_version_EQ);
++
+   if (Arg *A = DriverArgs.getLastArg(options::OPT_mtune_EQ)) {
+     StringRef V = A->getValue();
+     if (!V.empty())
+@@ -2931,7 +2936,7 @@
+     // FIXME: Impplement SPARC target features.
+     CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
+     if (Arch == llvm::Triple::sparc || Arch == llvm::Triple::sparcv9) {
+-      std::string S = "mtune=";
++      std::string S = "-mtune=";
+       S += mtune;
+       CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
+     } else {
+@@ -2947,7 +2952,7 @@
+     CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
+ 
+     if ((Arch == llvm::Triple::sparc) || (Arch == llvm::Triple::sparcv9)) {
+-      std::string S = "march=";
++      std::string S = "-march=";
+       S += mtune;
+       CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
+     } else {
+@@ -2965,7 +2970,7 @@
+     }
+ 
+     CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
+-    std::string S = "mcpu=";
++    std::string S = "-mcpu=";
+     S += mcpu;
+     CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
+ 
+--- tools/clang/lib/Driver/Tools.cpp	2016-02-02 07:35:42.107579301 -0800
++++ tools/clang/lib/Driver/Tools.cpp	2016-02-02 09:00:08.889301970 -0800
+@@ -3000,6 +3000,8 @@
+     StringRef v = A->getValue();
+     CmdArgs.push_back(Args.MakeArgString("-fabi-version=" + v));
+     A->claim();
++  } else {
++    CmdArgs.push_back(Args.MakeArgString("-fabi-version=4"));
+   }
+ 
+   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/021-llvm-ilist-iterator-22031298.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,13055 @@
+# http://lists.llvm.org/pipermail/llvm-dev/2015-October/091115.html
+# - 22031298 - toxic bugs in LLVM ilist/plist end up eliminating entire
+# MachineBasicBlocks
+# - Presumed fixed (?) in trunk upstream. Not verified.
+# - Verified fixed in our 3.6.2 fork.
+# Not for upstream. Autoconf-based built system is removed in 3.8.X.
+--- Makefile.rules	2015-10-05 11:01:32.687305595 -0700
++++ Makefile.rules	2015-12-08 11:12:41.094567698 -0800
+@@ -331,6 +331,12 @@
+  endif
+ endif
+ 
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++  REQUIRES_EH := 1
++else
++  REQUIRES_EH := 0
++endif
++
+ ifeq ($(ENABLE_WERROR),1)
+   CXX.Flags += -Werror
+   C.Flags += -Werror
+@@ -355,14 +361,16 @@
+ endif
+ 
+ # IF REQUIRES_EH=1 is specified then don't disable exceptions
+-ifndef REQUIRES_EH
++ifneq ($(REQUIRES_EH), 1)
++  REQUIRES_RTTI := 0
+   CXX.Flags += -fno-exceptions
+ else
+   # If the library requires EH, it also requires RTTI.
+   REQUIRES_RTTI := 1
++  CXX.Flags += -fexceptions
+ endif
+ 
+-ifdef REQUIRES_FRAME_POINTER
++ifeq ($(REQUIRES_FRAME_POINTER), 1)
+   CXX.Flags := $(filter-out -fomit-frame-pointer,$(CXX.Flags))
+   C.Flags   := $(filter-out -fomit-frame-pointer,$(C.Flags))
+   LD.Flags  := $(filter-out -fomit-frame-pointer,$(LD.Flags))
+@@ -371,6 +379,8 @@
+ # If REQUIRES_RTTI=1 is specified then don't disable run-time type id.
+ ifneq ($(REQUIRES_RTTI), 1)
+   CXX.Flags += -fno-rtti
++else
++  CXX.Flags += -frtti
+ endif
+ 
+ ifeq ($(ENABLE_COVERAGE),1)
+--- include/llvm/ADT/DenseMap.h	2015-10-05 11:01:32.000000000 -0700
++++ include/llvm/ADT/DenseMap.h	2016-01-24 14:13:03.000000000 -0800
+@@ -254,7 +254,7 @@
+   DenseMapBase() {}
+ 
+   void destroyAll() {
+-    if ((getNumBuckets() == 0) || empty()) // Nothing to do.
++    if (getNumBuckets() == 0) // Nothing to do.
+       return;
+ 
+     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
+@@ -264,10 +264,6 @@
+         P->getSecond().~ValueT();
+       P->getFirst().~KeyT();
+     }
+-
+-#ifndef NDEBUG
+-    memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets());
+-#endif
+   }
+ 
+   void initEmpty() {
+@@ -856,7 +852,8 @@
+ 
+       // First move the inline buckets into a temporary storage.
+       AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
+-      BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
++      BucketT *TmpBegin =
++        reinterpret_cast<BucketT*>(reinterpret_cast<void*>(TmpStorage.buffer));
+       BucketT *TmpEnd = TmpBegin;
+ 
+       // Loop over the buckets, moving non-empty, non-tombstones into the
+@@ -940,17 +937,22 @@
+     // Note that this cast does not violate aliasing rules as we assert that
+     // the memory's dynamic type is the small, inline bucket buffer, and the
+     // 'storage.buffer' static type is 'char *'.
+-    return reinterpret_cast<const BucketT *>(storage.buffer);
++    return reinterpret_cast<const BucketT*>(
++      reinterpret_cast<const void*>(storage.buffer));
+   }
++
+   BucketT *getInlineBuckets() {
+     return const_cast<BucketT *>(
+       const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
+   }
++
+   const LargeRep *getLargeRep() const {
+     assert(!Small);
+     // Note, same rule about aliasing as with getInlineBuckets.
+-    return reinterpret_cast<const LargeRep *>(storage.buffer);
++    return reinterpret_cast<const LargeRep*>(
++      reinterpret_cast<const void*>(storage.buffer));
+   }
++
+   LargeRep *getLargeRep() {
+     return const_cast<LargeRep *>(
+       const_cast<const SmallDenseMap *>(this)->getLargeRep());
+--- include/llvm/ADT/Optional.h	2014-09-30 19:12:35.000000000 -0700
++++ include/llvm/ADT/Optional.h	2015-12-07 14:59:03.998240128 -0800
+@@ -163,16 +163,34 @@
+     reset();
+   }
+ 
+-  const T* getPointer() const { assert(hasVal); return reinterpret_cast<const T*>(storage.buffer); }
+-  T* getPointer() { assert(hasVal); return reinterpret_cast<T*>(storage.buffer); }
+-  const T& getValue() const LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
++  const T* getPointer() const {
++    assert(hasVal);
++    return reinterpret_cast<const T*>(
++      reinterpret_cast<const void*>(storage.buffer));
++  }
++
++  T* getPointer() {
++    assert(hasVal);
++    return reinterpret_cast<T*>(
++      reinterpret_cast<void*>(storage.buffer));
++  }
++
++  const T& getValue() const LLVM_LVALUE_FUNCTION {
++    assert(hasVal);
++    return *getPointer();
++  }
++
+   T& getValue() LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
+ 
+   LLVM_EXPLICIT operator bool() const { return hasVal; }
+   bool hasValue() const { return hasVal; }
+   const T* operator->() const { return getPointer(); }
+   T* operator->() { return getPointer(); }
+-  const T& operator*() const LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
++  const T& operator*() const LLVM_LVALUE_FUNCTION {
++    assert(hasVal);
++    return *getPointer();
++  }
++
+   T& operator*() LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
+ 
+   template <typename U>
+--- include/llvm/ADT/ilist.h	2014-07-28 17:38:55.000000000 -0700
++++ include/llvm/ADT/ilist.h	2015-11-10 13:51:33.696789150 -0800
+@@ -104,6 +104,53 @@
+   }
+ };
+ 
++template <typename NodeTy> class ilist_half_node;
++template <typename NodeTy> class ilist_node;
++
++/// Traits with an embedded ilist_node as a sentinel.
++///
++/// FIXME: The downcast in createSentinel() is UB.
++template <typename NodeTy> struct ilist_embedded_sentinel_traits {
++  /// Get hold of the node that marks the end of the list.
++  NodeTy *createSentinel() const {
++    // Since i(p)lists always publicly derive from their corresponding traits,
++    // placing a data member in this class will augment the i(p)list.  But since
++    // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
++    // there is a legal viable downcast from it to NodeTy. We use this trick to
++    // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
++    // sentinel. Dereferencing the sentinel is forbidden (save the
++    // ilist_node<NodeTy>), so no one will ever notice the superposition.
++    return static_cast<NodeTy *>(&Sentinel);
++  }
++  static void destroySentinel(NodeTy *) {}
++
++  NodeTy *provideInitialHead() const { return createSentinel(); }
++  NodeTy *ensureHead(NodeTy *) const { return createSentinel(); }
++  static void noteHead(NodeTy *, NodeTy *) {}
++
++private:
++  mutable ilist_node<NodeTy> Sentinel;
++};
++
++/// Trait with an embedded ilist_half_node as a sentinel.
++///
++/// FIXME: The downcast in createSentinel() is UB.
++template <typename NodeTy> struct ilist_half_embedded_sentinel_traits {
++  /// Get hold of the node that marks the end of the list.
++  NodeTy *createSentinel() const {
++    // See comment in ilist_embedded_sentinel_traits::createSentinel().
++    return static_cast<NodeTy *>(&Sentinel);
++  }
++  static void destroySentinel(NodeTy *) {}
++
++  NodeTy *provideInitialHead() const { return createSentinel(); }
++  NodeTy *ensureHead(NodeTy *) const { return createSentinel(); }
++  static void noteHead(NodeTy *, NodeTy *) {}
++
++private:
++  mutable ilist_half_node<NodeTy> Sentinel;
++};
++
+ /// ilist_node_traits - A fragment for template traits for intrusive list
+ /// that provides default node related operations.
+ ///
+@@ -173,8 +220,8 @@
+   template<class T> void operator-(T) const;
+ public:
+ 
+-  ilist_iterator(pointer NP) : NodePtr(NP) {}
+-  ilist_iterator(reference NR) : NodePtr(&NR) {}
++  explicit ilist_iterator(pointer NP) : NodePtr(NP) {}
++  explicit ilist_iterator(reference NR) : NodePtr(&NR) {}
+   ilist_iterator() : NodePtr(nullptr) {}
+ 
+   // This is templated so that we can allow constructing a const iterator from
+@@ -191,8 +238,10 @@
+     return *this;
+   }
+ 
++  void reset(pointer NP) { NodePtr = NP; }
++
+   // Accessors...
+-  operator pointer() const {
++  explicit operator pointer() const {
+     return NodePtr;
+   }
+ 
+@@ -237,14 +286,14 @@
+ // These are to catch errors when people try to use them as random access
+ // iterators.
+ template<typename T>
+-void operator-(int, ilist_iterator<T>) LLVM_DELETED_FUNCTION;
++void operator-(int, ilist_iterator<T>) = delete;
+ template<typename T>
+-void operator-(ilist_iterator<T>,int) LLVM_DELETED_FUNCTION;
++void operator-(ilist_iterator<T>,int) = delete;
+ 
+ template<typename T>
+-void operator+(int, ilist_iterator<T>) LLVM_DELETED_FUNCTION;
++void operator+(int, ilist_iterator<T>) = delete;
+ template<typename T>
+-void operator+(ilist_iterator<T>,int) LLVM_DELETED_FUNCTION;
++void operator+(ilist_iterator<T>,int) = delete;
+ 
+ // operator!=/operator== - Allow mixed comparisons without dereferencing
+ // the iterator, which could very likely be pointing to end().
+@@ -332,8 +381,8 @@
+ 
+   // No fundamental reason why iplist can't be copyable, but the default
+   // copy/copy-assign won't do.
+-  iplist(const iplist &) LLVM_DELETED_FUNCTION;
+-  void operator=(const iplist &) LLVM_DELETED_FUNCTION;
++  iplist(const iplist &) = delete;
++  void operator=(const iplist &) = delete;
+ 
+ public:
+   typedef NodeTy *pointer;
+@@ -422,7 +471,7 @@
+     this->setPrev(CurNode, New);
+ 
+     this->addNodeToList(New);  // Notify traits that we added a node...
+-    return New;
++    return iterator(New);
+   }
+ 
+   iterator insertAfter(iterator where, NodeTy *New) {
+@@ -443,7 +492,7 @@
+     else
+       Head = NextNode;
+     this->setPrev(NextNode, PrevNode);
+-    IT = NextNode;
++    IT.reset(NextNode);
+     this->removeNodeFromList(Node);  // Notify traits that we removed a node...
+ 
+     // Set the next/prev pointers of the current node to null.  This isn't
+@@ -461,12 +510,18 @@
+     return remove(MutIt);
+   }
+ 
++  NodeTy *remove(NodeTy *IT) { return remove(iterator(IT)); }
++  NodeTy *remove(NodeTy &IT) { return remove(iterator(IT)); }
++
+   // erase - remove a node from the controlled sequence... and delete it.
+   iterator erase(iterator where) {
+     this->deleteNode(remove(where));
+     return where;
+   }
+ 
++  iterator erase(NodeTy *IT) { return erase(iterator(IT)); }
++  iterator erase(NodeTy &IT) { return erase(iterator(IT)); }
++
+   /// Remove all nodes from the list like clear(), but do not call
+   /// removeNodeFromList() or deleteNode().
+   ///
+@@ -522,7 +577,7 @@
+       this->setNext(Last, PosNext);
+       this->setPrev(PosNext, Last);
+ 
+-      this->transferNodesFromList(L2, First, PosNext);
++      this->transferNodesFromList(L2, iterator(First), iterator(PosNext));
+ 
+       // Now that everything is set, restore the pointers to the list sentinels.
+       L2.setTail(L2Sentinel);
+@@ -579,6 +634,59 @@
+   void splice(iterator where, iplist &L2, iterator first, iterator last) {
+     if (first != last) transfer(where, L2, first, last);
+   }
++  void splice(iterator where, iplist &L2, NodeTy &N) {
++    splice(where, L2, iterator(N));
++  }
++  void splice(iterator where, iplist &L2, NodeTy *N) {
++    splice(where, L2, iterator(N));
++  }
++
++  template <class Compare>
++  void merge(iplist &Right, Compare comp) {
++    if (this == &Right)
++      return;
++    iterator First1 = begin(), Last1 = end();
++    iterator First2 = Right.begin(), Last2 = Right.end();
++    while (First1 != Last1 && First2 != Last2) {
++      if (comp(*First2, *First1)) {
++        iterator Next = First2;
++        transfer(First1, Right, First2, ++Next);
++        First2 = Next;
++      } else {
++        ++First1;
++      }
++    }
++    if (First2 != Last2)
++      transfer(Last1, Right, First2, Last2);
++  }
++  void merge(iplist &Right) { return merge(Right, op_less); }
++
++  template <class Compare>
++  void sort(Compare comp) {
++    // The list is empty, vacuously sorted.
++    if (empty())
++      return;
++    // The list has a single element, vacuously sorted.
++    if (std::next(begin()) == end())
++      return;
++    // Find the split point for the list.
++    iterator Center = begin(), End = begin();
++    while (End != end() && std::next(End) != end()) {
++      Center = std::next(Center);
++      End = std::next(std::next(End));
++    }
++    // Split the list into two.
++    iplist RightHalf;
++    RightHalf.splice(RightHalf.begin(), *this, Center, end());
++
++    // Sort the two sublists.
++    sort(comp);
++    RightHalf.sort(comp);
++
++    // Merge the two sublists back together.
++    merge(RightHalf, comp);
++  }
++  void sort() { sort(op_less); }
+ };
+ 
+ 
+--- include/llvm/ADT/ilist_node.h	2014-08-13 09:26:38.000000000 -0700
++++ include/llvm/ADT/ilist_node.h	2015-11-02 09:17:47.446456035 -0800
+@@ -19,12 +19,15 @@
+ 
+ template<typename NodeTy>
+ struct ilist_traits;
++template <typename NodeTy> struct ilist_embedded_sentinel_traits;
++template <typename NodeTy> struct ilist_half_embedded_sentinel_traits;
+ 
+ /// ilist_half_node - Base class that provides prev services for sentinels.
+ ///
+ template<typename NodeTy>
+ class ilist_half_node {
+   friend struct ilist_traits<NodeTy>;
++  friend struct ilist_half_embedded_sentinel_traits<NodeTy>;
+   NodeTy *Prev;
+ protected:
+   NodeTy *getPrev() { return Prev; }
+@@ -36,6 +39,8 @@
+ template<typename NodeTy>
+ struct ilist_nextprev_traits;
+ 
++template <typename NodeTy> class ilist_iterator;
++
+ /// ilist_node - Base class that provides next/prev services for nodes
+ /// that use ilist_nextprev_traits or ilist_default_traits.
+ ///
+@@ -43,6 +48,8 @@
+ class ilist_node : private ilist_half_node<NodeTy> {
+   friend struct ilist_nextprev_traits<NodeTy>;
+   friend struct ilist_traits<NodeTy>;
++  friend struct ilist_half_embedded_sentinel_traits<NodeTy>;
++  friend struct ilist_embedded_sentinel_traits<NodeTy>;
+   NodeTy *Next;
+   NodeTy *getNext() { return Next; }
+   const NodeTy *getNext() const { return Next; }
+@@ -51,6 +58,15 @@
+   ilist_node() : Next(nullptr) {}
+ 
+ public:
++  ilist_iterator<NodeTy> getIterator() {
++    // FIXME: Stop downcasting to create the iterator (potential UB).
++    return ilist_iterator<NodeTy>(static_cast<NodeTy *>(this));
++  }
++  ilist_iterator<const NodeTy> getIterator() const {
++    // FIXME: Stop downcasting to create the iterator (potential UB).
++    return ilist_iterator<const NodeTy>(static_cast<const NodeTy *>(this));
++  }
++
+   /// @name Adjacent Node Accessors
+   /// @{
+ 
+--- include/llvm/CodeGen/CommandFlags.h	2015-01-13 21:24:33.000000000 -0800
++++ include/llvm/CodeGen/CommandFlags.h	2016-01-26 14:46:39.000000000 -0800
+@@ -31,7 +31,7 @@
+ MCPU("mcpu",
+      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
+      cl::value_desc("cpu-name"),
+-     cl::init(""));
++     cl::init(std::string("")));
+ 
+ cl::list<std::string>
+ MAttrs("mattr",
+@@ -177,7 +177,7 @@
+ cl::opt<std::string>
+ TrapFuncName("trap-func", cl::Hidden,
+         cl::desc("Emit a call to trap function rather than a trap instruction"),
+-        cl::init(""));
++        cl::init(std::string("")));
+ 
+ cl::opt<bool>
+ EnablePIE("enable-pie",
+@@ -192,11 +192,11 @@
+ cl::opt<std::string> StopAfter("stop-after",
+                             cl::desc("Stop compilation after a specific pass"),
+                             cl::value_desc("pass-name"),
+-                                      cl::init(""));
++                                      cl::init(std::string("")));
+ cl::opt<std::string> StartAfter("start-after",
+                           cl::desc("Resume compilation after a specific pass"),
+                           cl::value_desc("pass-name"),
+-                          cl::init(""));
++                          cl::init(std::string("")));
+ 
+ cl::opt<bool> DataSections("data-sections",
+                            cl::desc("Emit data into separate sections"),
+@@ -258,7 +258,7 @@
+ // CFI.
+ cl::opt<std::string>
+ CFIFuncName("cfi-func-name", cl::desc("The name of the CFI function to call"),
+-            cl::init(""));
++            cl::init(std::string("")));
+ 
+ // Common utility function tightly tied to the options listed here. Initializes
+ // a TargetOptions object with CodeGen flags and returns it.
+--- include/llvm/CodeGen/MachineBasicBlock.h	2014-11-13 16:34:59.000000000 -0800
++++ include/llvm/CodeGen/MachineBasicBlock.h	2015-12-06 12:31:19.423838338 -0800
+@@ -165,7 +165,7 @@
+     Ty &operator*() const { return *MII; }
+     Ty *operator->() const { return &operator*(); }
+ 
+-    operator Ty*() const { return MII; }
++    operator Ty*() const { return MII.getNodePtrUnchecked(); }
+ 
+     bool operator==(const bundle_iterator &x) const {
+       return MII == x.MII;
+--- include/llvm/CodeGen/MachineFunction.h	2015-01-06 12:05:02.000000000 -0800
++++ include/llvm/CodeGen/MachineFunction.h	2015-12-06 20:18:16.623633498 -0800
+@@ -352,12 +352,10 @@
+     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
+   }
+ 
+-  void remove(iterator MBBI) {
+-    BasicBlocks.remove(MBBI);
+-  }
+-  void erase(iterator MBBI) {
+-    BasicBlocks.erase(MBBI);
+-  }
++  void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
++  void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
++  void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
++  void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
+ 
+   //===--------------------------------------------------------------------===//
+   // Internal functions used to automatically number MachineBasicBlocks
+--- include/llvm/CodeGen/MachineInstrBuilder.h	2014-10-31 16:19:46.000000000 -0700
++++ include/llvm/CodeGen/MachineInstrBuilder.h	2015-12-06 13:48:56.344154780 -0800
+@@ -280,7 +280,7 @@
+                                    const MCInstrDesc &MCID,
+                                    unsigned DestReg) {
+   if (I->isInsideBundle()) {
+-    MachineBasicBlock::instr_iterator MII = I;
++    MachineBasicBlock::instr_iterator MII(I);
+     return BuildMI(BB, MII, DL, MCID, DestReg);
+   }
+ 
+@@ -317,7 +317,7 @@
+                                    DebugLoc DL,
+                                    const MCInstrDesc &MCID) {
+   if (I->isInsideBundle()) {
+-    MachineBasicBlock::instr_iterator MII = I;
++    MachineBasicBlock::instr_iterator MII(I);
+     return BuildMI(BB, MII, DL, MCID);
+   }
+ 
+@@ -472,7 +472,7 @@
+     if (I == Begin) {
+       if (!empty())
+         MI->bundleWithSucc();
+-      Begin = MI;
++      Begin = MI->getIterator();
+       return *this;
+     }
+     if (I == End) {
+--- include/llvm/CodeGen/MachineInstrBundle.h	2014-04-13 17:51:57.000000000 -0700
++++ include/llvm/CodeGen/MachineInstrBundle.h	2015-12-06 12:35:51.016366535 -0800
+@@ -44,23 +44,23 @@
+ /// getBundleStart - Returns the first instruction in the bundle containing MI.
+ ///
+ inline MachineInstr *getBundleStart(MachineInstr *MI) {
+-  MachineBasicBlock::instr_iterator I = MI;
++  MachineBasicBlock::instr_iterator I(MI);
+   while (I->isBundledWithPred())
+     --I;
+-  return I;
++  return &*I;
+ }
+ 
+ inline const MachineInstr *getBundleStart(const MachineInstr *MI) {
+-  MachineBasicBlock::const_instr_iterator I = MI;
++  MachineBasicBlock::const_instr_iterator I(MI);
+   while (I->isBundledWithPred())
+     --I;
+-  return I;
++  return &*I;
+ }
+ 
+ /// Return an iterator pointing beyond the bundle containing MI.
+ inline MachineBasicBlock::instr_iterator
+ getBundleEnd(MachineInstr *MI) {
+-  MachineBasicBlock::instr_iterator I = MI;
++  MachineBasicBlock::instr_iterator I(MI);
+   while (I->isBundledWithSucc())
+     ++I;
+   return ++I;
+@@ -69,7 +69,7 @@
+ /// Return an iterator pointing beyond the bundle containing MI.
+ inline MachineBasicBlock::const_instr_iterator
+ getBundleEnd(const MachineInstr *MI) {
+-  MachineBasicBlock::const_instr_iterator I = MI;
++  MachineBasicBlock::const_instr_iterator I(MI);
+   while (I->isBundledWithSucc())
+     ++I;
+   return ++I;
+@@ -116,10 +116,10 @@
+   ///
+   explicit MachineOperandIteratorBase(MachineInstr *MI, bool WholeBundle) {
+     if (WholeBundle) {
+-      InstrI = getBundleStart(MI);
++      InstrI = getBundleStart(MI)->getIterator();
+       InstrE = MI->getParent()->instr_end();
+     } else {
+-      InstrI = InstrE = MI;
++      InstrI = InstrE = MI->getIterator();
+       ++InstrE;
+     }
+     OpI = InstrI->operands_begin();
+--- include/llvm/CodeGen/SlotIndexes.h	2014-04-13 17:51:57.000000000 -0700
++++ include/llvm/CodeGen/SlotIndexes.h	2015-12-06 13:26:01.031361628 -0800
+@@ -427,11 +427,11 @@
+     /// Returns the next non-null index, if one exists.
+     /// Otherwise returns getLastIndex().
+     SlotIndex getNextNonNullIndex(SlotIndex Index) {
+-      IndexList::iterator I = Index.listEntry();
++      IndexList::iterator I = Index.listEntry()->getIterator();
+       IndexList::iterator E = indexList.end();
+       while (++I != E)
+         if (I->getInstr())
+-          return SlotIndex(I, Index.getSlot());
++          return SlotIndex(&*I, Index.getSlot());
+       // We reached the end of the function.
+       return getLastIndex();
+     }
+@@ -580,11 +580,11 @@
+       IndexList::iterator prevItr, nextItr;
+       if (Late) {
+         // Insert mi's index immediately before the following instruction.
+-        nextItr = getIndexAfter(mi).listEntry();
++        nextItr = getIndexAfter(mi).listEntry()->getIterator();
+         prevItr = std::prev(nextItr);
+       } else {
+         // Insert mi's index immediately after the preceding instruction.
+-        prevItr = getIndexBefore(mi).listEntry();
++        prevItr = getIndexBefore(mi).listEntry()->getIterator();
+         nextItr = std::next(prevItr);
+       }
+ 
+@@ -646,11 +646,11 @@
+       if (nextMBB == mbb->getParent()->end()) {
+         startEntry = &indexList.back();
+         endEntry = createEntry(nullptr, 0);
+-        newItr = indexList.insertAfter(startEntry, endEntry);
++        newItr = indexList.insertAfter(startEntry->getIterator(), endEntry);
+       } else {
+         startEntry = createEntry(nullptr, 0);
+-        endEntry = getMBBStartIdx(nextMBB).listEntry();
+-        newItr = indexList.insert(endEntry, startEntry);
++        endEntry = getMBBStartIdx(&*nextMBB).listEntry();
++        newItr = indexList.insert(endEntry->getIterator(), startEntry);
+       }
+ 
+       SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
+--- include/llvm/IR/IRBuilder.h	2014-12-30 06:28:14.000000000 -0800
++++ include/llvm/IR/IRBuilder.h	2015-11-24 09:08:00.970126898 -0800
+@@ -58,9 +58,10 @@
+   FastMathFlags FMF;
+ public:
+ 
+-  IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
+-    : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
+-    ClearInsertionPoint();
++  IRBuilderBase(LLVMContext &Ctx, MDNode *FPMathTag = nullptr)
++    : CurDbgLocation(), BB(nullptr), InsertPt(),
++    Context(Ctx), DefaultFPMathTag(FPMathTag), FMF() {
++    // ClearInsertionPoint();
+   }
+ 
+   //===--------------------------------------------------------------------===//
+@@ -71,7 +72,7 @@
+   /// inserted into a block.
+   void ClearInsertionPoint() {
+     BB = nullptr;
+-    InsertPt = nullptr;
++    InsertPt.reset(nullptr);
+   }
+ 
+   BasicBlock *GetInsertBlock() const { return BB; }
+@@ -89,8 +90,8 @@
+   /// the specified instruction.
+   void SetInsertPoint(Instruction *I) {
+     BB = I->getParent();
+-    InsertPt = I;
+-    assert(I != BB->end() && "Can't read debug loc from end()");
++    InsertPt = I->getIterator();
++    assert(InsertPt != BB->end() && "Can't read debug loc from end()");
+     SetCurrentDebugLocation(I->getDebugLoc());
+   }
+ 
+@@ -99,6 +100,8 @@
+   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
+     BB = TheBB;
+     InsertPt = IP;
++    if (IP != TheBB->end())
++      SetCurrentDebugLocation(IP->getDebugLoc());
+   }
+ 
+   /// \brief Find the nearest point that dominates this use, and specify that
+@@ -107,10 +110,12 @@
+     Instruction *UseInst = cast<Instruction>(U.getUser());
+     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
+       BasicBlock *PredBB = Phi->getIncomingBlock(U);
+-      assert(U != PredBB->getTerminator() && "critical edge not split");
+-      SetInsertPoint(PredBB, PredBB->getTerminator());
++      TerminatorInst *TI = PredBB->getTerminator();
++      assert(U != TI && "critical edge not split");
++      SetInsertPoint(PredBB, TI->getIterator());
+       return;
+     }
++
+     SetInsertPoint(UseInst);
+   }
+ 
+--- include/llvm/IR/Metadata.h	2015-10-05 11:01:32.758196248 -0700
++++ include/llvm/IR/Metadata.h	2015-11-27 09:20:10.357775627 -0800
+@@ -927,6 +927,71 @@
+   using ReplaceableMetadataImpl::replaceAllUsesWith;
+ };
+ 
++template <class T>
++class TypedMDOperandIterator : public std::iterator<std::input_iterator_tag, T*, std::ptrdiff_t, void, T*> {
++private:
++  MDNode::op_iterator I = nullptr;
++
++public:
++  TypedMDOperandIterator() = default;
++  explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
++  ~TypedMDOperandIterator() { }
++
++  T *operator*() const { return cast_or_null<T>(*I); }
++
++  TypedMDOperandIterator &operator++() {
++    ++I;
++    return *this;
++  }
++
++  TypedMDOperandIterator operator++(int) {
++    TypedMDOperandIterator Temp(*this);
++    ++I;
++    return Temp;
++  }
++
++  bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
++  bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
++};
++
++template<class T> class MDTupleTypedArrayWrapper {
++private:
++  const MDTuple *N = nullptr;
++
++public:
++  MDTupleTypedArrayWrapper() = default;
++  MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
++  ~MDTupleTypedArrayWrapper() { }
++
++  template<class U>
++  MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper<U> &Other,
++                           typename std::enable_if<std::is_convertible<U*, T*>::value>::type* = nullptr)
++  : N(Other.get()) { }
++
++  template<class U>
++  explicit MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper<U> &Other,
++                                    typename std::enable_if<!std::is_convertible<U*, T*>::value>::type* = nullptr)
++  : N(Other.get()) { }
++
++  explicit operator bool() const { return get(); }
++  explicit operator MDTuple *() const { return get(); }
++
++  MDTuple *get() const { return const_cast<MDTuple *>(N); }
++  MDTuple *operator->() const { return get(); }
++  MDTuple &operator*() const { return *get(); }
++
++  unsigned size() const { return N ? N->getNumOperands() : 0u; }
++  T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
++
++  typedef TypedMDOperandIterator<T> iterator;
++  iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
++  iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
++};
++
++#define HANDLE_METADATA(CLASS)                                                 \
++  typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
++#include "llvm/IR/Metadata.def"
++
+ //===----------------------------------------------------------------------===//
+ /// \brief A tuple of MDNodes.
+ ///
+--- include/llvm/MC/MCSection.h	2013-04-17 14:18:16.000000000 -0700
++++ include/llvm/MC/MCSection.h	2015-12-07 12:32:38.557027450 -0800
+@@ -15,6 +15,9 @@
+ #define LLVM_MC_MCSECTION_H
+ 
+ #include "llvm/ADT/StringRef.h"
++#include "llvm/ADT/ilist.h"
++#include "llvm/ADT/ilist_node.h"
++#include "llvm/MC/MCAssembler.h"
+ #include "llvm/MC/SectionKind.h"
+ #include "llvm/Support/Compiler.h"
+ 
+@@ -41,6 +44,14 @@
+     MCSection(SectionVariant V, SectionKind K) : Variant(V), Kind(K) {}
+     SectionVariant Variant;
+     SectionKind Kind;
++
++  public:
++    typedef iplist<MCFragment> FragmentListType;
++    typedef FragmentListType::const_iterator const_iterator;
++    typedef FragmentListType::iterator iterator;
++    typedef FragmentListType::const_reverse_iterator const_reverse_iterator;
++    typedef FragmentListType::reverse_iterator reverse_iterator;
++
+   public:
+     virtual ~MCSection();
+ 
+--- include/llvm/MC/MCTargetOptionsCommandFlags.h	2015-01-14 03:23:27.000000000 -0800
++++ include/llvm/MC/MCTargetOptionsCommandFlags.h	2016-01-26 19:29:37.000000000 -0800
+@@ -43,7 +43,7 @@
+ cl::opt<std::string>
+ ABIName("target-abi", cl::Hidden,
+         cl::desc("The name of the ABI to be targeted from the backend."),
+-        cl::init(""));
++        cl::init(std::string("")));
+ 
+ static inline MCTargetOptions InitMCTargetOptionsFromFlags() {
+   MCTargetOptions Options;
+--- include/llvm/Support/GenericDomTree.h	2015-01-14 02:33:21.000000000 -0800
++++ include/llvm/Support/GenericDomTree.h	2015-12-08 09:12:30.450453075 -0800
+@@ -715,7 +715,11 @@
+   /// recalculate - compute a dominator tree for the given function
+   template <class FT> void recalculate(FT &F) {
+     typedef GraphTraits<FT *> TraitsTy;
++    typedef typename GraphTraits<FT*>::ChildIteratorType TraitsTyChildIterator;
++    typedef typename GraphTraits<FT*>::nodes_iterator TraitsTyNodeIterator;
++
+     reset();
++
+     this->Vertex.push_back(nullptr);
+ 
+     if (!this->IsPostDominators) {
+@@ -728,19 +732,22 @@
+       Calculate<FT, NodeT *>(*this, F);
+     } else {
+       // Initialize the roots list
+-      for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
+-                                             E = TraitsTy::nodes_end(&F);
++      for (TraitsTyNodeIterator I = TraitsTy::nodes_begin(&F),
++                                E = TraitsTy::nodes_end(&F);
+            I != E; ++I) {
+-        if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
+-          addRoot(I);
++        TraitsTyChildIterator ChildBegin(TraitsTy::child_begin(&*I));
++        TraitsTyChildIterator ChildEnd(TraitsTy::child_end(&*I));
++
++        if (ChildBegin == ChildEnd)
++          addRoot(&*I);
+ 
+         // Prepopulate maps so that we don't get iterator invalidation issues
+         // later.
+-        this->IDoms[I] = nullptr;
+-        this->DomTreeNodes[I] = nullptr;
++        this->IDoms[&*I] = nullptr;
++        this->DomTreeNodes[&*I] = nullptr;
+       }
+ 
+-      Calculate<FT, Inverse<NodeT *>>(*this, F);
++      Calculate<FT, Inverse<NodeT*> >(*this, F);
+     }
+   }
+ };
+--- include/llvm/Transforms/Utils/SSAUpdaterImpl.h	2014-04-21 15:55:11.000000000 -0700
++++ include/llvm/Transforms/Utils/SSAUpdaterImpl.h	2015-11-29 13:46:28.070241785 -0800
+@@ -378,7 +378,7 @@
+   void FindExistingPHI(BlkT *BB, BlockListTy *BlockList) {
+     for (typename BlkT::iterator BBI = BB->begin(), BBE = BB->end();
+          BBI != BBE; ++BBI) {
+-      PhiT *SomePHI = Traits::InstrIsPHI(BBI);
++      PhiT *SomePHI = Traits::InstrIsPHI(&*BBI);
+       if (!SomePHI)
+         break;
+       if (CheckIfPHIMatches(SomePHI)) {
+--- lib/Analysis/AliasAnalysisEvaluator.cpp	2014-07-24 05:16:19.000000000 -0700
++++ lib/Analysis/AliasAnalysisEvaluator.cpp	2015-11-27 17:10:53.853958210 -0800
+@@ -146,9 +146,9 @@
+   SetVector<Value *> Loads;
+   SetVector<Value *> Stores;
+ 
+-  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
+-    if (I->getType()->isPointerTy())    // Add all pointer arguments.
+-      Pointers.insert(I);
++  for (auto &I : F.args())
++    if (I.getType()->isPointerTy())    // Add all pointer arguments.
++      Pointers.insert(&I);
+ 
+   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
+     if (I->getType()->isPointerTy()) // Add all pointer instructions.
+--- lib/Analysis/AliasAnalysis.cpp	2014-12-15 06:09:53.000000000 -0800
++++ lib/Analysis/AliasAnalysis.cpp	2015-11-27 09:33:58.058293495 -0800
+@@ -501,12 +501,12 @@
+                                               const ModRefResult Mode) {
+   assert(I1.getParent() == I2.getParent() &&
+          "Instructions not in same basic block!");
+-  BasicBlock::const_iterator I = &I1;
+-  BasicBlock::const_iterator E = &I2;
++  BasicBlock::const_iterator I = I1.getIterator();
++  BasicBlock::const_iterator E = I2.getIterator();
+   ++E;  // Convert from inclusive to exclusive range.
+ 
+   for (; I != E; ++I) // Check every instruction in range
+-    if (getModRefInfo(I, Loc) & Mode)
++    if (getModRefInfo(&(*I), Loc) & Mode)
+       return true;
+   return false;
+ }
+--- lib/Analysis/AliasSetTracker.cpp	2014-11-19 11:36:18.000000000 -0800
++++ lib/Analysis/AliasSetTracker.cpp	2015-11-27 09:52:20.756423865 -0800
+@@ -229,8 +229,8 @@
+     iterator Cur = I++;
+     if (Cur->Forward || !Cur->aliasesPointer(Ptr, Size, AAInfo, AA)) continue;
+     
+-    if (!FoundSet) {      // If this is the first alias set ptr can go into.
+-      FoundSet = Cur;     // Remember it.
++    if (!FoundSet) {        // If this is the first alias set ptr can go into.
++      FoundSet = &(*Cur);   // Remember it.
+     } else {              // Otherwise, we must merge the sets.
+       FoundSet->mergeSetIn(*Cur, *this);     // Merge in contents.
+     }
+@@ -264,16 +264,13 @@
+     if (Cur->Forward || !Cur->aliasesUnknownInst(Inst, AA))
+       continue;
+     if (!FoundSet)            // If this is the first alias set ptr can go into.
+-      FoundSet = Cur;         // Remember it.
++      FoundSet = &(*Cur);     // Remember it.
+     else if (!Cur->Forward)   // Otherwise, we must merge the sets.
+       FoundSet->mergeSetIn(*Cur, *this);     // Merge in contents.
+   }
+   return FoundSet;
+ }
+ 
+-
+-
+-
+ /// getAliasSetForPointer - Return the alias set that the specified pointer
+ /// lives in.
+ AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, uint64_t Size,
+@@ -287,13 +284,13 @@
+     // Return the set!
+     return *Entry.getAliasSet(*this)->getForwardedTarget(*this);
+   }
+-  
++
+   if (AliasSet *AS = findAliasSetForPointer(Pointer, Size, AAInfo)) {
+     // Add it to the alias set it aliases.
+     AS->addPointer(*this, Entry, Size, AAInfo);
+     return *AS;
+   }
+-  
++
+   if (New) *New = true;
+   // Otherwise create a new alias set to hold the loaded pointer.
+   AliasSets.push_back(new AliasSet());
+@@ -379,8 +376,8 @@
+ }
+ 
+ void AliasSetTracker::add(BasicBlock &BB) {
+-  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
+-    add(I);
++  for (auto &I : BB)
++    add(&I);
+ }
+ 
+ void AliasSetTracker::add(const AliasSetTracker &AST) {
+--- lib/Analysis/BasicAliasAnalysis.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Analysis/BasicAliasAnalysis.cpp	2015-11-27 09:53:17.612141117 -0800
+@@ -1440,7 +1440,7 @@
+   // the Values cannot come from different iterations of a potential cycle the
+   // phi nodes could be involved in.
+   for (auto *P : VisitedPhiBBs)
+-    if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
++    if (isPotentiallyReachable(&P->front(), Inst, DT, LI))
+       return false;
+ 
+   return true;
+--- lib/Analysis/BlockFrequencyInfo.cpp	2014-06-26 15:52:05.000000000 -0700
++++ lib/Analysis/BlockFrequencyInfo.cpp	2015-11-27 09:55:32.251496178 -0800
+@@ -34,17 +34,17 @@
+ };
+ 
+ static cl::opt<GVDAGType>
+-ViewBlockFreqPropagationDAG("view-block-freq-propagation-dags", cl::Hidden,
+-          cl::desc("Pop up a window to show a dag displaying how block "
+-                   "frequencies propagation through the CFG."),
+-          cl::values(
+-            clEnumValN(GVDT_None, "none",
+-                       "do not display graphs."),
+-            clEnumValN(GVDT_Fraction, "fraction", "display a graph using the "
+-                       "fractional block frequency representation."),
+-            clEnumValN(GVDT_Integer, "integer", "display a graph using the raw "
+-                       "integer fractional block frequency representation."),
+-            clEnumValEnd));
++ViewBlockFreqPropagationDAG("view-block-freq-propagation-dags",
++                            cl::Hidden,
++                            cl::desc("Pop up a window to show a dag displaying how block "
++                                     "frequencies propagation through the CFG."),
++                            cl::values(clEnumValN(GVDT_None, "none",
++                                                  "do not display graphs."),
++                                       clEnumValN(GVDT_Fraction, "fraction", "display a graph using the "
++                                                  "fractional block frequency representation."),
++                                       clEnumValN(GVDT_Integer, "integer", "display a graph using the raw "
++                                                  "integer fractional block frequency representation."),
++                                       clEnumValEnd));
+ 
+ namespace llvm {
+ 
+@@ -55,8 +55,9 @@
+   typedef Function::const_iterator nodes_iterator;
+ 
+   static inline const NodeType *getEntryNode(const BlockFrequencyInfo *G) {
+-    return G->getFunction()->begin();
++    return &(G->getFunction()->front());
+   }
++
+   static ChildIteratorType child_begin(const NodeType *N) {
+     return succ_begin(N);
+   }
+--- lib/Analysis/BranchProbabilityInfo.cpp	2014-12-09 10:38:53.000000000 -0800
++++ lib/Analysis/BranchProbabilityInfo.cpp	2015-11-27 09:59:58.010012465 -0800
+@@ -529,11 +529,10 @@
+   // We print the probabilities from the last function the analysis ran over,
+   // or the function it is currently running over.
+   assert(LastF && "Cannot print prior to running over a function");
+-  for (Function::const_iterator BI = LastF->begin(), BE = LastF->end();
+-       BI != BE; ++BI) {
+-    for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI);
++  for (const auto &BI : *LastF) {
++    for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI);
+          SI != SE; ++SI) {
+-      printEdgeProbability(OS << "  ", BI, *SI);
++      printEdgeProbability(OS << "  ", &BI, *SI);
+     }
+   }
+ }
+--- lib/Analysis/CFG.cpp	2015-01-12 19:46:47.000000000 -0800
++++ lib/Analysis/CFG.cpp	2015-11-27 10:13:16.659243122 -0800
+@@ -204,8 +204,9 @@
+       return true;
+ 
+     // Linear scan, start at 'A', see whether we hit 'B' or the end first.
+-    for (BasicBlock::const_iterator I = A, E = BB->end(); I != E; ++I) {
+-      if (&*I == B)
++    for (BasicBlock::const_iterator I = A->getIterator(), E = BB->end();
++         I != E; ++I) {
++      if (&(*I) == B)
+         return true;
+     }
+ 
+--- lib/Analysis/CodeMetrics.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Analysis/CodeMetrics.cpp	2015-11-27 10:14:02.544976823 -0800
+@@ -115,7 +115,7 @@
+   for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
+        II != E; ++II) {
+     // Skip ephemeral values.
+-    if (EphValues.count(II))
++    if (EphValues.count(&(*II)))
+       continue;
+ 
+     // Special handling for calls.
+--- lib/Analysis/CostModel.cpp	2014-07-03 15:24:18.000000000 -0700
++++ lib/Analysis/CostModel.cpp	2015-11-27 10:20:35.600601500 -0800
+@@ -524,7 +524,7 @@
+ 
+   for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
+     for (BasicBlock::iterator it = B->begin(), e = B->end(); it != e; ++it) {
+-      Instruction *Inst = it;
++      Instruction *Inst = &(*it);
+       unsigned Cost = getInstructionCost(Inst);
+       if (Cost != (unsigned)-1)
+         OS << "Cost Model: Found an estimated cost of " << Cost;
+--- lib/Analysis/IPA/CallGraph.cpp	2014-08-07 13:41:17.000000000 -0700
++++ lib/Analysis/IPA/CallGraph.cpp	2015-11-27 17:17:06.153920405 -0800
+@@ -25,7 +25,7 @@
+       CallsExternalNode(new CallGraphNode(nullptr)) {
+   // Add every function to the call graph.
+   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+-    addToCallGraph(I);
++    addToCallGraph(&*I);
+ 
+   // If we didn't find a main function, use the external call graph node
+   if (!Root)
+--- lib/Analysis/IPA/GlobalsModRef.cpp	2014-05-08 10:57:50.000000000 -0700
++++ lib/Analysis/IPA/GlobalsModRef.cpp	2015-11-27 17:21:08.993461915 -0800
+@@ -209,9 +209,9 @@
+   std::vector<Function*> Readers, Writers;
+   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+     if (I->hasLocalLinkage()) {
+-      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
++      if (!AnalyzeUsesOfPointer(&*I, Readers, Writers)) {
+         // Remember that we are tracking this global.
+-        NonAddressTakenGlobals.insert(I);
++        NonAddressTakenGlobals.insert(&*I);
+         ++NumNonAddrTakenFunctions;
+       }
+       Readers.clear(); Writers.clear();
+@@ -220,24 +220,26 @@
+   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+        I != E; ++I)
+     if (I->hasLocalLinkage()) {
+-      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
++      if (!AnalyzeUsesOfPointer(&*I, Readers, Writers)) {
+         // Remember that we are tracking this global, and the mod/ref fns
+-        NonAddressTakenGlobals.insert(I);
++        NonAddressTakenGlobals.insert(&*I);
+ 
+         for (unsigned i = 0, e = Readers.size(); i != e; ++i)
+-          FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
++          FunctionInfo[Readers[i]].GlobalInfo[&*I] |= Ref;
+ 
+         if (!I->isConstant())  // No need to keep track of writers to constants
+           for (unsigned i = 0, e = Writers.size(); i != e; ++i)
+-            FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
++            FunctionInfo[Writers[i]].GlobalInfo[&*I] |= Mod;
+         ++NumNonAddrTakenGlobalVars;
+ 
+         // If this global holds a pointer type, see if it is an indirect global.
+         if (I->getType()->getElementType()->isPointerTy() &&
+-            AnalyzeIndirectGlobalMemory(I))
++            AnalyzeIndirectGlobalMemory(&*I))
+           ++NumIndirectGlobalVars;
+       }
+-      Readers.clear(); Writers.clear();
++
++      Readers.clear();
++      Writers.clear();
+     }
+ }
+ 
+--- lib/Analysis/IPA/InlineCost.cpp	2015-02-12 13:28:02.000000000 -0800
++++ lib/Analysis/IPA/InlineCost.cpp	2015-11-27 17:25:16.116008808 -0800
+@@ -900,7 +900,7 @@
+       continue;
+ 
+     // Skip ephemeral values.
+-    if (EphValues.count(I))
++    if (EphValues.count(&*I))
+       continue;
+ 
+     ++NumInstructions;
+@@ -912,7 +912,7 @@
+     // all of the per-instruction logic. The visit tree returns true if we
+     // consumed the instruction in any way, and false if the instruction's base
+     // cost should count against inlining.
+-    if (Base::visit(I))
++    if (Base::visit(&*I))
+       ++NumInstructionsSimplified;
+     else
+       Cost += InlineConstants::InstrCost;
+@@ -1089,15 +1089,15 @@
+        FAI != FAE; ++FAI, ++CAI) {
+     assert(CAI != CS.arg_end());
+     if (Constant *C = dyn_cast<Constant>(CAI))
+-      SimplifiedValues[FAI] = C;
++      SimplifiedValues[&*FAI] = C;
+ 
+     Value *PtrArg = *CAI;
+     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
+-      ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
++      ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
+ 
+       // We can SROA any pointer arguments derived from alloca instructions.
+       if (isa<AllocaInst>(PtrArg)) {
+-        SROAArgValues[FAI] = PtrArg;
++        SROAArgValues[&*FAI] = PtrArg;
+         SROAArgCosts[PtrArg] = 0;
+       }
+     }
+@@ -1334,9 +1334,8 @@
+     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
+       return false;
+ 
+-    for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
+-         ++II) {
+-      CallSite CS(II);
++    for (auto &II : *BI) {
++      CallSite CS(&II);
+       if (!CS)
+         continue;
+ 
+--- lib/Analysis/IVUsers.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Analysis/IVUsers.cpp	2015-11-27 10:24:31.961529730 -0800
+@@ -248,7 +248,6 @@
+ }
+ 
+ bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
+-
+   L = l;
+   LI = &getAnalysis<LoopInfo>();
+   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
+@@ -260,7 +259,7 @@
+   // them by stride.  Start by finding all of the PHI nodes in the header for
+   // this loop.  If they are induction variables, inspect their uses.
+   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
+-    (void)AddUsersIfInteresting(I);
++    (void) AddUsersIfInteresting(&(*I));
+ 
+   return false;
+ }
+--- lib/Analysis/Lint.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Analysis/Lint.cpp	2015-11-27 10:28:34.901567525 -0800
+@@ -231,7 +231,8 @@
+     for (; AI != AE; ++AI) {
+       Value *Actual = *AI;
+       if (PI != PE) {
+-        Argument *Formal = PI++;
++        Argument *Formal = &(*PI);
++        PI++;
+         Assert1(Formal->getType() == Actual->getType(),
+                 "Undefined behavior: Call argument type mismatches "
+                 "callee parameter type", &I);
+@@ -609,8 +610,8 @@
+ 
+ void Lint::visitUnreachableInst(UnreachableInst &I) {
+   // This isn't undefined behavior, it's merely suspicious.
+-  Assert1(&I == I.getParent()->begin() ||
+-          std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
++  Assert1(&I == &(I.getParent()->front()) ||
++          std::prev(I.getIterator())->mayHaveSideEffects(),
+           "Unusual: unreachable immediately preceded by instruction without "
+           "side effects", &I);
+ }
+@@ -641,7 +642,7 @@
+   // TODO: Look through vector insert/extract/shuffle.
+   V = OffsetOk ? GetUnderlyingObject(V, DL) : V->stripPointerCasts();
+   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
+-    BasicBlock::iterator BBI = L;
++    BasicBlock::iterator BBI = L->getIterator();
+     BasicBlock *BB = L->getParent();
+     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
+     for (;;) {
+--- lib/Analysis/Loads.cpp	2014-11-25 00:20:27.000000000 -0800
++++ lib/Analysis/Loads.cpp	2015-11-27 17:11:12.096570890 -0800
+@@ -110,7 +110,8 @@
+   // from/to.  If so, the previous load or store would have already trapped,
+   // so there is no harm doing an extra load (also, CSE will later eliminate
+   // the load entirely).
+-  BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
++  BasicBlock::iterator BBI = ScanFrom->getIterator();
++  BasicBlock::iterator E = ScanFrom->getParent()->begin();
+ 
+   // We can at least always strip pointer casts even though we can't use the
+   // base here.
+@@ -189,7 +190,8 @@
+   while (ScanFrom != ScanBB->begin()) {
+     // We must ignore debug info directives when counting (otherwise they
+     // would affect codegen).
+-    Instruction *Inst = --ScanFrom;
++    --ScanFrom;
++    Instruction *Inst = &(*ScanFrom);
+     if (isa<DbgInfoIntrinsic>(Inst))
+       continue;
+ 
+--- lib/Analysis/MemoryBuiltins.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Analysis/MemoryBuiltins.cpp	2015-11-27 10:36:01.320964520 -0800
+@@ -642,7 +642,7 @@
+ 
+   // always generate code immediately before the instruction being
+   // processed, so that the generated code dominates the same BBs
+-  Instruction *PrevInsertPoint = Builder.GetInsertPoint();
++  BuilderTy::InsertPointGuard Guard(Builder);
+   if (Instruction *I = dyn_cast<Instruction>(V))
+     Builder.SetInsertPoint(I);
+ 
+@@ -671,9 +671,6 @@
+     Result = unknown();
+   }
+ 
+-  if (PrevInsertPoint)
+-    Builder.SetInsertPoint(PrevInsertPoint);
+-
+   // Don't reuse CacheIt since it may be invalid at this point.
+   CacheMap[V] = Result;
+   return Result;
+@@ -763,7 +760,7 @@
+ 
+   // compute offset/size for each PHI incoming pointer
+   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
+-    Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
++    Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
+     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
+ 
+     if (!bothKnown(EdgeData)) {
+--- lib/Analysis/MemoryDependenceAnalysis.cpp	2015-01-08 16:26:45.000000000 -0800
++++ lib/Analysis/MemoryDependenceAnalysis.cpp	2015-11-27 17:13:54.649752810 -0800
+@@ -215,7 +215,8 @@
+     if (!Limit)
+       return MemDepResult::getUnknown();
+ 
+-    Instruction *Inst = --ScanIt;
++    --ScanIt;
++    Instruction *Inst = &(*ScanIt);
+ 
+     // If this inst is a memory op, get the pointer it accessed
+     AliasAnalysis::Location Loc;
+@@ -415,7 +416,8 @@
+ 
+   // Walk backwards through the basic block, looking for dependencies.
+   while (ScanIt != BB->begin()) {
+-    Instruction *Inst = --ScanIt;
++    --ScanIt;
++    Instruction *Inst = &(*ScanIt);
+ 
+     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
+       // Debug intrinsics don't (and can't) cause dependencies.
+@@ -676,12 +678,14 @@
+       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
+         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
+ 
+-      LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
++      LocalCache = getPointerDependencyFrom(MemLoc, isLoad,
++                                            ScanPos->getIterator(),
+                                             QueryParent, QueryInst);
+     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
+       CallSite QueryCS(QueryInst);
+       bool isReadOnly = AA->onlyReadsMemory(QueryCS);
+-      LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
++      LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly,
++                                             ScanPos->getIterator(),
+                                              QueryParent);
+     } else
+       // Non-memory instruction.
+@@ -805,7 +809,7 @@
+     BasicBlock::iterator ScanPos = DirtyBB->end();
+     if (ExistingResult) {
+       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
+-        ScanPos = Inst;
++        ScanPos = Inst->getIterator();
+         // We're removing QueryInst's use of Inst.
+         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
+                              QueryCS.getInstruction());
+@@ -969,11 +973,11 @@
+     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
+            "Instruction invalidated?");
+     ++NumCacheDirtyNonLocalPtr;
+-    ScanPos = ExistingResult->getResult().getInst();
++    ScanPos = ExistingResult->getResult().getInst()->getIterator();
+ 
+     // Eliminating the dirty entry from 'Cache', so update the reverse info.
+     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
+-    RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
++    RemoveFromReverseMap(ReverseNonLocalPtrDeps, &(*ScanPos), CacheKey);
+   } else {
+     ++NumUncacheNonLocalPtr;
+   }
+@@ -1524,8 +1528,10 @@
+   // Using a dirty version of the instruction after RemInst saves having to scan
+   // the entire block to get to this point.
+   MemDepResult NewDirtyVal;
+-  if (!RemInst->isTerminator())
+-    NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
++  if (!RemInst->isTerminator()) {
++    ++RemInst;
++    NewDirtyVal = MemDepResult::getDirty(&*RemInst->getIterator());
++  }
+ 
+   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
+   if (ReverseDepIt != ReverseLocalDeps.end()) {
+--- lib/Analysis/ScalarEvolutionExpander.cpp	2015-03-16 14:15:49.000000000 -0700
++++ lib/Analysis/ScalarEvolutionExpander.cpp	2015-11-27 17:14:51.881419145 -0800
+@@ -59,7 +59,7 @@
+             // Create a new cast, and leave the old cast in place in case
+             // it is being used as an insert point. Clear its operand
+             // so that it doesn't hold anything live.
+-            Ret = CastInst::Create(Op, V, Ty, "", IP);
++            Ret = CastInst::Create(Op, V, Ty, "", &(*IP));
+             Ret->takeName(CI);
+             CI->replaceAllUsesWith(Ret);
+             CI->setOperand(0, UndefValue::get(V->getType()));
+@@ -71,12 +71,12 @@
+ 
+   // Create a new cast.
+   if (!Ret)
+-    Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
++    Ret = CastInst::Create(Op, V, Ty, V->getName(), &(*IP));
+ 
+   // We assert at the end of the function since IP might point to an
+   // instruction with different dominance properties than a cast
+   // (an invoke for example) and not dominate BIP (but the cast does).
+-  assert(SE.DT->dominates(Ret, BIP));
++  assert(SE.DT->dominates(Ret, &(*BIP)));
+ 
+   rememberInstruction(Ret);
+   return Ret;
+@@ -139,7 +139,8 @@
+ 
+   // Cast the instruction immediately after the instruction.
+   Instruction *I = cast<Instruction>(V);
+-  BasicBlock::iterator IP = I; ++IP;
++  ++I;
++  BasicBlock::iterator IP = I->getIterator();
+   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
+     IP = II->getNormalDest()->begin();
+   while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
+@@ -170,7 +171,7 @@
+         ScanLimit++;
+       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
+           IP->getOperand(1) == RHS)
+-        return IP;
++        return &(*IP);
+       if (IP == BlockBegin) break;
+     }
+   }
+@@ -186,7 +187,7 @@
+     if (!Preheader) break;
+ 
+     // Ok, move up a level.
+-    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
++    Builder.SetInsertPoint(Preheader->getTerminator());
+   }
+ 
+   // If we haven't found this binop, insert it.
+@@ -518,7 +519,8 @@
+        Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
+ 
+     assert(!isa<Instruction>(V) ||
+-           SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
++           SE.DT->dominates(cast<Instruction>(V),
++                            &(*Builder.GetInsertPoint())));
+ 
+     // Expand the operands for a plain byte offset.
+     Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
+@@ -542,7 +544,7 @@
+           ScanLimit++;
+         if (IP->getOpcode() == Instruction::GetElementPtr &&
+             IP->getOperand(0) == V && IP->getOperand(1) == Idx)
+-          return IP;
++          return &(*IP);
+         if (IP == BlockBegin) break;
+       }
+     }
+@@ -557,7 +559,7 @@
+       if (!Preheader) break;
+ 
+       // Ok, move up a level.
+-      Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
++      Builder.SetInsertPoint(Preheader->getTerminator());
+     }
+ 
+     // Emit a GEP.
+@@ -588,7 +590,7 @@
+     if (!Preheader) break;
+ 
+     // Ok, move up a level.
+-    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
++    Builder.SetInsertPoint(Preheader->getTerminator());
+   }
+ 
+   // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
+@@ -1168,8 +1170,8 @@
+   PostIncLoops.clear();
+ 
+   // Expand code for the start value.
+-  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
+-                                L->getHeader()->begin());
++  Value *StartV =
++    expandCodeFor(Normalized->getStart(), ExpandTy, &(L->getHeader()->front()));
+ 
+   // StartV must be hoisted into L's preheader to dominate the new phi.
+   assert(!isa<Instruction>(StartV) ||
+@@ -1186,7 +1188,7 @@
+   if (useSubtract)
+     Step = SE.getNegativeSCEV(Step);
+   // Expand the step somewhere that dominates the loop header.
+-  Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
++  Value *StepV = expandCodeFor(Step, IntTy, &(L->getHeader()->front()));
+ 
+   // Create the PHI.
+   BasicBlock *Header = L->getHeader();
+@@ -1297,7 +1299,7 @@
+     // or dominated by IVIncInsertPos.
+     if (isa<Instruction>(Result)
+         && !SE.DT->dominates(cast<Instruction>(Result),
+-                             Builder.GetInsertPoint())) {
++                             &(*Builder.GetInsertPoint()))) {
+       // The induction variable's postinc expansion does not dominate this use.
+       // IVUsers tries to prevent this case, so it is rare. However, it can
+       // happen when an IVUser outside the loop is not dominated by the latch
+@@ -1315,8 +1317,9 @@
+       {
+         // Expand the step somewhere that dominates the loop header.
+         BuilderType::InsertPointGuard Guard(Builder);
+-        StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
++        StepV = expandCodeFor(Step, IntTy, &(L->getHeader()->front()));
+       }
++
+       Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
+     }
+   }
+@@ -1395,7 +1398,7 @@
+            isa<LandingPadInst>(NewInsertPt))
+       ++NewInsertPt;
+     V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
+-                      NewInsertPt);
++                      &(*NewInsertPt));
+     return V;
+   }
+ 
+@@ -1436,7 +1439,7 @@
+     BasicBlock *Header = L->getHeader();
+     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
+     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
+-                                  Header->begin());
++                                  &(Header->front()));
+     rememberInstruction(CanonicalIV);
+ 
+     SmallSet<BasicBlock *, 4> PredSeen;
+@@ -1581,7 +1584,8 @@
+ 
+ Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
+                                    Instruction *IP) {
+-  Builder.SetInsertPoint(IP->getParent(), IP);
++  assert(IP && "Invalid Instruction argument!");
++  Builder.SetInsertPoint(IP);
+   return expandCodeFor(SH, Ty);
+ }
+ 
+@@ -1599,7 +1603,7 @@
+ Value *SCEVExpander::expand(const SCEV *S) {
+   // Compute an insertion point for this SCEV object. Hoist the instructions
+   // as far out in the loop nest as possible.
+-  Instruction *InsertPt = Builder.GetInsertPoint();
++  Instruction *InsertPt = &(*Builder.GetInsertPoint());
+   for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
+        L = L->getParentLoop())
+     if (SE.isLoopInvariant(S, L)) {
+@@ -1610,18 +1614,18 @@
+         // LSR sets the insertion point for AddRec start/step values to the
+         // block start to simplify value reuse, even though it's an invalid
+         // position. SCEVExpander must correct for this in all cases.
+-        InsertPt = L->getHeader()->getFirstInsertionPt();
++        InsertPt = &*L->getHeader()->getFirstInsertionPt();
+       }
+     } else {
+       // If the SCEV is computable at this level, insert it into the header
+       // after the PHIs (and after any other instructions that we've inserted
+       // there) so that it is guaranteed to dominate any user inside the loop.
+       if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
+-        InsertPt = L->getHeader()->getFirstInsertionPt();
++        InsertPt = &*L->getHeader()->getFirstInsertionPt();
+       while (InsertPt != Builder.GetInsertPoint()
+              && (isInsertedInstruction(InsertPt)
+                  || isa<DbgInfoIntrinsic>(InsertPt))) {
+-        InsertPt = std::next(BasicBlock::iterator(InsertPt));
++        InsertPt = &(*std::next(BasicBlock::iterator(InsertPt)));
+       }
+       break;
+     }
+@@ -1633,7 +1637,7 @@
+     return I->second;
+ 
+   BuilderType::InsertPointGuard Guard(Builder);
+-  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
++  Builder.SetInsertPoint(InsertPt);
+ 
+   // Expand the expression into instructions.
+   Value *V = visit(S);
+@@ -1671,8 +1675,9 @@
+ 
+   // Emit code for it.
+   BuilderType::InsertPointGuard Guard(Builder);
+-  PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
+-                                           L->getHeader()->begin()));
++  PHINode *V =
++    cast<PHINode>(expandCodeFor(H, nullptr,
++                                &(L->getHeader()->front())));
+ 
+   return V;
+ }
+@@ -1778,7 +1783,7 @@
+         if (OrigInc->getType() != IsomorphicInc->getType()) {
+           Instruction *IP = nullptr;
+           if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
+-            IP = PN->getParent()->getFirstInsertionPt();
++            IP = &*PN->getParent()->getFirstInsertionPt();
+           else
+             IP = OrigInc->getNextNode();
+ 
+@@ -1796,7 +1801,7 @@
+     ++NumElim;
+     Value *NewIV = OrigPhiRef;
+     if (OrigPhiRef->getType() != Phi->getType()) {
+-      IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
++      IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
+       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
+       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
+     }
+--- lib/Analysis/ScalarEvolutionNormalization.cpp	2014-08-29 14:53:01.000000000 -0700
++++ lib/Analysis/ScalarEvolutionNormalization.cpp	2015-11-27 15:32:52.251292445 -0800
+@@ -109,7 +109,7 @@
+     SmallVector<const SCEV *, 8> Operands;
+     const Loop *L = AR->getLoop();
+     // The addrec conceptually uses its operands at loop entry.
+-    Instruction *LUser = L->getHeader()->begin();
++    Instruction *LUser = &(L->getHeader()->front());
+     // Transform each operand.
+     for (SCEVNAryExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
+          I != E; ++I) {
+--- lib/Analysis/SparsePropagation.cpp	2014-04-21 19:48:03.000000000 -0700
++++ lib/Analysis/SparsePropagation.cpp	2015-11-27 16:56:54.595156233 -0800
+@@ -328,17 +328,17 @@
+ 
+ void SparseSolver::Print(Function &F, raw_ostream &OS) const {
+   OS << "\nFUNCTION: " << F.getName() << "\n";
+-  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
+-    if (!BBExecutable.count(BB))
++  for (auto &BB : F) {
++    if (!BBExecutable.count(&BB))
+       OS << "INFEASIBLE: ";
+     OS << "\t";
+-    if (BB->hasName())
+-      OS << BB->getName() << ":\n";
++    if (BB.hasName())
++      OS << BB.getName() << ":\n";
+     else
+       OS << "; anon bb\n";
+-    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
+-      LatticeFunc->PrintValue(getLatticeState(I), OS);
+-      OS << *I << "\n";
++    for (auto &I : BB) {
++      LatticeFunc->PrintValue(getLatticeState(&I), OS);
++      OS << I << "\n";
+     }
+     
+     OS << "\n";
+--- lib/Analysis/ValueTracking.cpp	2015-01-14 03:23:27.000000000 -0800
++++ lib/Analysis/ValueTracking.cpp	2015-11-27 17:02:21.643435710 -0800
+@@ -403,8 +403,8 @@
+       for (BasicBlock::const_iterator I =
+              std::next(BasicBlock::const_iterator(Q.CxtI)),
+                                       IE(Inv); I != IE; ++I)
+-        if (!isSafeToSpeculativelyExecute(I, DL) &&
+-            !isAssumeLikeIntrinsic(I))
++        if (!isSafeToSpeculativelyExecute(&*I, DL) &&
++            !isAssumeLikeIntrinsic(&*I))
+           return false;
+ 
+       return !isEphemeralValueOf(Inv, Q.CxtI);
+@@ -421,15 +421,15 @@
+     // of the block); the common case is that the assume will come first.
+     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
+          IE = Inv->getParent()->end(); I != IE; ++I)
+-      if (I == Q.CxtI)
++      if (&*I == Q.CxtI)
+         return true;
+ 
+     // The context must come first...
+     for (BasicBlock::const_iterator I =
+            std::next(BasicBlock::const_iterator(Q.CxtI)),
+                                     IE(Inv); I != IE; ++I)
+-      if (!isSafeToSpeculativelyExecute(I, DL) &&
+-          !isAssumeLikeIntrinsic(I))
++      if (!isSafeToSpeculativelyExecute(&*I, DL) &&
++          !isAssumeLikeIntrinsic(&*I))
+         return false;
+ 
+     return !isEphemeralValueOf(Inv, Q.CxtI);
+--- lib/AsmParser/LLParser.cpp	2015-01-13 13:10:44.000000000 -0800
++++ lib/AsmParser/LLParser.cpp	2015-12-06 12:01:01.192696877 -0800
+@@ -152,8 +152,10 @@
+       U->resolveCycles();
+ 
+   // Look for intrinsic functions and CallInst that need to be upgraded
+-  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
+-    UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
++  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
++    UpgradeCallsToIntrinsic(&*FI); // must be post-increment, as we remove
++    ++FI;
++  }
+ 
+   UpgradeDebugInfo(*M);
+ 
+@@ -2091,7 +2093,7 @@
+   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
+        AI != E; ++AI)
+     if (!AI->hasName())
+-      NumberedVals.push_back(AI);
++      NumberedVals.push_back(&*AI);
+ }
+ 
+ LLParser::PerFunctionState::~PerFunctionState() {
+--- lib/Bitcode/Reader/BitcodeReader.cpp	2015-02-17 13:27:11.000000000 -0800
++++ lib/Bitcode/Reader/BitcodeReader.cpp	2015-12-06 12:21:14.006297865 -0800
+@@ -1830,7 +1830,7 @@
+             return Error("Invalid ID");
+           ++BBI;
+         }
+-        BB = BBI;
++        BB = &*BBI;
+       } else {
+         // Otherwise insert a placeholder and remember it so it can be inserted
+         // when the function is parsed.
+@@ -1945,20 +1945,15 @@
+     return Error("Malformed global initializer set");
+ 
+   // Look for intrinsic functions which need to be upgraded at some point
+-  for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
+-       FI != FE; ++FI) {
++  for (Function &F : *TheModule) {
+     Function *NewFn;
+-    if (UpgradeIntrinsicFunction(FI, NewFn))
+-      UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
++    if (UpgradeIntrinsicFunction(&F, NewFn))
++      UpgradedIntrinsics.push_back(std::make_pair(&F, NewFn));
+   }
+ 
+   // Look for global variables which need to be renamed.
+-  for (Module::global_iterator
+-         GI = TheModule->global_begin(), GE = TheModule->global_end();
+-       GI != GE;) {
+-    GlobalVariable *GV = GI++;
+-    UpgradeGlobalVariable(GV);
+-  }
++  for (GlobalVariable &GV : TheModule->globals())
++    UpgradeGlobalVariable(&GV);
+ 
+   // Force deallocation of memory for these vectors to favor the client that
+   // want lazy deserialization.
+@@ -2528,8 +2523,8 @@
+   unsigned ModuleMDValueListSize = MDValueList.size();
+ 
+   // Add all the function arguments to the value table.
+-  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
+-    ValueList.push_back(I);
++  for (Argument &I : F->args())
++    ValueList.push_back(&I);
+ 
+   unsigned NextValueNo = ValueList.size();
+   BasicBlock *CurBB = nullptr;
+@@ -3555,9 +3550,8 @@
+ 
+   // Iterate over the module, deserializing any functions that are still on
+   // disk.
+-  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
+-       F != E; ++F) {
+-    if (std::error_code EC = materialize(F))
++  for (Function &F : *TheModule) {
++    if (std::error_code EC = materialize(&F))
+       return EC;
+   }
+   // At this point, if there are any function bodies, the current bit is
+--- lib/Bitcode/Writer/BitcodeWriter.cpp	2015-01-13 13:10:44.000000000 -0800
++++ lib/Bitcode/Writer/BitcodeWriter.cpp	2015-12-06 12:22:42.877667625 -0800
+@@ -924,7 +924,7 @@
+       // If no metadata, ignore instruction.
+       if (MDs.empty()) continue;
+ 
+-      Record.push_back(VE.getInstructionID(I));
++      Record.push_back(VE.getInstructionID(&*I));
+ 
+       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
+         Record.push_back(MDs[i].first);
+--- lib/Bitcode/Writer/ValueEnumerator.cpp	2015-01-13 13:10:44.000000000 -0800
++++ lib/Bitcode/Writer/ValueEnumerator.cpp	2015-12-06 12:26:51.090576745 -0800
+@@ -290,18 +290,18 @@
+   // Enumerate the global variables.
+   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
+        I != E; ++I)
+-    EnumerateValue(I);
++    EnumerateValue(&*I);
+ 
+   // Enumerate the functions.
+   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
+-    EnumerateValue(I);
++    EnumerateValue(&*I);
+     EnumerateAttributes(cast<Function>(I)->getAttributes());
+   }
+ 
+   // Enumerate the aliases.
+   for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
+        I != E; ++I)
+-    EnumerateValue(I);
++    EnumerateValue(&*I);
+ 
+   // Remember what is the cutoff between globalvalue's and other constants.
+   unsigned FirstConstant = Values.size();
+@@ -509,7 +509,7 @@
+   for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
+                                              E = M.named_metadata_end();
+        I != E; ++I)
+-    EnumerateNamedMDNode(I);
++    EnumerateNamedMDNode(&*I);
+ }
+ 
+ void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
+@@ -726,7 +726,7 @@
+   // Adding function arguments to the value table.
+   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
+        I != E; ++I)
+-    EnumerateValue(I);
++    EnumerateValue(&*I);
+ 
+   FirstFuncConstantID = Values.size();
+ 
+@@ -739,8 +739,8 @@
+             isa<InlineAsm>(*OI))
+           EnumerateValue(*OI);
+       }
+-    BasicBlocks.push_back(BB);
+-    ValueMap[BB] = BasicBlocks.size();
++    BasicBlocks.push_back(&*BB);
++    ValueMap[&*BB] = BasicBlocks.size();
+   }
+ 
+   // Optimize the constant layout.
+@@ -765,7 +765,7 @@
+       }
+ 
+       if (!I->getType()->isVoidTy())
+-        EnumerateValue(I);
++        EnumerateValue(&*I);
+     }
+   }
+ 
+@@ -793,7 +793,7 @@
+                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
+   unsigned Counter = 0;
+   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
+-    IDMap[BB] = ++Counter;
++    IDMap[&*BB] = ++Counter;
+ }
+ 
+ /// getGlobalBasicBlockID - This returns the function-specific ID for the
+--- lib/CodeGen/Analysis.cpp	2015-06-12 08:57:35.000000000 -0700
++++ lib/CodeGen/Analysis.cpp	2015-12-06 12:38:15.443685028 -0800
+@@ -514,7 +514,7 @@
+       if (isa<DbgInfoIntrinsic>(BBI))
+         continue;
+       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
+-          !isSafeToSpeculativelyExecute(BBI))
++          !isSafeToSpeculativelyExecute(&*BBI))
+         return false;
+     }
+ 
+--- lib/CodeGen/AsmPrinter/AsmPrinter.cpp	2015-01-12 16:48:10.000000000 -0800
++++ lib/CodeGen/AsmPrinter/AsmPrinter.cpp	2016-01-21 10:23:14.978051692 -0800
+@@ -857,6 +857,7 @@
+     MCSymbol *Sym = GetBlockAddressSymbol(&BB);
+     if (Sym->isDefined())
+       continue;
++
+     OutStreamer.AddComment("Address of block that was removed by CodeGen");
+     OutStreamer.EmitLabel(Sym);
+   }
+@@ -864,8 +865,8 @@
+   // Emit target-specific gunk after the function body.
+   EmitFunctionBodyEnd();
+ 
+-  // If the target wants a .size directive for the size of the function, emit
+-  // it.
++  // If the target wants a .size directive for the size of the function,
++  // emit it.
+   if (MAI->hasDotTypeDotSizeDirective()) {
+     // Create a symbol for the end of function, so we can get the size as
+     // difference between the function label and the temp label.
+@@ -885,6 +886,7 @@
+     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
+     HI.Handler->endFunction(MF);
+   }
++
+   MMI->EndFunction();
+ 
+   // Print out jump tables referenced by the function.
+--- lib/CodeGen/AtomicExpandPass.cpp	2014-09-25 10:27:43.000000000 -0700
++++ lib/CodeGen/AtomicExpandPass.cpp	2015-12-06 12:41:26.021558967 -0800
+@@ -298,7 +298,8 @@
+   // atomicrmw.end:
+   //     fence?
+   //     [...]
+-  BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
++  BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(),
++                                           "atomicrmw.end");
+   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
+ 
+   // This grabs the DebugLoc from AI.
+@@ -355,7 +356,7 @@
+   //     br i1 %success, label %atomicrmw.end, label %loop
+   // atomicrmw.end:
+   //     [...]
+-  BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
++  BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(), "atomicrmw.end");
+   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
+ 
+   // This grabs the DebugLoc from AI.
+@@ -436,7 +437,7 @@
+   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
+   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
+   //     [...]
+-  BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
++  BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
+   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
+   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
+   auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
+--- lib/CodeGen/BasicTargetTransformInfo.cpp	2015-01-07 16:51:32.000000000 -0800
++++ lib/CodeGen/BasicTargetTransformInfo.cpp	2015-12-06 12:42:25.950965490 -0800
+@@ -240,7 +240,7 @@
+ 
+     for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
+       if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
+-        ImmutableCallSite CS(J);
++        ImmutableCallSite CS(&*J);
+         if (const Function *F = CS.getCalledFunction()) {
+           if (!TopTTI->isLoweredToCall(F))
+             continue;
+--- lib/CodeGen/BranchFolding.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/CodeGen/BranchFolding.cpp	2015-12-06 14:41:40.491854005 -0800
+@@ -130,7 +130,7 @@
+   TriedMerging.erase(MBB);
+ 
+   // Remove the block.
+-  MF->erase(MBB);
++  MF->erase(MBB->getIterator());
+ }
+ 
+ /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
+@@ -207,12 +207,12 @@
+ 
+   // Fix CFG.  The later algorithms expect it to be right.
+   bool MadeChange = false;
+-  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
+-    MachineBasicBlock *MBB = I, *TBB = nullptr, *FBB = nullptr;
++  for (MachineBasicBlock &MBB : MF) {
++    MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
+     SmallVector<MachineOperand, 4> Cond;
+-    if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
+-      MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
+-    MadeChange |= OptimizeImpDefsBlock(MBB);
++    if (!TII->AnalyzeBranch(MBB, TBB, FBB, Cond, true))
++      MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
++    MadeChange |= OptimizeImpDefsBlock(&MBB);
+   }
+ 
+   bool MadeChangeThisIteration = true;
+@@ -426,7 +426,7 @@
+   MachineFunction &MF = *CurMBB.getParent();
+ 
+   // Create the fall-through block.
+-  MachineFunction::iterator MBBI = &CurMBB;
++  MachineFunction::iterator MBBI = CurMBB.getIterator();
+   MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
+   CurMBB.getParent()->insert(++MBBI, NewMBB);
+ 
+@@ -479,7 +479,7 @@
+   DebugLoc dl;  // FIXME: this is nowhere
+   if (I != MF->end() &&
+       !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
+-    MachineBasicBlock *NextBB = I;
++    MachineBasicBlock *NextBB = &*I;
+     if (TBB == NextBB && !Cond.empty() && !FBB) {
+       if (!TII->ReverseBranchCondition(Cond)) {
+         TII->RemoveBranch(*CurMBB);
+@@ -785,8 +785,8 @@
+     // block, which we can't jump to), we can treat all blocks with this same
+     // tail at once.  Use PredBB if that is one of the possibilities, as that
+     // will not introduce any extra branches.
+-    MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
+-                                 getParent()->begin();
++    MachineBasicBlock *EntryBB =
++      &MergePotentials.front().getBlock()->getParent()->front();
+     unsigned commonTailIndex = SameTails.size();
+     // If there are two blocks, check to see if one can be made to fall through
+     // into the other.
+@@ -860,12 +860,12 @@
+ 
+   // First find blocks with no successors.
+   MergePotentials.clear();
+-  for (MachineFunction::iterator I = MF.begin(), E = MF.end();
+-       I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
+-    if (TriedMerging.count(I))
+-      continue;
+-    if (I->succ_empty())
+-      MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
++  for (MachineBasicBlock &MBB : MF) {
++    if (MergePotentials.size() == TailMergeThreshold)
++      break;
++
++    if (!TriedMerging.count(&MBB) && MBB.succ_empty())
++      MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(&MBB), &MBB));
+   }
+ 
+   // If this is a large problem, avoid visiting the same basic blocks
+@@ -901,8 +901,8 @@
+        I != E; ++I) {
+     if (I->pred_size() < 2) continue;
+     SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
+-    MachineBasicBlock *IBB = I;
+-    MachineBasicBlock *PredBB = std::prev(I);
++    MachineBasicBlock *IBB = &*I;
++    MachineBasicBlock *PredBB = &*std::prev(I);
+     MergePotentials.clear();
+     for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
+            E2 = I->pred_end();
+@@ -933,18 +933,21 @@
+           if (TII->ReverseBranchCondition(NewCond))
+             continue;
+           // This is the QBB case described above
+-          if (!FBB)
+-            FBB = std::next(MachineFunction::iterator(PBB));
++          if (!FBB) {
++            auto Next = ++PBB->getIterator();
++            if (Next != MF.end())
++              FBB = &*Next;
++          }
+         }
+ 
+         // Failing case: the only way IBB can be reached from PBB is via
+         // exception handling.  Happens for landing pads.  Would be nice to have
+         // a bit in the edge so we didn't have to do all this.
+         if (IBB->isLandingPad()) {
+-          MachineFunction::iterator IP = PBB;  IP++;
++          MachineFunction::iterator IP = ++PBB->getIterator();
+           MachineBasicBlock *PredNextBB = nullptr;
+           if (IP != MF.end())
+-            PredNextBB = IP;
++            PredNextBB = &*IP;
+           if (!TBB) {
+             if (IBB != PredNextBB)      // fallthrough
+               continue;
+@@ -985,7 +988,7 @@
+ 
+     // Reinsert an unconditional branch if needed. The 1 below can occur as a
+     // result of removing blocks in TryTailMergeBlocks.
+-    PredBB = std::prev(I);     // this may have been changed in TryTailMergeBlocks
++    PredBB = &*std::prev(I);     // this may have been changed in TryTailMergeBlocks
+     if (MergePotentials.size() == 1 &&
+         MergePotentials.begin()->getBlock() != PredBB)
+       FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
+@@ -1044,7 +1047,7 @@
+ 
+   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
+        I != E; ) {
+-    MachineBasicBlock *MBB = I++;
++    MachineBasicBlock *MBB = &*I++;
+     MadeChange |= OptimizeBlock(MBB);
+ 
+     // If it is dead, remove it.
+@@ -1132,7 +1135,7 @@
+   MachineFunction &MF = *MBB->getParent();
+ ReoptimizeBlock:
+ 
+-  MachineFunction::iterator FallThrough = MBB;
++  MachineFunction::iterator FallThrough = MBB->getIterator();
+   ++FallThrough;
+ 
+   // If this block is empty, make everyone use its fall-through, not the block
+@@ -1150,12 +1153,12 @@
+       // instead.
+       while (!MBB->pred_empty()) {
+         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
+-        Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
++        Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
+       }
+       // If MBB was the target of a jump table, update jump tables to go to the
+       // fallthrough instead.
+       if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
+-        MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
++        MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
+       MadeChange = true;
+     }
+     return MadeChange;
+@@ -1293,7 +1296,7 @@
+           TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
+ 
+           // Move this block to the end of the function.
+-          MBB->moveAfter(--MF.end());
++          MBB->moveAfter(&MF.back());
+           MadeChange = true;
+           ++NumBranchOpts;
+           return MadeChange;
+@@ -1440,11 +1443,8 @@
+     if (!MBB->isLandingPad()) {
+       // Check all the predecessors of this block.  If one of them has no fall
+       // throughs, move this block right after it.
+-      for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
+-           E = MBB->pred_end(); PI != E; ++PI) {
++      for (MachineBasicBlock *PredBB : MBB->predecessors()) {
+         // Analyze the branch at the end of the pred.
+-        MachineBasicBlock *PredBB = *PI;
+-        MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
+         MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
+         SmallVector<MachineOperand, 4> PredCond;
+         if (PredBB != MBB && !PredBB->canFallThrough() &&
+@@ -1462,8 +1462,7 @@
+           // B elsewhere
+           // next:
+           if (CurFallsThru) {
+-            MachineBasicBlock *NextBB =
+-                std::next(MachineFunction::iterator(MBB));
++            MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
+             CurCond.clear();
+             TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
+           }
+@@ -1476,11 +1475,13 @@
+ 
+     if (!CurFallsThru) {
+       // Check all successors to see if we can move this block before it.
++      for (MachineBasicBlock *SuccBB : MBB->successors()) {
++#if 0
+       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
+            E = MBB->succ_end(); SI != E; ++SI) {
++#endif
+         // Analyze the branch at the end of the block before the succ.
+-        MachineBasicBlock *SuccBB = *SI;
+-        MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
++        MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
+ 
+         // If this block doesn't already fall-through to that successor, and if
+         // the succ doesn't already have a block that can fall through into it,
+@@ -1502,8 +1503,8 @@
+       SmallVector<MachineOperand, 4> PrevCond;
+       if (FallThrough != MF.end() &&
+           !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
+-          PrevBB.isSuccessor(FallThrough)) {
+-        MBB->moveAfter(--MF.end());
++          PrevBB.isSuccessor(&*FallThrough)) {
++        MBB->moveAfter(&MF.back());
+         MadeChange = true;
+         return MadeChange;
+       }
+@@ -1522,7 +1523,7 @@
+ bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
+   bool MadeChange = false;
+   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
+-    MachineBasicBlock *MBB = I++;
++    MachineBasicBlock *MBB = &*I++;
+     MadeChange |= HoistCommonCodeInSuccs(MBB);
+   }
+ 
+--- lib/CodeGen/CodeGenPrepare.cpp	2015-01-12 09:22:43.000000000 -0800
++++ lib/CodeGen/CodeGenPrepare.cpp	2015-12-06 14:55:51.313203408 -0800
+@@ -245,7 +245,8 @@
+   while (MadeChange) {
+     MadeChange = false;
+     for (Function::iterator I = F.begin(); I != F.end(); ) {
+-      BasicBlock *BB = I++;
++      BasicBlock *BB = &*I;
++      ++I;
+       bool ModifiedDTOnIteration = false;
+       MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
+       
+@@ -311,7 +312,8 @@
+   bool Changed = false;
+   // Scan all of the blocks in the function, except for the entry block.
+   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
+-    BasicBlock *BB = I++;
++    BasicBlock *BB = &*I;
++    ++I;
+     // If the destination block has a single pred, then this is a trivial
+     // edge, just collapse it.
+     BasicBlock *SinglePred = BB->getSinglePredecessor();
+@@ -332,7 +334,7 @@
+         BB->moveBefore(&BB->getParent()->getEntryBlock());
+ 
+       // We have erased a block. Update the iterator.
+-      I = BB;
++      I = BB->getIterator();
+     }
+   }
+   return Changed;
+@@ -347,7 +349,8 @@
+   bool MadeChange = false;
+   // Note that this intentionally skips the entry block.
+   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
+-    BasicBlock *BB = I++;
++    BasicBlock *BB = &*I;
++    ++I;
+ 
+     // If this block doesn't end with an uncond branch, ignore it.
+     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
+@@ -356,7 +359,7 @@
+ 
+     // If the instruction before the branch (skipping debug info) isn't a phi
+     // node, then other stuff is happening here.
+-    BasicBlock::iterator BBI = BI;
++    BasicBlock::iterator BBI(BI);
+     if (BBI != BB->begin()) {
+       --BBI;
+       while (isa<DbgInfoIntrinsic>(BBI)) {
+@@ -553,8 +556,8 @@
+     if (!InsertedCast) {
+       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
+       InsertedCast =
+-        CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
+-                         InsertPt);
++        CastInst::Create(CI->getOpcode(), CI->getOperand(0),
++                         CI->getType(), "", &*InsertPt);
+       MadeChange = true;
+     }
+ 
+@@ -648,7 +651,7 @@
+       InsertedCmp =
+         CmpInst::Create(CI->getOpcode(),
+                         CI->getPredicate(),  CI->getOperand(0),
+-                        CI->getOperand(1), "", InsertPt);
++                        CI->getOperand(1), "", &*InsertPt);
+       MadeChange = true;
+     }
+ 
+@@ -734,17 +737,17 @@
+       // Sink the shift
+       if (ShiftI->getOpcode() == Instruction::AShr)
+         InsertedShift =
+-            BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
++          BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
+       else
+         InsertedShift =
+-            BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
++          BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
+ 
+       // Sink the trunc
+       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
+       TruncInsertPt++;
+ 
+       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
+-                                       TruncI->getType(), "", TruncInsertPt);
++                                       TruncI->getType(), "", &*TruncInsertPt);
+ 
+       MadeChange = true;
+ 
+@@ -829,10 +832,10 @@
+ 
+       if (ShiftI->getOpcode() == Instruction::AShr)
+         InsertedShift =
+-            BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
++          BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
+       else
+         InsertedShift =
+-            BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
++          BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
+ 
+       MadeChange = true;
+     }
+@@ -941,7 +944,7 @@
+     //  %Elt = load i32* %EltAddr
+     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
+     //
+-    CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
++    CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
+     Builder.SetInsertPoint(InsertPt);
+     
+     Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
+@@ -949,7 +952,8 @@
+     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
+ 
+     // Create "else" block, fill it in the next iteration
+-    BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
++    BasicBlock *NewIfBlock =
++      CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
+     Builder.SetInsertPoint(InsertPt);
+     Instruction *OldBr = IfBlock->getTerminator();
+     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
+@@ -1024,7 +1028,8 @@
+     //  %to_store = icmp eq i1 %mask_1, true
+     //  br i1 %to_load, label %cond.store, label %else
+     //
+-    Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
++    Value *Predicate =
++      Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
+     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
+                                     ConstantInt::get(Predicate->getType(), 1));
+ 
+@@ -1034,15 +1039,17 @@
+     //  %EltAddr = getelementptr i32* %1, i32 0
+     //  %store i32 %OneElt, i32* %EltAddr
+     //
+-    BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
++    BasicBlock *CondBlock =
++      IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
+     Builder.SetInsertPoint(InsertPt);
+-    
++
+     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
+     Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
+     Builder.CreateStore(OneElt, Gep);
+ 
+     // Create "else" block, fill it in the next iteration
+-    BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
++    BasicBlock *NewIfBlock =
++      CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
+     Builder.SetInsertPoint(InsertPt);
+     Instruction *OldBr = IfBlock->getTerminator();
+     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
+@@ -1085,7 +1092,7 @@
+       // Substituting this can cause recursive simplifications, which can
+       // invalidate our iterator.  Use a WeakVH to hold onto it in case this
+       // happens.
+-      WeakVH IterHandle(CurInstIterator);
++      WeakVH IterHandle(&*CurInstIterator);
+ 
+       replaceAndRecursivelySimplify(CI, RetVal,
+                                     TLI ? TLI->getDataLayout() : nullptr,
+@@ -1093,7 +1100,7 @@
+ 
+       // If the iterator instruction was recursively deleted, start over at the
+       // start of the block.
+-      if (IterHandle != CurInstIterator) {
++      if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
+         CurInstIterator = BB->begin();
+         SunkAddrs.clear();
+       }
+@@ -1410,10 +1417,10 @@
+   public:
+     /// \brief Record the position of \p Inst.
+     InsertionHandler(Instruction *Inst) {
+-      BasicBlock::iterator It = Inst;
++      BasicBlock::iterator It = Inst->getIterator();
+       HasPrevInstruction = (It != (Inst->getParent()->begin()));
+       if (HasPrevInstruction)
+-        Point.PrevInst = --It;
++        Point.PrevInst = &*--It;
+       else
+         Point.BB = Inst->getParent();
+     }
+@@ -1425,7 +1432,7 @@
+           Inst->removeFromParent();
+         Inst->insertAfter(Point.PrevInst);
+       } else {
+-        Instruction *Position = Point.BB->getFirstInsertionPt();
++        Instruction *Position = &*Point.BB->getFirstInsertionPt();
+         if (Inst->getParent())
+           Inst->moveBefore(Position);
+         else
+@@ -3191,12 +3198,12 @@
+   if (Repl->use_empty()) {
+     // This can cause recursive deletion, which can invalidate our iterator.
+     // Use a WeakVH to hold onto it in case this happens.
+-    WeakVH IterHandle(CurInstIterator);
++    WeakVH IterHandle(&*CurInstIterator);
+     BasicBlock *BB = CurInstIterator->getParent();
+ 
+     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
+ 
+-    if (IterHandle != CurInstIterator) {
++    if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
+       // If the iterator instruction was recursively deleted, start over at the
+       // start of the block.
+       CurInstIterator = BB->begin();
+@@ -3495,7 +3502,7 @@
+ 
+     if (!InsertedTrunc) {
+       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
+-      InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
++      InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
+       InsertedTruncsSet.insert(InsertedTrunc);
+     }
+ 
+@@ -3583,7 +3590,8 @@
+   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
+ 
+   // The select itself is replaced with a PHI Node.
+-  PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
++  PHINode *PN = PHINode::Create(SI->getType(), 2, "",
++                                &NextBlock->front());
+   PN->takeName(SI);
+   PN->addIncoming(SI->getTrueValue(), StartBlock);
+   PN->addIncoming(SI->getFalseValue(), SmallBlock);
+@@ -3646,7 +3654,8 @@
+       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
+       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
+                                               SVI->getOperand(1),
+-                                              SVI->getOperand(2), "", InsertPt);
++                                              SVI->getOperand(2), "",
++                                              &*InsertPt);
+     }
+ 
+     UI->replaceUsesOfWith(SVI, InsertedShuffle);
+@@ -3969,148 +3978,6 @@
+   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
+ }
+ 
+-// See if we can speculate calls to intrinsic cttz/ctlz.
+-//
+-// Example:
+-// entry:
+-//   ...
+-//   %cmp = icmp eq i64 %val, 0
+-//   br i1 %cmp, label %end.bb, label %then.bb
+-//
+-// then.bb:
+-//   %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 true)
+-//   br label %EndBB
+-//
+-// end.bb:
+-//   %cond = phi i64 [ %c, %then.bb ], [ 64, %entry ]
+-//
+-// ==>
+-//
+-// entry:
+-//   ...
+-//   %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 false)
+-//
+-static bool OptimizeBranchInst(BranchInst *BrInst, const TargetLowering &TLI) {
+-  assert(BrInst->isConditional() && "Expected a conditional branch!");
+-  BasicBlock *ThenBB = BrInst->getSuccessor(1);
+-  BasicBlock *EndBB = BrInst->getSuccessor(0);
+-
+-  // See if ThenBB contains only one instruction (excluding the
+-  // terminator and DbgInfoIntrinsic calls).
+-  IntrinsicInst *II = nullptr;
+-  CastInst *CI = nullptr;
+-  for (BasicBlock::iterator I = ThenBB->begin(),
+-                            E = std::prev(ThenBB->end()); I != E; ++I) {
+-    // Skip debug info.
+-    if (isa<DbgInfoIntrinsic>(I))
+-      continue;
+-
+-    // Check if this is a zero extension or a truncate of a previously
+-    // matched call to intrinsic cttz/ctlz.
+-    if (II) {
+-      // Early exit if we already found a "free" zero extend/truncate.
+-      if (CI)
+-        return false;
+-
+-      Type *SrcTy = II->getType();
+-      Type *DestTy = I->getType();
+-      Value *V;
+- 
+-      if (match(cast<Instruction>(I), m_ZExt(m_Value(V))) && V == II) {
+-        // Speculate this zero extend only if it is "free" for the target.
+-        if (TLI.isZExtFree(SrcTy, DestTy)) {
+-          CI = cast<CastInst>(I);
+-          continue;
+-        }
+-      } else if (match(cast<Instruction>(I), m_Trunc(m_Value(V))) && V == II) {
+-        // Speculate this truncate only if it is "free" for the target.
+-        if (TLI.isTruncateFree(SrcTy, DestTy)) {
+-          CI = cast<CastInst>(I);
+-          continue;
+-        }
+-      } else {
+-        // Avoid speculating more than one instruction.
+-        return false;
+-      }
+-    }
+-
+-    // See if this is a call to intrinsic cttz/ctlz.
+-    if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::cttz>())) {
+-      // Avoid speculating expensive intrinsic calls.
+-      if (!TLI.isCheapToSpeculateCttz())
+-        return false;
+-    }
+-    else if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::ctlz>())) {
+-      // Avoid speculating expensive intrinsic calls.
+-      if (!TLI.isCheapToSpeculateCtlz())
+-        return false;
+-    } else
+-      return false;
+-    
+-    II = cast<IntrinsicInst>(I);
+-  }
+-
+-  // Look for PHI nodes with 'II' as the incoming value from 'ThenBB'.
+-  BasicBlock *EntryBB = BrInst->getParent();
+-  for (BasicBlock::iterator I = EndBB->begin();
+-       PHINode *PN = dyn_cast<PHINode>(I); ++I) {
+-    Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
+-    Value *OrigV = PN->getIncomingValueForBlock(EntryBB);
+-
+-    if (!OrigV)
+-      return false;
+-
+-    if (ThenV != II && (!CI || ThenV != CI))
+-      return false;
+-    
+-    if (ConstantInt *CInt = dyn_cast<ConstantInt>(OrigV)) {
+-      unsigned BitWidth = II->getType()->getIntegerBitWidth();
+-
+-      // Don't try to simplify this phi node if 'ThenV' is a cttz/ctlz
+-      // intrinsic call, but 'OrigV' is not equal to the 'size-of' in bits
+-      // of the value in input to the cttz/ctlz.
+-      if (CInt->getValue() != BitWidth)
+-        return false;
+-
+-      // Hoist the call to cttz/ctlz from ThenBB into EntryBB.
+-      EntryBB->getInstList().splice(BrInst, ThenBB->getInstList(),
+-                                    ThenBB->begin(), std::prev(ThenBB->end()));
+- 
+-      // Update PN setting ThenV as the incoming value from both 'EntryBB'
+-      // and 'ThenBB'. Eventually, method 'OptimizeInst' will fold this
+-      // phi node if all the incoming values are the same.
+-      PN->setIncomingValue(PN->getBasicBlockIndex(EntryBB), ThenV);
+-      PN->setIncomingValue(PN->getBasicBlockIndex(ThenBB), ThenV);
+-
+-      // Clear the 'undef on zero' flag of the cttz/ctlz intrinsic call.
+-      if (cast<ConstantInt>(II->getArgOperand(1))->isOne()) {
+-        Type *Ty = II->getArgOperand(0)->getType();
+-        Value *Args[] = { II->getArgOperand(0),
+-                          ConstantInt::getFalse(II->getContext()) };
+-        Module *M = EntryBB->getParent()->getParent();
+-        Value *IF = Intrinsic::getDeclaration(M, II->getIntrinsicID(), Ty);
+-        IRBuilder<> Builder(II);
+-        Instruction *NewI = Builder.CreateCall(IF, Args);
+-
+-        // Replace the old call to cttz/ctlz.
+-        II->replaceAllUsesWith(NewI);
+-        II->eraseFromParent();
+-      }
+- 
+-      // Update BrInst condition so that the branch to EndBB is always taken.
+-      // Later on, method 'ConstantFoldTerminator' will simplify this branch
+-      // replacing it with a direct branch to 'EndBB'.
+-      // As a side effect, CodeGenPrepare will attempt to simplify the control
+-      // flow graph by deleting basic block 'ThenBB' and merging 'EntryBB' into
+-      // 'EndBB' (calling method 'EliminateFallThrough').
+-      BrInst->setCondition(ConstantInt::getTrue(BrInst->getContext()));
+-      return true;
+-    }
+-  }
+-
+-  return false;
+-}
+-
+ /// Some targets can do store(extractelement) with one instruction.
+ /// Try to push the extractelement towards the stores when the target
+ /// has this feature and this is profitable.
+@@ -4263,34 +4130,6 @@
+   if (isa<ExtractElementInst>(I))
+     return OptimizeExtractElementInst(I);
+ 
+-  if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
+-    if (TLI && BI->isConditional() && BI->getCondition()->hasOneUse()) {
+-      // Check if the branch condition compares a value agaist zero.
+-      if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
+-        if (ICI->getPredicate() == ICmpInst::ICMP_EQ &&
+-            match(ICI->getOperand(1), m_Zero())) {
+-          BasicBlock *ThenBB = BI->getSuccessor(1);
+-          BasicBlock *EndBB = BI->getSuccessor(0);
+-
+-          // Check if ThenBB is only reachable from this basic block; also,
+-          // check if EndBB has more than one predecessor.
+-          if (ThenBB->getSinglePredecessor() &&
+-              !EndBB->getSinglePredecessor()) {
+-            TerminatorInst *TI = ThenBB->getTerminator();
+-
+-            if (TI->getNumSuccessors() == 1 && TI->getSuccessor(0) == EndBB &&
+-                // Try to speculate calls to intrinsic cttz/ctlz from 'ThenBB'.
+-                OptimizeBranchInst(BI, *TLI)) {
+-              ModifiedDT = true;
+-              return true;
+-            }
+-          }
+-        }
+-      }
+-    }
+-    return false;
+-  }
+-
+   return false;
+ }
+ 
+@@ -4303,7 +4142,7 @@
+ 
+   CurInstIterator = BB.begin();
+   while (CurInstIterator != BB.end()) {
+-    MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
++    MadeChange |= OptimizeInst(&*CurInstIterator++, ModifiedDT);
+     if (ModifiedDT)
+       return true;
+   }
+@@ -4320,7 +4159,7 @@
+   for (BasicBlock &BB : F) {
+     Instruction *PrevNonDbgInst = nullptr;
+     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
+-      Instruction *Insn = BI++;
++      Instruction *Insn = &*BI++;
+       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
+       // Leave dbg.values that refer to an alloca alone. These
+       // instrinsics describe the address of a variable (= the alloca)
+@@ -4337,7 +4176,7 @@
+         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
+         DVI->removeFromParent();
+         if (isa<PHINode>(VI))
+-          DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
++          DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
+         else
+           DVI->insertAfter(VI);
+         MadeChange = true;
+@@ -4361,7 +4200,7 @@
+     return false;
+   bool MadeChange = false;
+   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
+-    BasicBlock *BB = I++;
++    BasicBlock *BB = &*I++;
+ 
+     // Does this BB end with the following?
+     //   %andVal = and %val, #single-bit-set
+--- lib/CodeGen/DFAPacketizer.cpp	2014-10-13 18:03:16.000000000 -0700
++++ lib/CodeGen/DFAPacketizer.cpp	2015-12-06 18:00:08.967241318 -0800
+@@ -147,7 +147,7 @@
+                                          MachineInstr *MI) {
+   if (CurrentPacketMIs.size() > 1) {
+     MachineInstr *MIFirst = CurrentPacketMIs.front();
+-    finalizeBundle(*MBB, MIFirst, MI);
++    finalizeBundle(*MBB, MIFirst->getIterator(), MI->getIterator());
+   }
+   CurrentPacketMIs.clear();
+   ResourceTracker->clearResources();
+--- lib/CodeGen/ExecutionDepsFix.cpp	2014-12-17 11:13:47.000000000 -0800
++++ lib/CodeGen/ExecutionDepsFix.cpp	2015-12-06 14:03:54.050682968 -0800
+@@ -753,7 +753,7 @@
+         AliasMap[*AI].push_back(i);
+   }
+ 
+-  MachineBasicBlock *Entry = MF->begin();
++  MachineBasicBlock *Entry = &*MF->begin();
+   ReversePostOrderTraversal<MachineBasicBlock*> RPOT(Entry);
+   SmallVector<MachineBasicBlock*, 16> Loops;
+   for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
+--- lib/CodeGen/ExpandISelPseudos.cpp	2014-10-14 00:22:08.000000000 -0700
++++ lib/CodeGen/ExpandISelPseudos.cpp	2015-12-06 14:17:23.351013837 -0800
+@@ -50,7 +50,7 @@
+ 
+   // Iterate through each instruction in the function, looking for pseudos.
+   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
+-    MachineBasicBlock *MBB = I;
++    MachineBasicBlock *MBB = &*I;
+     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
+          MBBI != MBBE; ) {
+       MachineInstr *MI = MBBI++;
+@@ -63,7 +63,7 @@
+         // The expansion may involve new basic blocks.
+         if (NewMBB != MBB) {
+           MBB = NewMBB;
+-          I = NewMBB;
++          I = NewMBB->getIterator();
+           MBBI = NewMBB->begin();
+           MBBE = NewMBB->end();
+         }
+--- lib/CodeGen/ForwardControlFlowIntegrity.cpp	2015-01-14 03:23:27.000000000 -0800
++++ lib/CodeGen/ForwardControlFlowIntegrity.cpp	2015-12-06 18:01:31.650156258 -0800
+@@ -329,7 +329,7 @@
+       Check = TempBuilder.CreateICmpEQ(NewFunPtr, FunPtr);
+     BasicBlock *InvalidPtrBlock =
+         BasicBlock::Create(M.getContext(), "invalid.ptr", CurF, 0);
+-    BasicBlock *ContinuationBB = CurBB->splitBasicBlock(I);
++    BasicBlock *ContinuationBB = CurBB->splitBasicBlock(I->getIterator());
+ 
+     // Remove the unconditional branch that connects the two blocks.
+     TerminatorInst *TermInst = CurBB->getTerminator();
+--- lib/CodeGen/GCStrategy.cpp	2015-01-07 11:07:50.000000000 -0800
++++ lib/CodeGen/GCStrategy.cpp	2015-12-06 18:08:32.675654207 -0800
+@@ -156,12 +156,13 @@
+                                                           unsigned Count) {
+   // Scroll past alloca instructions.
+   BasicBlock::iterator IP = F.getEntryBlock().begin();
+-  while (isa<AllocaInst>(IP)) ++IP;
++  while (isa<AllocaInst>(IP))
++    ++IP;
+ 
+   // Search for initializers in the initial BB.
+   SmallPtrSet<AllocaInst*,16> InitedRoots;
+-  for (; !CouldBecomeSafePoint(IP); ++IP)
+-    if (StoreInst *SI = dyn_cast<StoreInst>(IP))
++  for (; !CouldBecomeSafePoint(&*IP); ++IP)
++    if (StoreInst *SI = dyn_cast<StoreInst>(&*IP))
+       if (AllocaInst *AI =
+           dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
+         InitedRoots.insert(AI);
+--- lib/CodeGen/GlobalMerge.cpp	2015-01-14 03:23:27.000000000 -0800
++++ lib/CodeGen/GlobalMerge.cpp	2015-12-06 18:44:54.895620825 -0800
+@@ -289,61 +289,61 @@
+   setMustKeepGlobalVariables(M);
+ 
+   // Grab all non-const globals.
+-  for (Module::global_iterator I = M.global_begin(),
+-         E = M.global_end(); I != E; ++I) {
++  for (auto &I : M.globals()) {
+     // Merge is safe for "normal" internal or external globals only
+-    if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
++    if (I.isDeclaration() || I.isThreadLocal() || I.hasSection())
+       continue;
+ 
+-    if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) &&
+-        !I->hasInternalLinkage())
++    if (!(EnableGlobalMergeOnExternal && I.hasExternalLinkage()) &&
++        !I.hasInternalLinkage())
+       continue;
+ 
+-    PointerType *PT = dyn_cast<PointerType>(I->getType());
++    PointerType *PT = dyn_cast<PointerType>(I.getType());
+     assert(PT && "Global variable is not a pointer!");
+ 
+     unsigned AddressSpace = PT->getAddressSpace();
+ 
+     // Ignore fancy-aligned globals for now.
+-    unsigned Alignment = DL->getPreferredAlignment(I);
+-    Type *Ty = I->getType()->getElementType();
++    unsigned Alignment = DL->getPreferredAlignment(&I);
++    Type *Ty = I.getType()->getElementType();
+     if (Alignment > DL->getABITypeAlignment(Ty))
+       continue;
+ 
+     // Ignore all 'special' globals.
+-    if (I->getName().startswith("llvm.") ||
+-        I->getName().startswith(".llvm."))
++    if (I.getName().startswith("llvm.") ||
++        I.getName().startswith(".llvm."))
+       continue;
+ 
+     // Ignore all "required" globals:
+-    if (isMustKeepGlobalVariable(I))
++    if (isMustKeepGlobalVariable(&I))
+       continue;
+ 
+     if (DL->getTypeAllocSize(Ty) < MaxOffset) {
+-      if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
+-        BSSGlobals[AddressSpace].push_back(I);
+-      else if (I->isConstant())
+-        ConstGlobals[AddressSpace].push_back(I);
++      if (TargetLoweringObjectFile::getKindForGlobal(&I, *TM).isBSSLocal())
++        BSSGlobals[AddressSpace].push_back(&I);
++      else if (I.isConstant())
++        ConstGlobals[AddressSpace].push_back(&I);
+       else
+-        Globals[AddressSpace].push_back(I);
++        Globals[AddressSpace].push_back(&I);
+     }
+   }
+ 
+-  for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
+-       I = Globals.begin(), E = Globals.end(); I != E; ++I)
+-    if (I->second.size() > 1)
+-      Changed |= doMerge(I->second, M, false, I->first);
+-
+-  for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
+-       I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
+-    if (I->second.size() > 1)
+-      Changed |= doMerge(I->second, M, false, I->first);
+-
+-  if (EnableGlobalMergeOnConst)
+-    for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
+-         I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
+-      if (I->second.size() > 1)
+-        Changed |= doMerge(I->second, M, true, I->first);
++  for (auto &G : Globals) {
++    if (G.second.size() > 1)
++      Changed |= doMerge(G.second, M, false, G.first);
++  }
++
++  for (auto &G : BSSGlobals) {
++    if (G.second.size() > 1)
++      Changed |= doMerge(G.second, M, false, G.first);
++  }
++
++  if (EnableGlobalMergeOnConst) {
++    for (auto &G : ConstGlobals) {
++      if (G.second.size() > 1)
++        Changed |= doMerge(G.second, M, true, G.first);
++    }
++  }
+ 
+   return Changed;
+ }
+--- lib/CodeGen/IfConversion.cpp	2014-10-14 00:22:08.000000000 -0700
++++ lib/CodeGen/IfConversion.cpp	2015-12-06 19:35:07.755981678 -0800
+@@ -460,11 +460,15 @@
+ /// getNextBlock - Returns the next block in the function blocks ordering. If
+ /// it is the end, returns NULL.
+ static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
+-  MachineFunction::iterator I = BB;
++  MachineFunction::iterator I = BB->getIterator();
+   MachineFunction::iterator E = BB->getParent()->end();
++  if (I == E)
++    return nullptr;
++
+   if (++I == E)
+     return nullptr;
+-  return I;
++
++  return &*I;
+ }
+ 
+ /// ValidSimple - Returns true if the 'true' block (along with its
+@@ -528,12 +532,13 @@
+ 
+   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
+   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
+-    MachineFunction::iterator I = TrueBBI.BB;
++    MachineFunction::iterator I = TrueBBI.BB->getIterator();
+     if (++I == TrueBBI.BB->getParent()->end())
+       return false;
+-    TExit = I;
++
++    TExit = &*I;
+   }
+-  return TExit && TExit == FalseBBI.BB;
++  return TExit && (TExit == FalseBBI.BB);
+ }
+ 
+ /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
+@@ -910,10 +915,8 @@
+ /// candidates.
+ void IfConverter::AnalyzeBlocks(MachineFunction &MF,
+                                 std::vector<IfcvtToken*> &Tokens) {
+-  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
+-    MachineBasicBlock *BB = I;
+-    AnalyzeBlock(BB, Tokens);
+-  }
++  for (auto &BB : MF)
++    AnalyzeBlock(&BB, Tokens);
+ 
+   // Sort to favor more complex ifcvt scheme.
+   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
+@@ -923,14 +926,14 @@
+ /// that all the intervening blocks are empty (given BB can fall through to its
+ /// next block).
+ static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
+-  MachineFunction::iterator PI = BB;
++  MachineFunction::iterator PI = BB->getIterator();
+   MachineFunction::iterator I = std::next(PI);
+-  MachineFunction::iterator TI = ToBB;
++  MachineFunction::iterator TI = ToBB->getIterator();
+   MachineFunction::iterator E = BB->getParent()->end();
+   while (I != TI) {
+     // Check isSuccessor to avoid case where the next block is empty, but
+     // it's not a successor.
+-    if (I == E || !I->empty() || !PI->isSuccessor(I))
++    if (I == E || !I->empty() || !PI->isSuccessor(&*I))
+       return false;
+     PI = I++;
+   }
+--- lib/CodeGen/InterferenceCache.cpp	2014-04-21 19:02:50.000000000 -0700
++++ lib/CodeGen/InterferenceCache.cpp	2015-12-06 19:36:56.386076813 -0800
+@@ -143,7 +143,8 @@
+     PrevPos = Start;
+   }
+ 
+-  MachineFunction::const_iterator MFI = MF->getBlockNumbered(MBBNum);
++  MachineFunction::const_iterator MFI =
++    MF->getBlockNumbered(MBBNum)->getIterator();
+   BlockInterference *BI = &Blocks[MBBNum];
+   ArrayRef<SlotIndex> RegMaskSlots;
+   ArrayRef<const uint32_t*> RegMaskBits;
+--- lib/CodeGen/IntrinsicLowering.cpp	2014-08-30 11:33:35.000000000 -0700
++++ lib/CodeGen/IntrinsicLowering.cpp	2015-12-06 19:45:17.855570385 -0800
+@@ -75,7 +75,7 @@
+   Constant* FCache = M->getOrInsertFunction(NewFn,
+                                   FunctionType::get(RetTy, ParamTys, false));
+ 
+-  IRBuilder<> Builder(CI->getParent(), CI);
++  IRBuilder<> Builder(CI->getParent(), CI->getIterator());
+   SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
+   CallInst *NewCI = Builder.CreateCall(FCache, Args);
+   NewCI->setName(CI->getName());
+@@ -94,71 +94,73 @@
+ 
+ void IntrinsicLowering::AddPrototypes(Module &M) {
+   LLVMContext &Context = M.getContext();
+-  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+-    if (I->isDeclaration() && !I->use_empty())
+-      switch (I->getIntrinsicID()) {
++  for (auto &I : M) {
++    if (I.isDeclaration() && !I.use_empty()) {
++      switch (I.getIntrinsicID()) {
+       default: break;
+       case Intrinsic::setjmp:
+-        EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
+-                             Type::getInt32Ty(M.getContext()));
+-        break;
++               EnsureFunctionExists(M, "setjmp", I.arg_begin(), I.arg_end(),
++                                    Type::getInt32Ty(M.getContext()));
++               break;
+       case Intrinsic::longjmp:
+-        EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
+-                             Type::getVoidTy(M.getContext()));
+-        break;
++               EnsureFunctionExists(M, "longjmp", I.arg_begin(), I.arg_end(),
++                                    Type::getVoidTy(M.getContext()));
++               break;
+       case Intrinsic::siglongjmp:
+-        EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
+-                             Type::getVoidTy(M.getContext()));
+-        break;
++               EnsureFunctionExists(M, "abort", I.arg_end(), I.arg_end(),
++                                    Type::getVoidTy(M.getContext()));
++               break;
+       case Intrinsic::memcpy:
+-        M.getOrInsertFunction("memcpy",
+-          Type::getInt8PtrTy(Context),
+-                              Type::getInt8PtrTy(Context), 
+-                              Type::getInt8PtrTy(Context), 
+-                              DL.getIntPtrType(Context), nullptr);
+-        break;
++               M.getOrInsertFunction("memcpy",
++                                     Type::getInt8PtrTy(Context),
++                                     Type::getInt8PtrTy(Context),
++                                     Type::getInt8PtrTy(Context),
++                                     DL.getIntPtrType(Context), nullptr);
++               break;
+       case Intrinsic::memmove:
+-        M.getOrInsertFunction("memmove",
+-          Type::getInt8PtrTy(Context),
+-                              Type::getInt8PtrTy(Context), 
+-                              Type::getInt8PtrTy(Context), 
+-                              DL.getIntPtrType(Context), nullptr);
+-        break;
++               M.getOrInsertFunction("memmove",
++                                     Type::getInt8PtrTy(Context),
++                                     Type::getInt8PtrTy(Context),
++                                     Type::getInt8PtrTy(Context),
++                                     DL.getIntPtrType(Context), nullptr);
++               break;
+       case Intrinsic::memset:
+-        M.getOrInsertFunction("memset",
+-          Type::getInt8PtrTy(Context),
+-                              Type::getInt8PtrTy(Context), 
+-                              Type::getInt32Ty(M.getContext()), 
+-                              DL.getIntPtrType(Context), nullptr);
+-        break;
++               M.getOrInsertFunction("memset",
++                                     Type::getInt8PtrTy(Context),
++                                     Type::getInt8PtrTy(Context),
++                                     Type::getInt32Ty(M.getContext()),
++                                     DL.getIntPtrType(Context), nullptr);
++               break;
+       case Intrinsic::sqrt:
+-        EnsureFPIntrinsicsExist(M, I, "sqrtf", "sqrt", "sqrtl");
+-        break;
++               EnsureFPIntrinsicsExist(M, &I, "sqrtf", "sqrt", "sqrtl");
++               break;
+       case Intrinsic::sin:
+-        EnsureFPIntrinsicsExist(M, I, "sinf", "sin", "sinl");
+-        break;
++               EnsureFPIntrinsicsExist(M, &I, "sinf", "sin", "sinl");
++               break;
+       case Intrinsic::cos:
+-        EnsureFPIntrinsicsExist(M, I, "cosf", "cos", "cosl");
+-        break;
++               EnsureFPIntrinsicsExist(M, &I, "cosf", "cos", "cosl");
++               break;
+       case Intrinsic::pow:
+-        EnsureFPIntrinsicsExist(M, I, "powf", "pow", "powl");
+-        break;
++               EnsureFPIntrinsicsExist(M, &I, "powf", "pow", "powl");
++               break;
+       case Intrinsic::log:
+-        EnsureFPIntrinsicsExist(M, I, "logf", "log", "logl");
+-        break;
++               EnsureFPIntrinsicsExist(M, &I, "logf", "log", "logl");
++               break;
+       case Intrinsic::log2:
+-        EnsureFPIntrinsicsExist(M, I, "log2f", "log2", "log2l");
+-        break;
++               EnsureFPIntrinsicsExist(M, &I, "log2f", "log2", "log2l");
++               break;
+       case Intrinsic::log10:
+-        EnsureFPIntrinsicsExist(M, I, "log10f", "log10", "log10l");
+-        break;
++               EnsureFPIntrinsicsExist(M, &I, "log10f", "log10", "log10l");
++               break;
+       case Intrinsic::exp:
+-        EnsureFPIntrinsicsExist(M, I, "expf", "exp", "expl");
+-        break;
++               EnsureFPIntrinsicsExist(M, &I, "expf", "exp", "expl");
++               break;
+       case Intrinsic::exp2:
+-        EnsureFPIntrinsicsExist(M, I, "exp2f", "exp2", "exp2l");
+-        break;
++               EnsureFPIntrinsicsExist(M, &I, "exp2f", "exp2", "exp2l");
++               break;
+       }
++    }
++  }
+ }
+ 
+ /// LowerBSWAP - Emit the code to lower bswap of V before the specified
+@@ -168,7 +170,7 @@
+ 
+   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
+   
+-  IRBuilder<> Builder(IP->getParent(), IP);
++  IRBuilder<> Builder(IP->getParent(), IP->getIterator());
+ 
+   switch(BitSize) {
+   default: llvm_unreachable("Unhandled type size of value to byteswap!");
+@@ -268,7 +270,7 @@
+     0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
+   };
+ 
+-  IRBuilder<> Builder(IP->getParent(), IP);
++  IRBuilder<> Builder(IP->getParent(), IP->getIterator());
+ 
+   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
+   unsigned WordSize = (BitSize + 63) / 64;
+@@ -301,7 +303,7 @@
+ /// instruction IP.
+ static Value *LowerCTLZ(LLVMContext &Context, Value *V, Instruction *IP) {
+ 
+-  IRBuilder<> Builder(IP->getParent(), IP);
++  IRBuilder<> Builder(IP->getParent(), IP->getIterator());
+ 
+   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
+   for (unsigned i = 1; i < BitSize; i <<= 1) {
+@@ -338,7 +340,7 @@
+ }
+ 
+ void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
+-  IRBuilder<> Builder(CI->getParent(), CI);
++  IRBuilder<> Builder(CI->getParent(), CI->getIterator());
+   LLVMContext &Context = CI->getContext();
+ 
+   const Function *Callee = CI->getCalledFunction();
+--- lib/CodeGen/LiveDebugVariables.cpp	2015-01-14 03:23:27.000000000 -0800
++++ lib/CodeGen/LiveDebugVariables.cpp	2015-12-06 19:51:37.891248865 -0800
+@@ -480,7 +480,7 @@
+   bool Changed = false;
+   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
+        ++MFI) {
+-    MachineBasicBlock *MBB = MFI;
++    MachineBasicBlock *MBB = &*MFI;
+     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
+          MBBI != MBBE;) {
+       if (!MBBI->isDebugValue()) {
+@@ -974,11 +974,11 @@
+     SlotIndex Stop = I.stop();
+     unsigned LocNo = I.value();
+     DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
+-    MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
+-    SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
++    MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
++    SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
+ 
+     DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
+-    insertDebugValue(MBB, Start, LocNo, LIS, TII);
++    insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
+     // This interval may span multiple basic blocks.
+     // Insert a DBG_VALUE into each one.
+     while(Stop > MBBEnd) {
+@@ -986,9 +986,9 @@
+       Start = MBBEnd;
+       if (++MBB == MFEnd)
+         break;
+-      MBBEnd = LIS.getMBBEndIdx(MBB);
++      MBBEnd = LIS.getMBBEndIdx(&*MBB);
+       DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
+-      insertDebugValue(MBB, Start, LocNo, LIS, TII);
++      insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
+     }
+     DEBUG(dbgs() << '\n');
+     if (MBB == MFEnd)
+--- lib/CodeGen/LiveIntervalAnalysis.cpp	2014-12-23 18:11:43.000000000 -0800
++++ lib/CodeGen/LiveIntervalAnalysis.cpp	2015-12-06 19:52:56.875852273 -0800
+@@ -211,7 +211,7 @@
+   // Find all instructions with regmask operands.
+   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
+        MBBI != E; ++MBBI) {
+-    MachineBasicBlock *MBB = MBBI;
++    MachineBasicBlock *MBB = &*MBBI;
+     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
+     RMB.first = RegMaskSlots.size();
+     for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
+@@ -285,7 +285,7 @@
+   // Check all basic blocks for live-ins.
+   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
+        MFI != MFE; ++MFI) {
+-    const MachineBasicBlock *MBB = MFI;
++    const MachineBasicBlock *MBB = &*MFI;
+ 
+     // We only care about ABI blocks: Entry + landing pads.
+     if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
+--- lib/CodeGen/LiveVariables.cpp	2014-10-14 00:22:08.000000000 -0700
++++ lib/CodeGen/LiveVariables.cpp	2015-12-06 19:54:20.348152143 -0800
+@@ -639,7 +639,7 @@
+   // function.  This guarantees that we will see the definition of a virtual
+   // register before its uses due to dominance properties of SSA (except for PHI
+   // nodes, which are treated as a special case).
+-  MachineBasicBlock *Entry = MF->begin();
++  MachineBasicBlock *Entry = &MF->front();
+   SmallPtrSet<MachineBasicBlock*,16> Visited;
+ 
+   for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
+--- lib/CodeGen/LocalStackSlotAllocation.cpp	2014-12-01 14:52:56.000000000 -0800
++++ lib/CodeGen/LocalStackSlotAllocation.cpp	2015-12-06 19:56:09.955965495 -0800
+@@ -324,7 +324,7 @@
+   // Sort the frame references by local offset
+   array_pod_sort(FrameReferenceInsns.begin(), FrameReferenceInsns.end());
+ 
+-  MachineBasicBlock *Entry = Fn.begin();
++  MachineBasicBlock *Entry = &Fn.front();
+ 
+   unsigned BaseReg = 0;
+   int64_t BaseOffset = 0;
+--- lib/CodeGen/MachineBasicBlock.cpp	2014-12-22 05:00:36.000000000 -0800
++++ lib/CodeGen/MachineBasicBlock.cpp	2015-12-06 20:28:52.972371805 -0800
+@@ -300,8 +300,8 @@
+ 
+   for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
+     if (Indexes) {
+-      if (Indexes->hasIndex(I))
+-        OS << Indexes->getInstructionIndex(I);
++      if (Indexes->hasIndex(&*I))
++        OS << Indexes->getInstructionIndex(&*I);
+       OS << '\t';
+     }
+     OS << '\t';
+@@ -372,12 +372,11 @@
+ }
+ 
+ void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
+-  getParent()->splice(NewAfter, this);
++  getParent()->splice(NewAfter->getIterator(), getIterator());
+ }
+ 
+ void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
+-  MachineFunction::iterator BBI = NewBefore;
+-  getParent()->splice(++BBI, this);
++  getParent()->splice(++NewBefore->getIterator(), getIterator());
+ }
+ 
+ void MachineBasicBlock::updateTerminator() {
+@@ -623,14 +622,14 @@
+ }
+ 
+ bool MachineBasicBlock::canFallThrough() {
+-  MachineFunction::iterator Fallthrough = this;
++  MachineFunction::iterator Fallthrough = getIterator();
+   ++Fallthrough;
+   // If FallthroughBlock is off the end of the function, it can't fall through.
+   if (Fallthrough == getParent()->end())
+     return false;
+ 
+   // If FallthroughBlock isn't a successor, no fallthrough is possible.
+-  if (!isSuccessor(Fallthrough))
++  if (!isSuccessor(&*Fallthrough))
+     return false;
+ 
+   // Analyze the branches, if any, at the end of the block.
+@@ -721,7 +720,7 @@
+   if (LV)
+     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
+          I != E; ++I) {
+-      MachineInstr *MI = I;
++      MachineInstr *MI = &*I;
+       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
+            OE = MI->operands_end(); OI != OE; ++OI) {
+         if (!OI->isReg() || OI->getReg() == 0 ||
+@@ -741,7 +740,7 @@
+   if (LIS) {
+     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
+          I != E; ++I) {
+-      MachineInstr *MI = I;
++      MachineInstr *MI = &*I;
+ 
+       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
+            OE = MI->operands_end(); OI != OE; ++OI) {
+@@ -763,7 +762,7 @@
+   if (Indexes) {
+     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
+          I != E; ++I)
+-      Terminators.push_back(I);
++      Terminators.push_back(&*I);
+   }
+ 
+   updateTerminator();
+@@ -772,7 +771,7 @@
+     SmallVector<MachineInstr*, 4> NewTerminators;
+     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
+          I != E; ++I)
+-      NewTerminators.push_back(I);
++      NewTerminators.push_back(&*I);
+ 
+     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
+         E = Terminators.end(); I != E; ++I) {
+@@ -794,9 +793,9 @@
+            I != E; ++I) {
+         // Some instructions may have been moved to NMBB by updateTerminator(),
+         // so we first remove any instruction that already has an index.
+-        if (Indexes->hasIndex(I))
+-          Indexes->removeMachineInstrFromMaps(I);
+-        Indexes->insertMachineInstrInMaps(I);
++        if (Indexes->hasIndex(&*I))
++          Indexes->removeMachineInstrFromMaps(&*I);
++        Indexes->insertMachineInstrInMaps(&*I);
+       }
+     }
+   }
+@@ -811,7 +810,7 @@
+ 
+   // Inherit live-ins from the successor
+   for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
+-         E = Succ->livein_end(); I != E; ++I)
++       E = Succ->livein_end(); I != E; ++I)
+     NMBB->addLiveIn(*I);
+ 
+   // Update LiveVariables.
+@@ -824,7 +823,7 @@
+         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
+           continue;
+         if (TargetRegisterInfo::isVirtualRegister(Reg))
+-          LV->getVarInfo(Reg).Kills.push_back(I);
++          LV->getVarInfo(Reg).Kills.push_back(&*I);
+         DEBUG(dbgs() << "Restored terminator kill: " << *I);
+         break;
+       }
+@@ -943,7 +942,7 @@
+ 
+ MachineBasicBlock::instr_iterator
+ MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
+-  unbundleSingleMI(I);
++  unbundleSingleMI(&*I);
+   return Insts.erase(I);
+ }
+ 
+@@ -1038,12 +1037,12 @@
+ 
+   if (!DestA && !DestB) {
+     // Block falls through to successor.
+-    DestA = FallThru;
+-    DestB = FallThru;
++    DestA = &*FallThru;
++    DestB = &*FallThru;
+   } else if (DestA && !DestB) {
+     if (isCond)
+       // Block ends in conditional jump that falls through to successor.
+-      DestB = FallThru;
++      DestB = &*FallThru;
+   } else {
+     assert(DestA && DestB && isCond &&
+            "CFG in a bad state. Cannot correct CFG edges");
+--- lib/CodeGen/MachineBlockFrequencyInfo.cpp	2014-06-26 15:52:05.000000000 -0700
++++ lib/CodeGen/MachineBlockFrequencyInfo.cpp	2015-12-06 20:30:07.075098190 -0800
+@@ -57,7 +57,7 @@
+ 
+   static inline
+   const NodeType *getEntryNode(const MachineBlockFrequencyInfo *G) {
+-    return G->getFunction()->begin();
++    return &G->getFunction()->front();
+   }
+ 
+   static ChildIteratorType child_begin(const NodeType *N) {
+--- lib/CodeGen/MachineBlockPlacement.cpp	2015-01-03 09:58:24.000000000 -0800
++++ lib/CodeGen/MachineBlockPlacement.cpp	2015-12-06 20:45:33.550025788 -0800
+@@ -471,14 +471,14 @@
+     const BlockFilterSet *BlockFilter) {
+   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
+        ++I) {
+-    if (BlockFilter && !BlockFilter->count(I))
++    if (BlockFilter && !BlockFilter->count(&*I))
+       continue;
+-    if (BlockToChain[I] != &PlacedChain) {
++    if (BlockToChain[&*I] != &PlacedChain) {
+       PrevUnplacedBlockIt = I;
+       // Now select the head of the chain to which the unplaced block belongs
+       // as the block to place. This will force the entire chain to be placed,
+       // and satisfies the requirements of merging chains.
+-      return *BlockToChain[I]->begin();
++      return *BlockToChain[&*I]->begin();
+     }
+   }
+   return nullptr;
+@@ -878,9 +878,9 @@
+   // the assumptions of the remaining algorithm.
+   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
+   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
+-    MachineBasicBlock *BB = FI;
+-    BlockChain *Chain
+-      = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
++    MachineBasicBlock *BB = &*FI;
++    BlockChain *Chain =
++      new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
+     // Also, merge any blocks which we cannot reason about and must preserve
+     // the exact fallthrough behavior for.
+     for (;;) {
+@@ -890,7 +890,7 @@
+         break;
+ 
+       MachineFunction::iterator NextFI(std::next(FI));
+-      MachineBasicBlock *NextBB = NextFI;
++      MachineBasicBlock *NextBB = &*NextFI;
+       // Ensure that the layout successor is a viable block, as we know that
+       // fallthrough is a possibility.
+       assert(NextFI != FE && "Can't fallthrough past the last block.");
+@@ -944,8 +944,9 @@
+     // Crash at the end so we get all of the debugging output first.
+     bool BadFunc = false;
+     FunctionBlockSetType FunctionBlockSet;
+-    for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
+-      FunctionBlockSet.insert(FI);
++
++    for (MachineBasicBlock &MBB : F)
++      FunctionBlockSet.insert(&MBB);
+ 
+     for (BlockChain::iterator BCI = FunctionChain.begin(),
+                               BCE = FunctionChain.end();
+@@ -969,21 +970,19 @@
+ 
+   // Splice the blocks into place.
+   MachineFunction::iterator InsertPos = F.begin();
+-  for (BlockChain::iterator BI = FunctionChain.begin(),
+-                            BE = FunctionChain.end();
+-       BI != BE; ++BI) {
+-    DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
++  for (MachineBasicBlock *BI : FunctionChain) {
++    DEBUG(dbgs() << (BI == *FunctionChain.begin() ? "Placing chain "
+                                                   : "          ... ")
+-          << getBlockName(*BI) << "\n");
+-    if (InsertPos != MachineFunction::iterator(*BI))
+-      F.splice(InsertPos, *BI);
++          << getBlockName(BI) << "\n");
++    if (InsertPos != MachineFunction::iterator(BI))
++      F.splice(InsertPos, BI->getIterator());
+     else
+       ++InsertPos;
+ 
+     // Update the terminator of the previous block.
+-    if (BI == FunctionChain.begin())
++    if (BI == *FunctionChain.begin())
+       continue;
+-    MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
++    MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(BI));
+ 
+     // FIXME: It would be awesome of updateTerminator would just return rather
+     // than assert when the branch cannot be analyzed in order to remove this
+@@ -1002,7 +1001,7 @@
+       // is mistakenly pointing to "*BI".
+       //
+       bool needUpdateBr = true;
+-      if (!Cond.empty() && (!FBB || FBB == *BI)) {
++      if (!Cond.empty() && (!FBB || FBB == BI)) {
+         PrevBB->updateTerminator();
+         needUpdateBr = false;
+         Cond.clear();
+@@ -1050,7 +1049,7 @@
+     return;  // Empty chain.
+ 
+   const BranchProbability ColdProb(1, 5); // 20%
+-  BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
++  BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
+   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
+   for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
+                             BE = FunctionChain.end();
+@@ -1182,7 +1181,7 @@
+   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
+ 
+   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+-    BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
++    BlockFrequency BlockFreq = MBFI->getBlockFreq(&*I);
+     Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
+                                                   : NumUncondBranches;
+     Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
+@@ -1194,7 +1193,8 @@
+       if (I->isLayoutSuccessor(*SI))
+         continue;
+ 
+-      BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
++      BlockFrequency EdgeFreq =
++        BlockFreq * MBPI->getEdgeProbability(&*I, *SI);
+       ++NumBranches;
+       BranchTakenFreq += EdgeFreq.getFrequency();
+     }
+--- lib/CodeGen/MachineFunction.cpp	2015-01-12 16:48:10.000000000 -0800
++++ lib/CodeGen/MachineFunction.cpp	2015-12-06 20:48:05.529036618 -0800
+@@ -144,7 +144,7 @@
+   if (MBB == nullptr)
+     MBBI = begin();
+   else
+-    MBBI = MBB;
++    MBBI = MBB->getIterator();
+ 
+   // Figure out the block number this should have.
+   unsigned BlockNo = 0;
+@@ -164,7 +164,7 @@
+       if (MBBNumbering[BlockNo])
+         MBBNumbering[BlockNo]->setNumber(-1);
+ 
+-      MBBNumbering[BlockNo] = MBBI;
++      MBBNumbering[BlockNo] = &*MBBI;
+       MBBI->setNumber(BlockNo);
+     }
+   }
+--- lib/CodeGen/MachineInstr.cpp	2014-12-09 10:38:53.000000000 -0800
++++ lib/CodeGen/MachineInstr.cpp	2015-12-06 21:23:40.823649137 -0800
+@@ -825,7 +825,8 @@
+ 
+ bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
+   assert(!isBundledWithPred() && "Must be called on bundle header");
+-  for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
++  for (MachineBasicBlock::const_instr_iterator MII = getIterator();
++       /* empty */ ; ++MII) {
+     if (MII->getDesc().getFlags() & Mask) {
+       if (Type == AnyInBundle)
+         return true;
+@@ -849,13 +850,13 @@
+ 
+   if (isBundle()) {
+     // Both instructions are bundles, compare MIs inside the bundle.
+-    MachineBasicBlock::const_instr_iterator I1 = *this;
++    MachineBasicBlock::const_instr_iterator I1 = getIterator();
+     MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
+-    MachineBasicBlock::const_instr_iterator I2 = *Other;
++    MachineBasicBlock::const_instr_iterator I2 = Other->getIterator();
+     MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
+     while (++I1 != E1 && I1->isInsideBundle()) {
+       ++I2;
+-      if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
++      if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(&*I2, Check))
+         return false;
+     }
+   }
+@@ -961,7 +962,7 @@
+ void MachineInstr::bundleWithPred() {
+   assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
+   setFlag(BundledPred);
+-  MachineBasicBlock::instr_iterator Pred = this;
++  MachineBasicBlock::instr_iterator Pred = getIterator();
+   --Pred;
+   assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
+   Pred->setFlag(BundledSucc);
+@@ -970,7 +971,7 @@
+ void MachineInstr::bundleWithSucc() {
+   assert(!isBundledWithSucc() && "MI is already bundled with its successor");
+   setFlag(BundledSucc);
+-  MachineBasicBlock::instr_iterator Succ = this;
++  MachineBasicBlock::instr_iterator Succ = getIterator();
+   ++Succ;
+   assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
+   Succ->setFlag(BundledPred);
+@@ -979,7 +980,7 @@
+ void MachineInstr::unbundleFromPred() {
+   assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
+   clearFlag(BundledPred);
+-  MachineBasicBlock::instr_iterator Pred = this;
++  MachineBasicBlock::instr_iterator Pred = getIterator();
+   --Pred;
+   assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
+   Pred->clearFlag(BundledSucc);
+@@ -988,7 +989,7 @@
+ void MachineInstr::unbundleFromSucc() {
+   assert(isBundledWithSucc() && "MI isn't bundled with its successor");
+   clearFlag(BundledSucc);
+-  MachineBasicBlock::instr_iterator Succ = this;
++  MachineBasicBlock::instr_iterator Succ = getIterator();
+   ++Succ;
+   assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
+   Succ->clearFlag(BundledPred);
+@@ -1125,7 +1126,7 @@
+ /// Return the number of instructions inside the MI bundle, not counting the
+ /// header instruction.
+ unsigned MachineInstr::getBundleSize() const {
+-  MachineBasicBlock::const_instr_iterator I = this;
++  MachineBasicBlock::const_instr_iterator I = getIterator();
+   unsigned Size = 0;
+   while (I->isBundledWithSucc())
+     ++Size, ++I;
+--- lib/CodeGen/MachineLoopInfo.cpp	2014-03-02 04:27:27.000000000 -0800
++++ lib/CodeGen/MachineLoopInfo.cpp	2015-12-06 21:26:39.722845395 -0800
+@@ -50,11 +50,11 @@
+   MachineBasicBlock *TopMBB = getHeader();
+   MachineFunction::iterator Begin = TopMBB->getParent()->begin();
+   if (TopMBB != Begin) {
+-    MachineBasicBlock *PriorMBB = std::prev(MachineFunction::iterator(TopMBB));
++    MachineBasicBlock *PriorMBB = &*std::prev(TopMBB->getIterator());
+     while (contains(PriorMBB)) {
+       TopMBB = PriorMBB;
+       if (TopMBB == Begin) break;
+-      PriorMBB = std::prev(MachineFunction::iterator(TopMBB));
++      PriorMBB = &*std::prev(TopMBB->getIterator());
+     }
+   }
+   return TopMBB;
+@@ -64,11 +64,11 @@
+   MachineBasicBlock *BotMBB = getHeader();
+   MachineFunction::iterator End = BotMBB->getParent()->end();
+   if (BotMBB != std::prev(End)) {
+-    MachineBasicBlock *NextMBB = std::next(MachineFunction::iterator(BotMBB));
++    MachineBasicBlock *NextMBB = &*std::next(BotMBB->getIterator());
+     while (contains(NextMBB)) {
+       BotMBB = NextMBB;
+       if (BotMBB == std::next(MachineFunction::iterator(BotMBB))) break;
+-      NextMBB = std::next(MachineFunction::iterator(BotMBB));
++      NextMBB = &*std::next(BotMBB->getIterator());
+     }
+   }
+   return BotMBB;
+--- lib/CodeGen/MachineScheduler.cpp	2014-12-12 20:52:04.000000000 -0800
++++ lib/CodeGen/MachineScheduler.cpp	2015-12-06 21:37:05.936122225 -0800
+@@ -391,7 +391,7 @@
+   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
+        MBB != MBBEnd; ++MBB) {
+ 
+-    Scheduler.startBlock(MBB);
++    Scheduler.startBlock(&*MBB);
+ 
+ #ifndef NDEBUG
+     if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
+@@ -420,7 +420,7 @@
+ 
+       // Avoid decrementing RegionEnd for blocks with no terminator.
+       if (RegionEnd != MBB->end() ||
+-          isSchedBoundary(std::prev(RegionEnd), MBB, MF, TII, IsPostRA)) {
++          isSchedBoundary(std::prev(RegionEnd), &*MBB, MF, TII, IsPostRA)) {
+         --RegionEnd;
+         // Count the boundary instruction.
+         --RemainingInstrs;
+@@ -431,14 +431,14 @@
+       unsigned NumRegionInstrs = 0;
+       MachineBasicBlock::iterator I = RegionEnd;
+       for(;I != MBB->begin(); --I, --RemainingInstrs) {
+-        if (isSchedBoundary(std::prev(I), MBB, MF, TII, IsPostRA))
++        if (isSchedBoundary(std::prev(I), &*MBB, MF, TII, IsPostRA))
+           break;
+         if (!I->isDebugValue())
+           ++NumRegionInstrs;
+       }
+       // Notify the scheduler of the region, even if we may skip scheduling
+       // it. Perhaps it still needs to be bundled.
+-      Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
++      Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
+ 
+       // Skip empty scheduling regions (0 or 1 schedulable instructions).
+       if (I == RegionEnd || I == std::prev(RegionEnd)) {
+@@ -478,7 +478,7 @@
+     if (Scheduler.isPostRA()) {
+       // FIXME: Ideally, no further passes should rely on kill flags. However,
+       // thumb2 size reduction is currently an exception.
+-      Scheduler.fixupKills(MBB);
++      Scheduler.fixupKills(&*MBB);
+     }
+   }
+   Scheduler.finalizeSchedule();
+--- lib/CodeGen/MachineVerifier.cpp	2014-12-11 11:41:51.000000000 -0800
++++ lib/CodeGen/MachineVerifier.cpp	2015-12-06 22:06:08.770556953 -0800
+@@ -317,7 +317,7 @@
+   visitMachineFunctionBefore();
+   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
+        MFI!=MFE; ++MFI) {
+-    visitMachineBasicBlockBefore(MFI);
++    visitMachineBasicBlockBefore(&*MFI);
+     // Keep track of the current bundle header.
+     const MachineInstr *CurBundle = nullptr;
+     // Do we expect the next instruction to be part of the same bundle?
+@@ -325,8 +325,8 @@
+ 
+     for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
+            MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
+-      if (MBBI->getParent() != MFI) {
+-        report("Bad instruction parent pointer", MFI);
++      if (MBBI->getParent() != &*MFI) {
++        report("Bad instruction parent pointer", &*MFI);
+         *OS << "Instruction: " << *MBBI;
+         continue;
+       }
+@@ -334,33 +334,44 @@
+       // Check for consistent bundle flags.
+       if (InBundle && !MBBI->isBundledWithPred())
+         report("Missing BundledPred flag, "
+-               "BundledSucc was set on predecessor", MBBI);
++               "BundledSucc was set on predecessor", &*MBBI);
+       if (!InBundle && MBBI->isBundledWithPred())
+         report("BundledPred flag is set, "
+-               "but BundledSucc not set on predecessor", MBBI);
++               "but BundledSucc not set on predecessor", &*MBBI);
+ 
+       // Is this a bundle header?
+       if (!MBBI->isInsideBundle()) {
+         if (CurBundle)
+           visitMachineBundleAfter(CurBundle);
+-        CurBundle = MBBI;
++        CurBundle = &*MBBI;
+         visitMachineBundleBefore(CurBundle);
+       } else if (!CurBundle)
+-        report("No bundle header", MBBI);
+-      visitMachineInstrBefore(MBBI);
+-      for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
+-        visitMachineOperand(&MBBI->getOperand(I), I);
+-      visitMachineInstrAfter(MBBI);
++        report("No bundle header", &*MBBI);
++
++      visitMachineInstrBefore(&*MBBI);
++
++      for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
++        const MachineInstr &MI = *MBBI;
++        const MachineOperand &Op = MI.getOperand(I);
++        if (Op.getParent() != &MI)
++          report("Instruction has operand with wrong parent set", &MI);
++
++        visitMachineOperand(&Op, I);
++      }
++
++      visitMachineInstrAfter(&*MBBI);
+ 
+       // Was this the last bundled instruction?
+       InBundle = MBBI->isBundledWithSucc();
+     }
++
+     if (CurBundle)
+       visitMachineBundleAfter(CurBundle);
+     if (InBundle)
+       report("BundledSucc flag set on last instruction in block", &MFI->back());
+-    visitMachineBasicBlockAfter(MFI);
++    visitMachineBasicBlockAfter(&*MFI);
+   }
++
+   visitMachineFunctionAfter();
+ 
+   if (OutFile)
+@@ -573,7 +584,7 @@
+     // check whether its answers match up with reality.
+     if (!TBB && !FBB) {
+       // Block falls through to its successor.
+-      MachineFunction::const_iterator MBBI = MBB;
++      MachineFunction::const_iterator MBBI = MBB->getIterator();
+       ++MBBI;
+       if (MBBI == MF->end()) {
+         // It's possible that the block legitimately ends with a noreturn
+@@ -586,7 +597,7 @@
+       } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
+         report("MBB exits via unconditional fall-through but doesn't have "
+                "exactly one CFG successor!", MBB);
+-      } else if (!MBB->isSuccessor(MBBI)) {
++      } else if (!MBB->isSuccessor(&*MBBI)) {
+         report("MBB exits via unconditional fall-through but its successor "
+                "differs from its CFG successor!", MBB);
+       }
+@@ -624,7 +635,7 @@
+       }
+     } else if (TBB && !FBB && !Cond.empty()) {
+       // Block conditionally branches somewhere, otherwise falls through.
+-      MachineFunction::const_iterator MBBI = MBB;
++      MachineFunction::const_iterator MBBI = MBB->getIterator();
+       ++MBBI;
+       if (MBBI == MF->end()) {
+         report("MBB conditionally falls through out of function!", MBB);
+@@ -639,7 +650,7 @@
+       } else if (MBB->succ_size() != 2) {
+         report("MBB exits via conditional branch/fall-through but doesn't have "
+                "exactly two CFG successors!", MBB);
+-      } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
++      } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
+         report("MBB exits via conditional branch/fall-through but the CFG "
+                "successors don't match the actual successors!", MBB);
+       }
+@@ -1585,7 +1596,7 @@
+   }
+ 
+   // Now check all the basic blocks in this live segment.
+-  MachineFunction::const_iterator MFI = MBB;
++  MachineFunction::const_iterator MFI = MBB->getIterator();
+   // Is this live segment the beginning of a non-PHIDef VN?
+   if (S.start == VNI->def && !VNI->isPHIDef()) {
+     // Not live-in to any blocks.
+@@ -1595,7 +1606,7 @@
+     ++MFI;
+   }
+   for (;;) {
+-    assert(LiveInts->isLiveInToMBB(LR, MFI));
++    assert(LiveInts->isLiveInToMBB(LR, &*MFI));
+     // We don't know how to track physregs into a landing pad.
+     if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
+         MFI->isLandingPad()) {
+@@ -1607,7 +1618,7 @@
+ 
+     // Is VNI a PHI-def in the current block?
+     bool IsPHI = VNI->isPHIDef() &&
+-      VNI->def == LiveInts->getMBBStartIdx(MFI);
++      VNI->def == LiveInts->getMBBStartIdx(&*MFI);
+ 
+     // Check that VNI is live-out of all predecessors.
+     for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
+@@ -1620,7 +1631,7 @@
+         report("Register not marked live out of predecessor", *PI, LR, Reg,
+                LaneMask);
+         *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
+-            << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
++            << '@' << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
+             << PEnd << '\n';
+         continue;
+       }
+@@ -1632,7 +1643,7 @@
+         *OS << "Valno #" << PVNI->id << " live out of BB#"
+             << (*PI)->getNumber() << '@' << PEnd
+             << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
+-            << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
++            << '@' << LiveInts->getMBBStartIdx(&*MFI) << '\n';
+       }
+     }
+     if (&*MFI == EndMBB)
+--- lib/CodeGen/Passes.cpp	2015-02-11 16:29:01.000000000 -0800
++++ lib/CodeGen/Passes.cpp	2016-01-23 20:25:56.000000000 -0800
+@@ -83,10 +83,13 @@
+ static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
+     cl::desc("Verify generated machine code"),
+     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=nullptr));
++
++static std::string PMIInitString("option-unspecified");
+ static cl::opt<std::string>
+ PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
+                    cl::desc("Print machine instrs"),
+-                   cl::value_desc("pass-name"), cl::init("option-unspecified"));
++                   cl::value_desc("pass-name"),
++                   cl::init(PMIInitString));
+ 
+ // Temporary option to allow experimenting with MachineScheduler as a post-RA
+ // scheduler. Targets can "properly" enable this with
+--- lib/CodeGen/PostRASchedulerList.cpp	2014-10-29 08:23:11.000000000 -0700
++++ lib/CodeGen/PostRASchedulerList.cpp	2016-01-23 20:26:45.000000000 -0800
+@@ -58,11 +58,13 @@
+ EnablePostRAScheduler("post-RA-scheduler",
+                        cl::desc("Enable scheduling after register allocation"),
+                        cl::init(false), cl::Hidden);
++
++static std::string NoneString("none");
+ static cl::opt<std::string>
+ EnableAntiDepBreaking("break-anti-dependencies",
+                       cl::desc("Break post-RA scheduling anti-dependencies: "
+                                "\"critical\", \"all\", or \"none\""),
+-                      cl::init("none"), cl::Hidden);
++                      cl::init(NoneString), cl::Hidden);
+ 
+ // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
+ static cl::opt<int>
+@@ -318,7 +320,7 @@
+ #endif
+ 
+     // Initialize register live-range state for scheduling in this block.
+-    Scheduler.startBlock(MBB);
++    Scheduler.startBlock(&*MBB);
+ 
+     // Schedule each sequence of instructions not interrupted by a label
+     // or anything else that effectively needs to shut down scheduling.
+@@ -330,8 +332,8 @@
+       // Calls are not scheduling boundaries before register allocation, but
+       // post-ra we don't gain anything by scheduling across calls since we
+       // don't need to worry about register pressure.
+-      if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
+-        Scheduler.enterRegion(MBB, I, Current, CurrentCount - Count);
++      if (MI->isCall() || TII->isSchedulingBoundary(MI, &*MBB, Fn)) {
++        Scheduler.enterRegion(&*MBB, I, Current, CurrentCount - Count);
+         Scheduler.setEndIndex(CurrentCount);
+         Scheduler.schedule();
+         Scheduler.exitRegion();
+@@ -347,7 +349,7 @@
+     assert(Count == 0 && "Instruction count mismatch!");
+     assert((MBB->begin() == Current || CurrentCount != 0) &&
+            "Instruction count mismatch!");
+-    Scheduler.enterRegion(MBB, MBB->begin(), Current, CurrentCount);
++    Scheduler.enterRegion(&*MBB, MBB->begin(), Current, CurrentCount);
+     Scheduler.setEndIndex(CurrentCount);
+     Scheduler.schedule();
+     Scheduler.exitRegion();
+@@ -357,7 +359,7 @@
+     Scheduler.finishBlock();
+ 
+     // Update register kills
+-    Scheduler.fixupKills(MBB);
++    Scheduler.fixupKills(&*MBB);
+   }
+ 
+   return true;
+--- lib/CodeGen/ProcessImplicitDefs.cpp	2014-08-04 19:39:49.000000000 -0700
++++ lib/CodeGen/ProcessImplicitDefs.cpp	2015-12-07 06:32:25.399048598 -0800
+@@ -96,11 +96,11 @@
+ 
+   // This is a physreg implicit-def.
+   // Look for the first instruction to use or define an alias.
+-  MachineBasicBlock::instr_iterator UserMI = MI;
++  MachineBasicBlock::instr_iterator UserMI = MI->getIterator();
+   MachineBasicBlock::instr_iterator UserE = MI->getParent()->instr_end();
+   bool Found = false;
+   for (++UserMI; UserMI != UserE; ++UserMI) {
+-    for (MIOperands MO(UserMI); MO.isValid(); ++MO) {
++    for (MIOperands MO(&*UserMI); MO.isValid(); ++MO) {
+       if (!MO->isReg())
+         continue;
+       unsigned UserReg = MO->getReg();
+@@ -151,7 +151,7 @@
+     for (MachineBasicBlock::instr_iterator MBBI = MFI->instr_begin(),
+          MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI)
+       if (MBBI->isImplicitDef())
+-        WorkList.insert(MBBI);
++        WorkList.insert(&*MBBI);
+ 
+     if (WorkList.empty())
+       continue;
+--- lib/CodeGen/PrologEpilogInserter.cpp	2015-01-12 16:48:10.000000000 -0800
++++ lib/CodeGen/PrologEpilogInserter.cpp	2015-12-07 06:37:25.905435777 -0800
+@@ -94,13 +94,11 @@
+     return;
+ 
+   // Save refs to entry and return blocks.
+-  EntryBlock = Fn.begin();
+-  for (MachineFunction::iterator MBB = Fn.begin(), E = Fn.end();
+-       MBB != E; ++MBB)
+-    if (isReturnBlock(MBB))
+-      ReturnBlocks.push_back(MBB);
+-
+-  return;
++  EntryBlock = &Fn.front();
++  for (MachineBasicBlock &MBB : Fn) {
++    if (isReturnBlock(&MBB))
++      ReturnBlocks.push_back(&MBB);
++  }
+ }
+ 
+ /// StackObjSet - A set of stack object indexes
+@@ -728,11 +726,11 @@
+ 
+   // Handle the unreachable blocks.
+   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
+-    if (Reachable.count(BB))
++    if (Reachable.count(&*BB))
+       // Already handled in DFS traversal.
+       continue;
+     int SPAdj = 0;
+-    replaceFrameIndices(BB, Fn, SPAdj);
++    replaceFrameIndices(&*BB, Fn, SPAdj);
+   }
+ }
+ 
+@@ -873,7 +871,7 @@
+   // Run through the instructions and find any virtual registers.
+   for (MachineFunction::iterator BB = Fn.begin(),
+        E = Fn.end(); BB != E; ++BB) {
+-    RS->enterBasicBlock(BB);
++    RS->enterBasicBlock(&*BB);
+ 
+     int SPAdj = 0;
+ 
+@@ -922,7 +920,7 @@
+           assert (ScratchReg && "Missing scratch register!");
+           MachineRegisterInfo &MRI = Fn.getRegInfo();
+           Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
+-          
++
+           // Make sure MRI now accounts this register as used.
+           MRI.setPhysRegUsed(ScratchReg);
+ 
+@@ -938,7 +936,7 @@
+       // problem because we need the spill code before I: Move I to just
+       // prior to J.
+       if (I != std::prev(J)) {
+-        BB->splice(J, BB, I);
++        BB->splice(J, &*BB, I);
+ 
+         // Before we move I, we need to prepare the RS to visit I again.
+         // Specifically, RS will assert if it sees uses of registers that
+--- lib/CodeGen/RegisterCoalescer.cpp	2015-01-14 03:23:27.000000000 -0800
++++ lib/CodeGen/RegisterCoalescer.cpp	2015-12-07 06:39:22.414657202 -0800
+@@ -2669,7 +2669,7 @@
+   std::vector<MBBPriorityInfo> MBBs;
+   MBBs.reserve(MF->size());
+   for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
+-    MachineBasicBlock *MBB = I;
++    MachineBasicBlock *MBB = &*I;
+     MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
+                                    JoinSplitEdges && isSplitEdge(MBB)));
+   }
+--- lib/CodeGen/SelectionDAG/DAGCombiner.cpp	2015-04-01 17:15:35.000000000 -0700
++++ lib/CodeGen/SelectionDAG/DAGCombiner.cpp	2015-12-07 08:35:37.075981457 -0800
+@@ -1163,7 +1163,7 @@
+   // Add all the dag nodes to the worklist.
+   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
+        E = DAG.allnodes_end(); I != E; ++I)
+-    AddToWorklist(I);
++    AddToWorklist(&*I);
+ 
+   // Create a dummy node (which is not added to allnodes), that adds a reference
+   // to the root node, preventing it from being deleted, and tracking any
+--- lib/CodeGen/SelectionDAG/FastISel.cpp	2015-04-29 07:54:57.000000000 -0700
++++ lib/CodeGen/SelectionDAG/FastISel.cpp	2015-12-07 08:37:53.997786920 -0800
+@@ -116,9 +116,9 @@
+   for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
+                                     E = FuncInfo.Fn->arg_end();
+        I != E; ++I) {
+-    DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
++    DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I);
+     assert(VI != LocalValueMap.end() && "Missed an argument?");
+-    FuncInfo.ValueMap[I] = VI->second;
++    FuncInfo.ValueMap[&*I] = VI->second;
+   }
+   return true;
+ }
+--- lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp	2014-12-02 10:50:36.000000000 -0800
++++ lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp	2015-12-07 08:44:06.691399075 -0800
+@@ -130,7 +130,7 @@
+ 
+       // Look for inline asm that clobbers the SP register.
+       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
+-        ImmutableCallSite CS(I);
++        ImmutableCallSite CS(&*I);
+         if (isa<InlineAsm>(CS.getCalledValue())) {
+           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
+           std::vector<TargetLowering::AsmOperandInfo> Ops =
+@@ -167,10 +167,10 @@
+ 
+       // Mark values used outside their block as exported, by allocating
+       // a virtual register for them.
+-      if (isUsedOutsideOfDefiningBlock(I))
++      if (isUsedOutsideOfDefiningBlock(&*I))
+         if (!isa<AllocaInst>(I) ||
+             !StaticAllocaMap.count(cast<AllocaInst>(I)))
+-          InitializeRegForValue(I);
++          InitializeRegForValue(&*I);
+ 
+       // Collect llvm.dbg.declare information. This is done now instead of
+       // during the initial isel pass through the IR so that it is done
+@@ -204,15 +204,15 @@
+       }
+ 
+       // Decide the preferred extend type for a value.
+-      PreferredExtendType[I] = getPreferredExtendForValue(I);
++      PreferredExtendType[&*I] = getPreferredExtendForValue(&*I);
+     }
+ 
+   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
+   // also creates the initial PHI MachineInstrs, though none of the input
+   // operands are populated.
+   for (BB = Fn->begin(); BB != EB; ++BB) {
+-    MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
+-    MBBMap[BB] = MBB;
++    MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(&*BB);
++    MBBMap[&*BB] = MBB;
+     MF->push_back(MBB);
+ 
+     // Transfer the address-taken flag. This is necessary because there could
+--- lib/CodeGen/SelectionDAG/LegalizeDAG.cpp	2015-01-13 17:35:17.000000000 -0800
++++ lib/CodeGen/SelectionDAG/LegalizeDAG.cpp	2015-12-07 08:49:07.697376637 -0800
+@@ -4326,7 +4326,7 @@
+     for (auto NI = allnodes_end(); NI != allnodes_begin();) {
+       --NI;
+ 
+-      SDNode *N = NI;
++      SDNode *N = &*NI;
+       if (N->use_empty() && N != getRoot().getNode()) {
+         ++NI;
+         DeleteNode(N);
+--- lib/CodeGen/SelectionDAG/LegalizeTypes.cpp	2014-12-02 14:01:00.000000000 -0800
++++ lib/CodeGen/SelectionDAG/LegalizeTypes.cpp	2015-12-07 08:56:21.562944470 -0800
+@@ -77,10 +77,10 @@
+        E = DAG.allnodes_end(); I != E; ++I) {
+     // Remember nodes marked NewNode - they are subject to extra checking below.
+     if (I->getNodeId() == NewNode)
+-      NewNodes.push_back(I);
++      NewNodes.push_back(&*I);
+ 
+     for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) {
+-      SDValue Res(I, i);
++      SDValue Res(&*I, i);
+       bool Failed = false;
+ 
+       unsigned Mapped = 0;
+@@ -128,7 +128,7 @@
+           dbgs() << "Unprocessed value in a map!";
+           Failed = true;
+         }
+-      } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
++      } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(&*I)) {
+         if (Mapped > 1) {
+           dbgs() << "Value with legal type was transformed!";
+           Failed = true;
+@@ -198,7 +198,7 @@
+        E = DAG.allnodes_end(); I != E; ++I) {
+     if (I->getNumOperands() == 0) {
+       I->setNodeId(ReadyToProcess);
+-      Worklist.push_back(I);
++      Worklist.push_back(&*I);
+     } else {
+       I->setNodeId(Unanalyzed);
+     }
+@@ -406,7 +406,7 @@
+     bool Failed = false;
+ 
+     // Check that all result types are legal.
+-    if (!IgnoreNodeResults(I))
++    if (!IgnoreNodeResults(&*I))
+       for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
+         if (!isTypeLegal(I->getValueType(i))) {
+           dbgs() << "Result type " << i << " illegal!\n";
+--- lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp	2015-02-12 15:51:24.000000000 -0800
++++ lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp	2015-12-07 09:08:20.015507523 -0800
+@@ -159,7 +159,7 @@
+   DAG.AssignTopologicalOrder();
+   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
+        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
+-    LegalizeOp(SDValue(I, 0));
++    LegalizeOp(SDValue(&*I, 0));
+ 
+   // Finally, it's possible the root changed.  Get the new root.
+   SDValue OldRoot = DAG.getRoot();
+--- lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp	2015-12-07 09:09:27.427273648 -0800
+@@ -728,7 +728,7 @@
+   unsigned DAGSize = 0;
+   for (SelectionDAG::allnodes_iterator I = DAG->allnodes_begin(),
+          E = DAG->allnodes_end(); I != E; ++I) {
+-    SDNode *N = I;
++    SDNode *N = &*I;
+ 
+     // Use node id to record degree.
+     unsigned Degree = N->use_size();
+--- lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp	2015-05-08 07:13:47.000000000 -0700
++++ lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp	2015-12-07 10:48:44.168405053 -0800
+@@ -1460,7 +1460,7 @@
+   }
+ 
+   //  Create TmpBB after CurBB.
+-  MachineFunction::iterator BBI = CurBB;
++  MachineFunction::iterator BBI(CurBB);
+   MachineFunction &MF = DAG.getMachineFunction();
+   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
+   CurBB->getParent()->insert(++BBI, TmpBB);
+@@ -1575,9 +1575,9 @@
+ 
+   // Figure out which block is immediately after the current one.
+   MachineBasicBlock *NextBlock = nullptr;
+-  MachineFunction::iterator BBI = BrMBB;
++  MachineFunction::iterator BBI(BrMBB);
+   if (++BBI != FuncInfo.MF->end())
+-    NextBlock = BBI;
++    NextBlock = &*BBI;
+ 
+   if (I.isUnconditional()) {
+     // Update machine-CFG edges.
+@@ -1708,9 +1708,9 @@
+   // Set NextBlock to be the MBB immediately after the current one, if any.
+   // This is used to avoid emitting unnecessary branches to the next block.
+   MachineBasicBlock *NextBlock = nullptr;
+-  MachineFunction::iterator BBI = SwitchBB;
++  MachineFunction::iterator BBI(SwitchBB);
+   if (++BBI != FuncInfo.MF->end())
+-    NextBlock = BBI;
++    NextBlock = &*BBI;
+ 
+   // If the lhs block is the next block, invert the condition so that we can
+   // fall through to the lhs instead of the rhs block.
+@@ -1784,10 +1784,10 @@
+   // Set NextBlock to be the MBB immediately after the current one, if any.
+   // This is used to avoid emitting unnecessary branches to the next block.
+   MachineBasicBlock *NextBlock = nullptr;
+-  MachineFunction::iterator BBI = SwitchBB;
++  MachineFunction::iterator BBI(SwitchBB);
+ 
+   if (++BBI != FuncInfo.MF->end())
+-    NextBlock = BBI;
++    NextBlock = &*BBI;
+ 
+   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
+                                MVT::Other, CopyTo, CMP,
+@@ -1925,9 +1925,9 @@
+   // Set NextBlock to be the MBB immediately after the current one, if any.
+   // This is used to avoid emitting unnecessary branches to the next block.
+   MachineBasicBlock *NextBlock = nullptr;
+-  MachineFunction::iterator BBI = SwitchBB;
++  MachineFunction::iterator BBI(SwitchBB);
+   if (++BBI != FuncInfo.MF->end())
+-    NextBlock = BBI;
++    NextBlock = &*BBI;
+ 
+   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
+ 
+@@ -1994,9 +1994,9 @@
+   // Set NextBlock to be the MBB immediately after the current one, if any.
+   // This is used to avoid emitting unnecessary branches to the next block.
+   MachineBasicBlock *NextBlock = nullptr;
+-  MachineFunction::iterator BBI = SwitchBB;
++  MachineFunction::iterator BBI(SwitchBB);
+   if (++BBI != FuncInfo.MF->end())
+-    NextBlock = BBI;
++    NextBlock = &*BBI;
+ 
+   if (NextMBB != NextBlock)
+     BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
+@@ -2104,10 +2104,10 @@
+ 
+   // Figure out which block is immediately after the current one.
+   MachineBasicBlock *NextBlock = nullptr;
+-  MachineFunction::iterator BBI = CR.CaseBB;
++  MachineFunction::iterator BBI(CR.CaseBB);
+ 
+   if (++BBI != FuncInfo.MF->end())
+-    NextBlock = BBI;
++    NextBlock = &*BBI;
+ 
+   BranchProbabilityInfo *BPI = FuncInfo.BPI;
+   // If any two of the cases has the same destination, and if one value
+@@ -2291,7 +2291,7 @@
+   MachineFunction *CurMF = FuncInfo.MF;
+ 
+   // Figure out which block is immediately after the current one.
+-  MachineFunction::iterator BBI = CR.CaseBB;
++  MachineFunction::iterator BBI(CR.CaseBB);
+   ++BBI;
+ 
+   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
+@@ -2377,7 +2377,7 @@
+   MachineFunction *CurMF = FuncInfo.MF;
+ 
+   // Figure out which block is immediately after the current one.
+-  MachineFunction::iterator BBI = CR.CaseBB;
++  MachineFunction::iterator BBI(CR.CaseBB);
+   ++BBI;
+ 
+   Case& FrontCase = *CR.Range.first;
+@@ -2600,7 +2600,7 @@
+   BitTestInfo BTC;
+ 
+   // Figure out which block is immediately after the current one.
+-  MachineFunction::iterator BBI = CR.CaseBB;
++  MachineFunction::iterator BBI(CR.CaseBB);
+   ++BBI;
+ 
+   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
+@@ -7614,7 +7614,7 @@
+   if (FastISel)
+     return A->use_empty();
+ 
+-  const BasicBlock *Entry = A->getParent()->begin();
++  const BasicBlock *Entry = &A->getParent()->front();
+   for (const User *U : A->users())
+     if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
+       return false;  // Use not in entry block.
+@@ -7779,12 +7779,12 @@
+     // If this argument is unused then remember its value. It is used to generate
+     // debugging information.
+     if (I->use_empty() && NumValues) {
+-      SDB->setUnusedArgValue(I, InVals[i]);
++      SDB->setUnusedArgValue(&*I, InVals[i]);
+ 
+       // Also remember any frame index for use in FastISel.
+       if (FrameIndexSDNode *FI =
+           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
+-        FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
++        FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
+     }
+ 
+     for (unsigned Val = 0; Val != NumValues; ++Val) {
+@@ -7814,18 +7814,18 @@
+     // Note down frame index.
+     if (FrameIndexSDNode *FI =
+         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
+-      FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
++      FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
+ 
+     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
+                                      SDB->getCurSDLoc());
+ 
+-    SDB->setValue(I, Res);
++    SDB->setValue(&*I, Res);
+     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
+       if (LoadSDNode *LNode =
+           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
+         if (FrameIndexSDNode *FI =
+             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
+-        FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
++        FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
+     }
+ 
+     // If this argument is live outside of the entry block, insert a copy from
+@@ -7837,13 +7837,13 @@
+       // uses with vregs.
+       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
+       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
+-        FuncInfo->ValueMap[I] = Reg;
++        FuncInfo->ValueMap[&*I] = Reg;
+         continue;
+       }
+     }
+-    if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
+-      FuncInfo->InitializeRegForValue(I);
+-      SDB->CopyToExportRegsIfNeeded(I);
++    if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) {
++      FuncInfo->InitializeRegForValue(&*I);
++      SDB->CopyToExportRegsIfNeeded(&*I);
+     }
+   }
+ 
+@@ -7946,7 +7946,7 @@
+   // If SuccBB has not been created yet, create it.
+   if (!SuccMBB) {
+     MachineFunction *MF = ParentMBB->getParent();
+-    MachineFunction::iterator BBI = ParentMBB;
++    MachineFunction::iterator BBI(ParentMBB);
+     SuccMBB = MF->CreateMachineBasicBlock(BB);
+     MF->insert(++BBI, SuccMBB);
+   }
+--- lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp	2014-12-04 01:40:44.000000000 -0800
++++ lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp	2015-12-07 11:02:44.434678105 -0800
+@@ -554,7 +554,7 @@
+ 
+   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
+        I != E; ++I) {
+-    const SDNode *N = I;
++    const SDNode *N = &*I;
+     if (!N->hasOneUse() && N != getRoot().getNode())
+       DumpNodes(N, 2, this);
+   }
+--- lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp	2015-06-14 08:38:10.000000000 -0700
++++ lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp	2015-12-07 11:43:29.120419077 -0800
+@@ -401,7 +401,7 @@
+ 
+         // Okay, we have to split this edge.
+         SplitCriticalEdge(Pred->getTerminator(),
+-                          GetSuccessorNumber(Pred, BB), SDISel, true);
++                          GetSuccessorNumber(Pred, &*BB), SDISel, true);
+         goto ReprocessBlock;
+       }
+   }
+@@ -457,7 +457,7 @@
+   // If the first basic block in the function has live ins that need to be
+   // copied into vregs, emit the copies into the top of the block before
+   // emitting the code for the block.
+-  MachineBasicBlock *EntryMBB = MF->begin();
++  MachineBasicBlock *EntryMBB = &MF->front();
+   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
+   RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
+ 
+@@ -868,7 +868,7 @@
+     // graph) and preceding back toward the beginning (the entry
+     // node).
+     while (ISelPosition != CurDAG->allnodes_begin()) {
+-      SDNode *Node = --ISelPosition;
++      SDNode *Node = &*--ISelPosition;
+       // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
+       // but there are currently some corner cases that it misses. Also, this
+       // makes it theoretically possible to disable the DAGCombiner.
+@@ -1085,7 +1085,8 @@
+       FuncInfo->VisitedBBs.insert(LLVMBB);
+     }
+ 
+-    BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
++    BasicBlock::const_iterator const Begin =
++      LLVMBB->getFirstNonPHI()->getIterator();
+     BasicBlock::const_iterator const End = LLVMBB->end();
+     BasicBlock::const_iterator BI = End;
+ 
+@@ -1133,7 +1134,7 @@
+       unsigned NumFastIselRemaining = std::distance(Begin, End);
+       // Do FastISel on as many instructions as possible.
+       for (; BI != Begin; --BI) {
+-        const Instruction *Inst = std::prev(BI);
++        const Instruction *Inst = &*std::prev(BI);
+ 
+         // If we no longer require this instruction, skip it.
+         if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
+@@ -1154,7 +1155,7 @@
+           // Try to fold the load if so.
+           const Instruction *BeforeInst = Inst;
+           while (BeforeInst != Begin) {
+-            BeforeInst = std::prev(BasicBlock::const_iterator(BeforeInst));
++            BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
+             if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
+               break;
+           }
+@@ -1190,7 +1191,7 @@
+ 
+           bool HadTailCall = false;
+           MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
+-          SelectBasicBlock(Inst, BI, HadTailCall);
++          SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
+ 
+           // If the call was emitted as a tail call, we're done with the block.
+           // We also need to delete any previously emitted instructions.
+--- lib/CodeGen/SelectionDAG/SelectionDAG.cpp	2015-02-17 13:57:20.000000000 -0800
++++ lib/CodeGen/SelectionDAG/SelectionDAG.cpp	2015-12-07 09:14:05.327228003 -0800
+@@ -618,7 +618,7 @@
+   // Add all obviously-dead nodes to the DeadNodes worklist.
+   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
+     if (I->use_empty())
+-      DeadNodes.push_back(I);
++      DeadNodes.push_back(&*I);
+ 
+   RemoveDeadNodes(DeadNodes);
+ 
+@@ -937,7 +937,7 @@
+   assert(&*AllNodes.begin() == &EntryNode);
+   AllNodes.remove(AllNodes.begin());
+   while (!AllNodes.empty())
+-    DeallocateNode(AllNodes.begin());
++    DeallocateNode(&AllNodes.front());
+ }
+ 
+ BinarySDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, SDLoc DL,
+@@ -6139,13 +6139,15 @@
+   // Node Id fields for nodes At SortedPos and after will contain the
+   // count of outstanding operands.
+   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
+-    SDNode *N = I++;
++    SDNode *N = &*I;
++    ++I;
++
+     checkForCycles(N, this);
+     unsigned Degree = N->getNumOperands();
+     if (Degree == 0) {
+       // A node with no uses, add it to the result array immediately.
+       N->setNodeId(DAGSize++);
+-      allnodes_iterator Q = N;
++      allnodes_iterator Q(N);
+       if (Q != SortedPos)
+         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
+       assert(SortedPos != AllNodes.end() && "Overran node list");
+@@ -6159,7 +6161,7 @@
+   // Visit all the nodes. As we iterate, move nodes into sorted order,
+   // such that by the time the end is reached all nodes will be sorted.
+   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
+-    SDNode *N = I;
++    SDNode *N = &*I;
+     checkForCycles(N, this);
+     // N is in sorted position, so all its uses have one less operand
+     // that needs to be sorted.
+@@ -6183,7 +6185,7 @@
+     }
+     if (I == SortedPos) {
+ #ifndef NDEBUG
+-      SDNode *S = ++I;
++      SDNode *S = &*++I;
+       dbgs() << "Overran sorted position:\n";
+       S->dumprFull(this); dbgs() << "\n";
+       dbgs() << "Checking if this is due to cycles\n";
+--- lib/CodeGen/ShadowStackGC.cpp	2014-11-13 14:55:19.000000000 -0800
++++ lib/CodeGen/ShadowStackGC.cpp	2015-12-07 06:47:52.372680302 -0800
+@@ -112,7 +112,8 @@
+       case 1:
+         // Find all 'return', 'resume', and 'unwind' instructions.
+         while (StateBB != StateE) {
+-          BasicBlock *CurBB = StateBB++;
++          BasicBlock *CurBB = &*StateBB;
++          ++StateBB;
+ 
+           // Branches and invokes do not escape, only unwind, resume, and return
+           // do.
+@@ -120,7 +121,7 @@
+           if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI))
+             continue;
+ 
+-          Builder.SetInsertPoint(TI->getParent(), TI);
++          Builder.SetInsertPoint(TI);
+           return &Builder;
+         }
+ 
+@@ -164,7 +165,8 @@
+           // Split the basic block containing the function call.
+           BasicBlock *CallBB = CI->getParent();
+           BasicBlock *NewBB =
+-            CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
++            CallBB->splitBasicBlock(CI->getIterator(),
++                                    CallBB->getName() + ".cont");
+ 
+           // Remove the unconditional branch inserted at the end of CallBB.
+           CallBB->getInstList().pop_back();
+@@ -184,7 +186,7 @@
+           delete CI;
+         }
+ 
+-        Builder.SetInsertPoint(RI->getParent(), RI);
++        Builder.SetInsertPoint(RI);
+         return &Builder;
+       }
+     }
+--- lib/CodeGen/SjLjEHPrepare.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/CodeGen/SjLjEHPrepare.cpp	2015-12-07 06:54:48.366220128 -0800
+@@ -174,8 +174,8 @@
+   // values and replace the LPI with that aggregate.
+   Type *LPadType = LPI->getType();
+   Value *LPadVal = UndefValue::get(LPadType);
+-  IRBuilder<> Builder(
+-      std::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
++  auto *SelI = cast<Instruction>(SelVal);
++  IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
+   LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
+   LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
+ 
+@@ -186,7 +186,7 @@
+ /// it with all of the data that we know at this point.
+ Value *SjLjEHPrepare::setupFunctionContext(Function &F,
+                                            ArrayRef<LandingPadInst *> LPads) {
+-  BasicBlock *EntryBB = F.begin();
++  BasicBlock *EntryBB = &F.front();
+ 
+   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
+   // that needs to be restored on all exits from the function. This is an alloca
+@@ -195,12 +195,13 @@
+   unsigned Align =
+       TLI->getDataLayout()->getPrefTypeAlignment(FunctionContextTy);
+   FuncCtx = new AllocaInst(FunctionContextTy, nullptr, Align, "fn_context",
+-                           EntryBB->begin());
++                           &EntryBB->front());
+ 
+   // Fill in the function context structure.
+   for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
+     LandingPadInst *LPI = LPads[I];
+-    IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
++    IRBuilder<> Builder(LPI->getParent(),
++                        LPI->getParent()->getFirstInsertionPt());
+ 
+     // Reference the __data field.
+     Value *FCData = Builder.CreateConstGEP2_32(FuncCtx, 0, 2, "__data");
+@@ -253,13 +254,13 @@
+     // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
+     Value *TrueValue = ConstantInt::getTrue(F.getContext());
+     Value *UndefValue = UndefValue::get(Ty);
+-    Instruction *SI = SelectInst::Create(TrueValue, AI, UndefValue,
++    Instruction *SI = SelectInst::Create(TrueValue, &*AI, UndefValue,
+                                          AI->getName() + ".tmp",
+-                                         AfterAllocaInsPt);
++                                         &*AfterAllocaInsPt);
+     AI->replaceAllUsesWith(SI);
+ 
+     // Reset the operand, because it  was clobbered by the RAUW above.
+-    SI->setOperand(1, AI);
++    SI->setOperand(1, &*AI);
+   }
+ }
+ 
+@@ -274,7 +275,7 @@
+       // Ignore obvious cases we don't have to handle. In particular, most
+       // instructions either have no uses or only have a single use inside the
+       // current block. Ignore them quickly.
+-      Instruction *Inst = II;
++      Instruction *Inst = &*II;
+       if (Inst->use_empty())
+         continue;
+       if (Inst->hasOneUse() &&
+@@ -355,7 +356,7 @@
+       DemotePHIToStack(PN);
+ 
+     // Move the landingpad instruction back to the top of the landing pad block.
+-    LPI->moveBefore(UnwindBlock->begin());
++    LPI->moveBefore(&UnwindBlock->front());
+   }
+ }
+ 
+@@ -395,7 +396,7 @@
+ 
+   Value *FuncCtx =
+       setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
+-  BasicBlock *EntryBB = F.begin();
++  BasicBlock *EntryBB = &F.front();
+   IRBuilder<> Builder(EntryBB->getTerminator());
+ 
+   // Get a reference to the jump buffer.
+@@ -467,7 +468,7 @@
+         continue;
+       }
+       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
+-      StackAddr->insertAfter(I);
++      StackAddr->insertAfter(&*I);
+       Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
+       StoreStackAddr->insertAfter(StackAddr);
+     }
+--- lib/CodeGen/SlotIndexes.cpp	2014-04-21 19:02:50.000000000 -0700
++++ lib/CodeGen/SlotIndexes.cpp	2015-12-07 07:32:28.357221215 -0800
+@@ -172,8 +172,8 @@
+   // optionally includes an additional position prior to MBB->begin(), indicated
+   // by the includeStart flag. This is done so that we can iterate MIs in a MBB
+   // in parallel with SlotIndexes, but there should be a better way to do this.
+-  IndexList::iterator ListB = startIdx.listEntry();
+-  IndexList::iterator ListI = endIdx.listEntry();
++  IndexList::iterator ListB = startIdx.listEntry()->getIterator();
++  IndexList::iterator ListI = endIdx.listEntry()->getIterator();
+   MachineBasicBlock::iterator MBBI = End;
+   bool pastStart = false;
+   while (ListI != ListB || MBBI != Begin || (includeStart && !pastStart)) {
+--- lib/CodeGen/SpillPlacement.cpp	2014-10-02 15:23:14.000000000 -0700
++++ lib/CodeGen/SpillPlacement.cpp	2015-12-07 07:33:14.076165375 -0800
+@@ -190,7 +190,7 @@
+   setThreshold(MBFI->getEntryFreq());
+   for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {
+     unsigned Num = I->getNumber();
+-    BlockFrequencies[Num] = MBFI->getBlockFreq(I);
++    BlockFrequencies[Num] = MBFI->getBlockFreq(&*I);
+   }
+ 
+   // We never change the function.
+--- lib/CodeGen/SplitKit.cpp	2014-12-10 15:07:54.000000000 -0800
++++ lib/CodeGen/SplitKit.cpp	2015-12-07 07:59:47.837252063 -0800
+@@ -176,10 +176,11 @@
+   UseE = UseSlots.end();
+ 
+   // Loop over basic blocks where CurLI is live.
+-  MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
++  MachineFunction::iterator MFI =
++    LIS.getMBBFromIndex(LVI->start)->getIterator();
+   for (;;) {
+     BlockInfo BI;
+-    BI.MBB = MFI;
++    BI.MBB = &*MFI;
+     SlotIndex Start, Stop;
+     std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
+ 
+@@ -259,7 +260,7 @@
+     if (LVI->start < Stop)
+       ++MFI;
+     else
+-      MFI = LIS.getMBBFromIndex(LVI->start);
++      MFI = LIS.getMBBFromIndex(LVI->start)->getIterator();
+   }
+ 
+   assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
+@@ -275,8 +276,9 @@
+   unsigned Count = 0;
+ 
+   // Loop over basic blocks where li is live.
+-  MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start);
+-  SlotIndex Stop = LIS.getMBBEndIdx(MFI);
++  MachineFunction::const_iterator MFI =
++    LIS.getMBBFromIndex(LVI->start)->getIterator();
++  SlotIndex Stop = LIS.getMBBEndIdx(&*MFI);
+   for (;;) {
+     ++Count;
+     LVI = li->advanceTo(LVI, Stop);
+@@ -284,7 +286,7 @@
+       return Count;
+     do {
+       ++MFI;
+-      Stop = LIS.getMBBEndIdx(MFI);
++      Stop = LIS.getMBBEndIdx(&*MFI);
+     } while (Stop <= LVI->start);
+   }
+ }
+@@ -866,9 +868,11 @@
+       // This value has multiple defs in RegIdx, but it wasn't rematerialized,
+       // so the live range is accurate. Add live-in blocks in [Start;End) to the
+       // LiveInBlocks.
+-      MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
++      MachineFunction::iterator MBB =
++        LIS.getMBBFromIndex(Start)->getIterator();
+       SlotIndex BlockStart, BlockEnd;
+-      std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB);
++      std::tie(BlockStart, BlockEnd) =
++        LIS.getSlotIndexes()->getMBBRange(&*MBB);
+ 
+       // The first block may be live-in, or it may have its own def.
+       if (Start != BlockStart) {
+@@ -877,7 +881,7 @@
+         DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
+         // MBB has its own def. Is it also live-out?
+         if (BlockEnd <= End)
+-          LRC.setLiveOutValue(MBB, VNI);
++          LRC.setLiveOutValue(&*MBB, VNI);
+ 
+         // Skip to the next block for live-in.
+         ++MBB;
+@@ -888,23 +892,23 @@
+       assert(Start <= BlockStart && "Expected live-in block");
+       while (BlockStart < End) {
+         DEBUG(dbgs() << ">BB#" << MBB->getNumber());
+-        BlockEnd = LIS.getMBBEndIdx(MBB);
++        BlockEnd = LIS.getMBBEndIdx(&*MBB);
+         if (BlockStart == ParentVNI->def) {
+           // This block has the def of a parent PHI, so it isn't live-in.
+           assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
+           VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
+           assert(VNI && "Missing def for complex mapped parent PHI");
+           if (End >= BlockEnd)
+-            LRC.setLiveOutValue(MBB, VNI); // Live-out as well.
++            LRC.setLiveOutValue(&*MBB, VNI); // Live-out as well.
+         } else {
+           // This block needs a live-in value.  The last block covered may not
+           // be live-out.
+           if (End < BlockEnd)
+-            LRC.addLiveInBlock(LR, MDT[MBB], End);
++            LRC.addLiveInBlock(LR, MDT[&*MBB], End);
+           else {
+             // Live-through, and we don't know the value.
+-            LRC.addLiveInBlock(LR, MDT[MBB]);
+-            LRC.setLiveOutValue(MBB, nullptr);
++            LRC.addLiveInBlock(LR, MDT[&*MBB]);
++            LRC.setLiveOutValue(&*MBB, nullptr);
+           }
+         }
+         BlockStart = BlockEnd;
+--- lib/CodeGen/StackMapLivenessAnalysis.cpp	2015-01-13 09:47:59.000000000 -0800
++++ lib/CodeGen/StackMapLivenessAnalysis.cpp	2015-12-07 08:03:47.966214485 -0800
+@@ -86,7 +86,7 @@
+        MBBI != MBBE; ++MBBI) {
+     DEBUG(dbgs() << "****** BB " << MBBI->getName() << " ******\n");
+     LiveRegs.init(TRI);
+-    LiveRegs.addLiveOuts(MBBI);
++    LiveRegs.addLiveOuts(&*MBBI);
+     bool HasStackMap = false;
+     // Reverse iterate over all instructions and add the current live register
+     // set to an instruction if we encounter a patchpoint instruction.
+--- lib/CodeGen/StackProtector.cpp	2014-12-21 13:52:38.000000000 -0800
++++ lib/CodeGen/StackProtector.cpp	2015-12-07 08:06:06.725425403 -0800
+@@ -377,7 +377,8 @@
+   Value *StackGuardVar = nullptr; // The stack guard variable.
+ 
+   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
+-    BasicBlock *BB = I++;
++    BasicBlock *BB = &*I;
++    ++I;
+     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
+     if (!RI)
+       continue;
+@@ -437,7 +438,7 @@
+       BasicBlock *FailBB = CreateFailBB();
+ 
+       // Split the basic block before the return instruction.
+-      BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
++      BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
+ 
+       // Update the dominator tree if we need to.
+       if (DT && DT->isReachableFromEntry(BB)) {
+--- lib/CodeGen/TailDuplication.cpp	2014-08-04 19:39:49.000000000 -0700
++++ lib/CodeGen/TailDuplication.cpp	2015-12-07 08:11:12.192736388 -0800
+@@ -161,7 +161,7 @@
+ 
+ static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
+   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
+-    MachineBasicBlock *MBB = I;
++    MachineBasicBlock *MBB = &*I;
+     SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
+                                                 MBB->pred_end());
+     MachineBasicBlock::iterator MI = MBB->begin();
+@@ -322,7 +322,8 @@
+   }
+ 
+   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
+-    MachineBasicBlock *MBB = I++;
++    MachineBasicBlock *MBB = &*I;
++    ++I;
+ 
+     if (NumTails == TailDupLimit)
+       break;
+@@ -697,7 +698,7 @@
+                  << "From simple Succ: " << *TailBB);
+ 
+     MachineBasicBlock *NewTarget = *TailBB->succ_begin();
+-    MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(PredBB));
++    MachineBasicBlock *NextBB = &*std::next(PredBB->getIterator());
+ 
+     // Make PredFBB explicit.
+     if (PredCond.empty())
+@@ -855,7 +856,7 @@
+   // If TailBB was duplicated into all its predecessors except for the prior
+   // block, which falls through unconditionally, move the contents of this
+   // block into the prior block.
+-  MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(TailBB));
++  MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
+   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
+   SmallVector<MachineOperand, 4> PriorCond;
+   // This has to check PrevBB->succ_size() because EH edges are ignored by
+--- lib/CodeGen/TwoAddressInstructionPass.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/CodeGen/TwoAddressInstructionPass.cpp	2015-12-07 08:24:37.706267592 -0800
+@@ -634,7 +634,7 @@
+                                               unsigned RegA, unsigned RegB,
+                                               unsigned Dist) {
+   // FIXME: Why does convertToThreeAddress() need an iterator reference?
+-  MachineFunction::iterator MFI = MBB;
++  MachineFunction::iterator MFI = MBB->getIterator();
+   MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
+   assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
+   if (!NewMI)
+@@ -1535,7 +1535,7 @@
+   TiedOperandMap TiedOperands;
+   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
+        MBBI != MBBE; ++MBBI) {
+-    MBB = MBBI;
++    MBB = &*MBBI;
+     unsigned Dist = 0;
+     DistanceMap.clear();
+     SrcRegMap.clear();
+--- lib/CodeGen/UnreachableBlockElim.cpp	2014-08-24 16:23:06.000000000 -0700
++++ lib/CodeGen/UnreachableBlockElim.cpp	2015-12-07 08:28:10.169471890 -0800
+@@ -71,8 +71,8 @@
+   // in them.
+   std::vector<BasicBlock*> DeadBlocks;
+   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
+-    if (!Reachable.count(I)) {
+-      BasicBlock *BB = I;
++    if (!Reachable.count(&*I)) {
++      BasicBlock *BB = &*I;
+       DeadBlocks.push_back(BB);
+       while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
+         PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
+@@ -131,7 +131,7 @@
+   // in them.
+   std::vector<MachineBasicBlock*> DeadBlocks;
+   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+-    MachineBasicBlock *BB = I;
++    MachineBasicBlock *BB = &*I;
+ 
+     // Test for deadness.
+     if (!Reachable.count(BB)) {
+@@ -167,7 +167,7 @@
+ 
+   // Cleanup PHI nodes.
+   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+-    MachineBasicBlock *BB = I;
++    MachineBasicBlock *BB = &*I;
+     // Prune unneeded PHI entries.
+     SmallPtrSet<MachineBasicBlock*, 8> preds(BB->pred_begin(),
+                                              BB->pred_end());
+--- lib/CodeGen/VirtRegMap.cpp	2014-12-10 16:59:06.000000000 -0800
++++ lib/CodeGen/VirtRegMap.cpp	2015-12-07 08:29:40.895828212 -0800
+@@ -312,7 +312,7 @@
+     bool IsExitBB = MBBI->succ_empty();
+     for (MachineBasicBlock::instr_iterator
+            MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
+-      MachineInstr *MI = MII;
++      MachineInstr *MI = &*MII;
+       ++MII;
+ 
+       // Check if this instruction is a call to a noreturn function.  If this
+--- lib/ExecutionEngine/ExecutionEngine.cpp	2014-12-02 16:51:19.000000000 -0800
++++ lib/ExecutionEngine/ExecutionEngine.cpp	2015-12-07 12:04:19.264547988 -0800
+@@ -190,10 +190,10 @@
+   MutexGuard locked(lock);
+ 
+   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
+-    EEState.RemoveMapping(FI);
++    EEState.RemoveMapping(&*FI);
+   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
+        GI != GE; ++GI)
+-    EEState.RemoveMapping(GI);
++    EEState.RemoveMapping(&*GI);
+ }
+ 
+ void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
+--- lib/ExecutionEngine/Interpreter/Execution.cpp	2014-04-27 21:05:08.000000000 -0700
++++ lib/ExecutionEngine/Interpreter/Execution.cpp	2015-12-07 12:10:37.392666513 -0800
+@@ -2091,7 +2091,7 @@
+   }
+ 
+   // Get pointers to first LLVM BB & Instruction in function.
+-  StackFrame.CurBB     = F->begin();
++  StackFrame.CurBB     = &F->front();
+   StackFrame.CurInst   = StackFrame.CurBB->begin();
+ 
+   // Run through the function arguments and initialize their values...
+@@ -2103,7 +2103,7 @@
+   unsigned i = 0;
+   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 
+        AI != E; ++AI, ++i)
+-    SetValue(AI, ArgVals[i], StackFrame);
++    SetValue(&*AI, ArgVals[i], StackFrame);
+ 
+   // Handle varargs arguments...
+   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
+--- lib/IR/AsmWriter.cpp	2015-01-14 19:59:43.000000000 -0800
++++ lib/IR/AsmWriter.cpp	2015-11-24 08:43:48.354963500 -0800
+@@ -674,14 +674,14 @@
+   for (Module::const_global_iterator I = TheModule->global_begin(),
+          E = TheModule->global_end(); I != E; ++I) {
+     if (!I->hasName())
+-      CreateModuleSlot(I);
++      CreateModuleSlot(&(*I));
+   }
+ 
+   // Add metadata used by named metadata.
+   for (Module::const_named_metadata_iterator
+          I = TheModule->named_metadata_begin(),
+          E = TheModule->named_metadata_end(); I != E; ++I) {
+-    const NamedMDNode *NMD = I;
++    const NamedMDNode *NMD = &(*I);
+     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
+       CreateMetadataSlot(NMD->getOperand(i));
+   }
+@@ -690,7 +690,7 @@
+        I != E; ++I) {
+     if (!I->hasName())
+       // Add all the unnamed functions to the table.
+-      CreateModuleSlot(I);
++      CreateModuleSlot(&(*I));
+ 
+     // Add all the function attributes to the table.
+     // FIXME: Add attributes of other objects?
+@@ -711,7 +711,7 @@
+   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
+       AE = TheFunction->arg_end(); AI != AE; ++AI)
+     if (!AI->hasName())
+-      CreateFunctionSlot(AI);
++      CreateFunctionSlot(&(*AI));
+ 
+   ST_DEBUG("Inserting Instructions:\n");
+ 
+@@ -721,12 +721,12 @@
+   for (Function::const_iterator BB = TheFunction->begin(),
+        E = TheFunction->end(); BB != E; ++BB) {
+     if (!BB->hasName())
+-      CreateFunctionSlot(BB);
++      CreateFunctionSlot(&(*BB));
+ 
+     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
+          ++I) {
+       if (!I->getType()->isVoidTy() && !I->hasName())
+-        CreateFunctionSlot(I);
++        CreateFunctionSlot(&(*I));
+ 
+       // Intrinsics can directly use metadata.  We allow direct calls to any
+       // llvm.foo function here, because the target may not be linked into the
+@@ -1607,21 +1607,22 @@
+   if (!M->global_empty()) Out << '\n';
+   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
+        I != E; ++I) {
+-    printGlobal(I); Out << '\n';
++    printGlobal(&(*I));
++    Out << '\n';
+   }
+ 
+   // Output all aliases.
+   if (!M->alias_empty()) Out << "\n";
+   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
+        I != E; ++I)
+-    printAlias(I);
++    printAlias(&(*I));
+ 
+   // Output global use-lists.
+   printUseLists(nullptr);
+ 
+   // Output all of the functions.
+   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
+-    printFunction(I);
++    printFunction(&(*I));
+   assert(UseListOrders.empty() && "All use-lists should have been consumed");
+ 
+   // Output all attribute groups.
+@@ -1635,7 +1636,7 @@
+ 
+   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
+        E = M->named_metadata_end(); I != E; ++I)
+-    printNamedMDNode(I);
++    printNamedMDNode(&(*I));
+ 
+   // Output metadata.
+   if (!Machine.mdn_empty()) {
+@@ -1936,7 +1937,7 @@
+          I != E; ++I) {
+       // Insert commas as we go... the first arg doesn't get a comma
+       if (I != F->arg_begin()) Out << ", ";
+-      printArgument(I, Attrs, Idx);
++      printArgument(&(*I), Attrs, Idx);
+       Idx++;
+     }
+   } else {
+@@ -1988,7 +1989,7 @@
+     Out << " {";
+     // Output all of the function's basic blocks.
+     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
+-      printBasicBlock(I);
++      printBasicBlock(&(*I));
+ 
+     // Output the function's use-lists.
+     printUseLists(F);
+--- lib/IR/AutoUpgrade.cpp	2015-01-14 03:23:27.000000000 -0800
++++ lib/IR/AutoUpgrade.cpp	2015-11-24 09:08:05.216149050 -0800
+@@ -278,7 +278,7 @@
+   Function *F = CI->getCalledFunction();
+   LLVMContext &C = CI->getContext();
+   IRBuilder<> Builder(C);
+-  Builder.SetInsertPoint(CI->getParent(), CI);
++  Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
+ 
+   assert(F && "Intrinsic call is not direct?");
+ 
+@@ -304,7 +304,7 @@
+                Name == "llvm.x86.avx.movnt.ps.256" ||
+                Name == "llvm.x86.avx.movnt.pd.256") {
+       IRBuilder<> Builder(C);
+-      Builder.SetInsertPoint(CI->getParent(), CI);
++      Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
+ 
+       Module *M = F->getParent();
+       SmallVector<Metadata *, 1> Elts;
+--- lib/IR/BasicBlock.cpp	2014-12-22 05:00:36.000000000 -0800
++++ lib/IR/BasicBlock.cpp	2015-11-24 09:18:34.413275013 -0800
+@@ -60,7 +60,7 @@
+   assert(!Parent && "Already has a parent");
+ 
+   if (InsertBefore)
+-    NewParent->getBasicBlockList().insert(InsertBefore, this);
++    NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
+   else
+     NewParent->getBasicBlockList().push_back(this);
+ }
+@@ -95,26 +95,28 @@
+ }
+ 
+ void BasicBlock::removeFromParent() {
+-  getParent()->getBasicBlockList().remove(this);
++  getParent()->getBasicBlockList().remove(getIterator());
+ }
+ 
+ void BasicBlock::eraseFromParent() {
+-  getParent()->getBasicBlockList().erase(this);
++  getParent()->getBasicBlockList().erase(getIterator());
+ }
+ 
+ /// moveBefore - Unlink this basic block from its current function and
+ /// insert it into the function that MovePos lives in, right before MovePos.
+ void BasicBlock::moveBefore(BasicBlock *MovePos) {
+-  MovePos->getParent()->getBasicBlockList().splice(MovePos,
+-                       getParent()->getBasicBlockList(), this);
++  MovePos->getParent()->getBasicBlockList().splice(MovePos->getIterator(),
++                       getParent()->getBasicBlockList(), getIterator());
+ }
+ 
+ /// moveAfter - Unlink this basic block from its current function and
+ /// insert it into the function that MovePos lives in, right after MovePos.
+ void BasicBlock::moveAfter(BasicBlock *MovePos) {
+-  Function::iterator I = MovePos;
+-  MovePos->getParent()->getBasicBlockList().splice(++I,
+-                                       getParent()->getBasicBlockList(), this);
++  Function::iterator I = MovePos->getIterator();
++  Function::iterator II = ++I;
++  MovePos->getParent()->getBasicBlockList().splice(II,
++                                       getParent()->getBasicBlockList(),
++                                       getIterator());
+ }
+ 
+ 
+@@ -200,7 +202,7 @@
+ }
+ 
+ BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
+-  iterator InsertPt = getFirstNonPHI();
++  iterator InsertPt = getFirstNonPHI()->getIterator();
+   if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
+   return InsertPt;
+ }
+--- lib/IR/Core.cpp	2015-01-29 09:33:19.000000000 -0800
++++ lib/IR/Core.cpp	2015-11-24 20:09:32.108977930 -0800
+@@ -1517,7 +1517,8 @@
+   Module::global_iterator I = Mod->global_begin();
+   if (I == Mod->global_end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M) {
+@@ -1525,23 +1526,28 @@
+   Module::global_iterator I = Mod->global_end();
+   if (I == Mod->global_begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar) {
+   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
+-  Module::global_iterator I = GV;
++  Module::global_iterator I(GV);
+   if (++I == GV->getParent()->global_end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar) {
+   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
+-  Module::global_iterator I = GV;
++  Module::global_iterator I(GV);
+   if (I == GV->getParent()->global_begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ void LLVMDeleteGlobal(LLVMValueRef GlobalVar) {
+@@ -1550,8 +1556,9 @@
+ 
+ LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar) {
+   GlobalVariable* GV = unwrap<GlobalVariable>(GlobalVar);
+-  if ( !GV->hasInitializer() )
++  if (!GV->hasInitializer())
+     return nullptr;
++
+   return wrap(GV->getInitializer());
+ }
+ 
+@@ -1650,7 +1657,8 @@
+   Module::iterator I = Mod->begin();
+   if (I == Mod->end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M) {
+@@ -1658,23 +1666,28 @@
+   Module::iterator I = Mod->end();
+   if (I == Mod->begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn) {
+   Function *Func = unwrap<Function>(Fn);
+-  Module::iterator I = Func;
++  Module::iterator I(Func);
+   if (++I == Func->getParent()->end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn) {
+   Function *Func = unwrap<Function>(Fn);
+-  Module::iterator I = Func;
++  Module::iterator I(Func);
+   if (I == Func->getParent()->begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ void LLVMDeleteFunction(LLVMValueRef Fn) {
+@@ -1684,6 +1697,7 @@
+ unsigned LLVMGetIntrinsicID(LLVMValueRef Fn) {
+   if (Function *F = dyn_cast<Function>(unwrap(Fn)))
+     return F->getIntrinsicID();
++
+   return 0;
+ }
+ 
+@@ -1698,7 +1712,7 @@
+ 
+ const char *LLVMGetGC(LLVMValueRef Fn) {
+   Function *F = unwrap<Function>(Fn);
+-  return F->hasGC()? F->getGC() : nullptr;
++  return F->hasGC() ? F->getGC() : nullptr;
+ }
+ 
+ void LLVMSetGC(LLVMValueRef Fn, const char *GC) {
+@@ -1761,14 +1775,15 @@
+   Function *Fn = unwrap<Function>(FnRef);
+   for (Function::arg_iterator I = Fn->arg_begin(),
+                               E = Fn->arg_end(); I != E; I++)
+-    *ParamRefs++ = wrap(I);
++    *ParamRefs++ = wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetParam(LLVMValueRef FnRef, unsigned index) {
+   Function::arg_iterator AI = unwrap<Function>(FnRef)->arg_begin();
+   while (index --> 0)
+     AI++;
+-  return wrap(AI);
++
++  return wrap(&(*AI));
+ }
+ 
+ LLVMValueRef LLVMGetParamParent(LLVMValueRef V) {
+@@ -1780,7 +1795,8 @@
+   Function::arg_iterator I = Func->arg_begin();
+   if (I == Func->arg_end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn) {
+@@ -1788,23 +1804,28 @@
+   Function::arg_iterator I = Func->arg_end();
+   if (I == Func->arg_begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg) {
+   Argument *A = unwrap<Argument>(Arg);
+-  Function::arg_iterator I = A;
++  Function::arg_iterator I(A);
+   if (++I == A->getParent()->arg_end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg) {
+   Argument *A = unwrap<Argument>(Arg);
+-  Function::arg_iterator I = A;
++  Function::arg_iterator I(A);
+   if (I == A->getParent()->arg_begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ void LLVMAddAttribute(LLVMValueRef Arg, LLVMAttribute PA) {
+@@ -1862,7 +1883,7 @@
+ void LLVMGetBasicBlocks(LLVMValueRef FnRef, LLVMBasicBlockRef *BasicBlocksRefs){
+   Function *Fn = unwrap<Function>(FnRef);
+   for (Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++)
+-    *BasicBlocksRefs++ = wrap(I);
++    *BasicBlocksRefs++ = wrap(&(*I));
+ }
+ 
+ LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn) {
+@@ -1874,7 +1895,8 @@
+   Function::iterator I = Func->begin();
+   if (I == Func->end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn) {
+@@ -1882,23 +1904,28 @@
+   Function::iterator I = Func->end();
+   if (I == Func->begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB) {
+   BasicBlock *Block = unwrap(BB);
+-  Function::iterator I = Block;
++  Function::iterator I(Block);
+   if (++I == Block->getParent()->end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB) {
+   BasicBlock *Block = unwrap(BB);
+-  Function::iterator I = Block;
++  Function::iterator I(Block);
+   if (I == Block->getParent()->begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,
+@@ -1950,7 +1977,8 @@
+   BasicBlock::iterator I = Block->begin();
+   if (I == Block->end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB) {
+@@ -1958,23 +1986,28 @@
+   BasicBlock::iterator I = Block->end();
+   if (I == Block->begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst) {
+   Instruction *Instr = unwrap<Instruction>(Inst);
+-  BasicBlock::iterator I = Instr;
++  BasicBlock::iterator I(Instr);
+   if (++I == Instr->getParent()->end())
+     return nullptr;
+-  return wrap(I);
++
++  return wrap(&(*I));
+ }
+ 
+ LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst) {
+   Instruction *Instr = unwrap<Instruction>(Inst);
+-  BasicBlock::iterator I = Instr;
++  BasicBlock::iterator I(Instr);
+   if (I == Instr->getParent()->begin())
+     return nullptr;
+-  return wrap(--I);
++
++  --I;
++  return wrap(&(*I));
+ }
+ 
+ void LLVMInstructionEraseFromParent(LLVMValueRef Inst) {
+@@ -2142,12 +2175,12 @@
+                          LLVMValueRef Instr) {
+   BasicBlock *BB = unwrap(Block);
+   Instruction *I = Instr? unwrap<Instruction>(Instr) : (Instruction*) BB->end();
+-  unwrap(Builder)->SetInsertPoint(BB, I);
++  unwrap(Builder)->SetInsertPoint(BB, I->getIterator());
+ }
+ 
+ void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr) {
+   Instruction *I = unwrap<Instruction>(Instr);
+-  unwrap(Builder)->SetInsertPoint(I->getParent(), I);
++  unwrap(Builder)->SetInsertPoint(I->getParent(), I->getIterator());
+ }
+ 
+ void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block) {
+--- lib/IR/DebugInfo.cpp	2015-02-12 15:46:59.000000000 -0800
++++ lib/IR/DebugInfo.cpp	2015-11-24 20:11:47.916206795 -0800
+@@ -1485,7 +1485,7 @@
+ 
+   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
+          NME = M.named_metadata_end(); NMI != NME;) {
+-    NamedMDNode *NMD = NMI;
++    NamedMDNode *NMD = &(*NMI);
+     ++NMI;
+     if (NMD->getName().startswith("llvm.dbg.")) {
+       NMD->eraseFromParent();
+--- lib/IR/Function.cpp	2014-12-24 23:49:20.000000000 -0800
++++ lib/IR/Function.cpp	2015-11-27 09:29:07.971979862 -0800
+@@ -228,11 +228,11 @@
+ }
+ 
+ void Function::removeFromParent() {
+-  getParent()->getFunctionList().remove(this);
++  getParent()->getFunctionList().remove(getIterator());
+ }
+ 
+ void Function::eraseFromParent() {
+-  getParent()->getFunctionList().erase(this);
++  getParent()->getFunctionList().erase(getIterator());
+ }
+ 
+ //===----------------------------------------------------------------------===//
+--- lib/IR/Globals.cpp	2014-12-22 05:00:36.000000000 -0800
++++ lib/IR/Globals.cpp	2015-11-27 06:06:12.109691445 -0800
+@@ -178,7 +178,7 @@
+   }
+ 
+   if (Before)
+-    Before->getParent()->getGlobalList().insert(Before, this);
++    Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
+   else
+     M.getGlobalList().push_back(this);
+ }
+@@ -188,11 +188,11 @@
+ }
+ 
+ void GlobalVariable::removeFromParent() {
+-  getParent()->getGlobalList().remove(this);
++  getParent()->getGlobalList().remove(getIterator());
+ }
+ 
+ void GlobalVariable::eraseFromParent() {
+-  getParent()->getGlobalList().erase(this);
++  getParent()->getGlobalList().erase(getIterator());
+ }
+ 
+ void GlobalVariable::replaceUsesOfWithOnConstant(Value *From, Value *To,
+@@ -290,11 +290,11 @@
+ }
+ 
+ void GlobalAlias::removeFromParent() {
+-  getParent()->getAliasList().remove(this);
++  getParent()->getAliasList().remove(getIterator());
+ }
+ 
+ void GlobalAlias::eraseFromParent() {
+-  getParent()->getAliasList().erase(this);
++  getParent()->getAliasList().erase(getIterator());
+ }
+ 
+ void GlobalAlias::setAliasee(Constant *Aliasee) {
+--- lib/IR/Instruction.cpp	2014-12-22 05:00:36.000000000 -0800
++++ lib/IR/Instruction.cpp	2015-11-27 07:26:46.480147123 -0800
+@@ -26,9 +26,9 @@
+ 
+   // If requested, insert this instruction into a basic block...
+   if (InsertBefore) {
+-    assert(InsertBefore->getParent() &&
+-           "Instruction to insert before is not in a basic block!");
+-    InsertBefore->getParent()->getInstList().insert(InsertBefore, this);
++    BasicBlock *BB = InsertBefore->getParent();
++    assert(BB && "Instruction to insert before is not in a basic block!");
++    BB->getInstList().insert(InsertBefore->getIterator(), this);
+   }
+ }
+ 
+@@ -59,31 +59,33 @@
+ }
+ 
+ void Instruction::removeFromParent() {
+-  getParent()->getInstList().remove(this);
++  getParent()->getInstList().remove(getIterator());
+ }
+ 
+ void Instruction::eraseFromParent() {
+-  getParent()->getInstList().erase(this);
++  getParent()->getInstList().erase(getIterator());
+ }
+ 
+ /// insertBefore - Insert an unlinked instructions into a basic block
+ /// immediately before the specified instruction.
+ void Instruction::insertBefore(Instruction *InsertPos) {
+-  InsertPos->getParent()->getInstList().insert(InsertPos, this);
++  InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
+ }
+ 
+ /// insertAfter - Insert an unlinked instructions into a basic block
+ /// immediately after the specified instruction.
+ void Instruction::insertAfter(Instruction *InsertPos) {
+-  InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
++  InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
++                                                    this);
+ }
+ 
+ /// moveBefore - Unlink this instruction from its current basic block and
+ /// insert it into the basic block that MovePos lives in, right before
+ /// MovePos.
+ void Instruction::moveBefore(Instruction *MovePos) {
+-  MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
+-                                             this);
++  MovePos->getParent()->getInstList().splice(MovePos->getIterator(),
++                                             getParent()->getInstList(),
++                                             getIterator());
+ }
+ 
+ /// Set or clear the unsafe-algebra flag on this instruction, which must be an
+--- lib/IR/Module.cpp	2014-12-22 05:00:36.000000000 -0800
++++ lib/IR/Module.cpp	2015-11-27 09:30:00.064132788 -0800
+@@ -274,7 +274,7 @@
+ /// delete it.
+ void Module::eraseNamedMetadata(NamedMDNode *NMD) {
+   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
+-  NamedMDList.erase(NMD);
++  NamedMDList.erase(NMD->getIterator());
+ }
+ 
+ bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
+--- lib/IR/SymbolTableListTraitsImpl.h	2014-08-13 09:26:38.000000000 -0700
++++ lib/IR/SymbolTableListTraitsImpl.h	2015-11-24 12:37:36.693556920 -0800
+@@ -57,7 +57,7 @@
+     for (typename iplist<ValueSubClass>::iterator I = ItemList.begin();
+          I != ItemList.end(); ++I)
+       if (I->hasName())
+-        NewST->reinsertValue(I);
++        NewST->reinsertValue(&(*I));
+   }
+   
+ }
+--- lib/IR/TypeFinder.cpp	2014-12-09 10:38:53.000000000 -0800
++++ lib/IR/TypeFinder.cpp	2015-11-27 07:40:03.669762910 -0800
+@@ -53,7 +53,7 @@
+     // First incorporate the arguments.
+     for (Function::const_arg_iterator AI = FI->arg_begin(),
+            AE = FI->arg_end(); AI != AE; ++AI)
+-      incorporateValue(AI);
++      incorporateValue(&(*AI));
+ 
+     for (Function::const_iterator BB = FI->begin(), E = FI->end();
+          BB != E;++BB)
+@@ -82,7 +82,7 @@
+ 
+   for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
+          E = M.named_metadata_end(); I != E; ++I) {
+-    const NamedMDNode *NMD = I;
++    const NamedMDNode *NMD = &(*I);
+     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
+       incorporateMDNode(NMD->getOperand(i));
+   }
+--- lib/IR/Verifier.cpp	2015-01-12 19:46:47.000000000 -0800
++++ lib/IR/Verifier.cpp	2015-11-27 09:27:19.724275928 -0800
+@@ -81,7 +81,8 @@
+ static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(false));
+ 
+ namespace {
+-struct VerifierSupport {
++class VerifierSupport {
++public:
+   raw_ostream &OS;
+   const Module *M;
+ 
+@@ -89,11 +90,15 @@
+   bool Broken;
+ 
+   explicit VerifierSupport(raw_ostream &OS)
+-      : OS(OS), M(nullptr), Broken(false) {}
++    : OS(OS), M(nullptr), Broken(false) { }
++
++  ~VerifierSupport() { }
+ 
+-  void WriteValue(const Value *V) {
++private:
++  void Write(const Value *V) {
+     if (!V)
+       return;
++
+     if (isa<Instruction>(V)) {
+       OS << *V << '\n';
+     } else {
+@@ -102,81 +107,69 @@
+     }
+   }
+ 
+-  void WriteMetadata(const Metadata *MD) {
++  void Write(const Metadata *MD) {
+     if (!MD)
+       return;
++
+     MD->printAsOperand(OS, true, M);
+     OS << '\n';
+   }
+ 
+-  void WriteType(Type *T) {
++  void Write(Type *T) {
+     if (!T)
+       return;
++
+     OS << ' ' << *T;
+   }
+ 
+-  void WriteComdat(const Comdat *C) {
++  void Write(const Comdat *C) {
+     if (!C)
+       return;
++
+     OS << *C;
+   }
+ 
+-  // CheckFailed - A check failed, so print out the condition and the message
+-  // that failed.  This provides a nice place to put a breakpoint if you want
+-  // to see why something is not correct.
+-  void CheckFailed(const Twine &Message, const Value *V1 = nullptr,
+-                   const Value *V2 = nullptr, const Value *V3 = nullptr,
+-                   const Value *V4 = nullptr) {
+-    OS << Message.str() << "\n";
+-    WriteValue(V1);
+-    WriteValue(V2);
+-    WriteValue(V3);
+-    WriteValue(V4);
+-    Broken = true;
+-  }
++  void Write(const NamedMDNode *NMD) {
++    if (!NMD)
++      return;
+ 
+-  void CheckFailed(const Twine &Message, const Metadata *V1, const Metadata *V2,
+-                   const Metadata *V3 = nullptr, const Metadata *V4 = nullptr) {
+-    OS << Message.str() << "\n";
+-    WriteMetadata(V1);
+-    WriteMetadata(V2);
+-    WriteMetadata(V3);
+-    WriteMetadata(V4);
+-    Broken = true;
++    NMD->print(OS);
++    OS << "\n";
+   }
+ 
+-  void CheckFailed(const Twine &Message, const Metadata *V1,
+-                   const Value *V2 = nullptr) {
+-    OS << Message.str() << "\n";
+-    WriteMetadata(V1);
+-    WriteValue(V2);
+-    Broken = true;
++  template<class T>
++  void Write(const MDTupleTypedArrayWrapper<T> &MD) {
++    Write(MD.get());
+   }
+ 
+-  void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
+-                   const Value *V3 = nullptr) {
+-    OS << Message.str() << "\n";
+-    WriteValue(V1);
+-    WriteType(T2);
+-    WriteValue(V3);
+-    Broken = true;
++  template<class NodeTy> void Write(const ilist_iterator<NodeTy> &I) {
++    Write(&(*I));
+   }
+ 
+-  void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr,
+-                   Type *T3 = nullptr) {
+-    OS << Message.str() << "\n";
+-    WriteType(T1);
+-    WriteType(T2);
+-    WriteType(T3);
++  template <typename T1, typename... Ts>
++    void WriteTs(const T1 &V1, const Ts &... Vs) {
++      Write(V1);
++      WriteTs(Vs...);
++    }
++
++  template <typename... Ts> void WriteTs() {}
++
++public:
++  // CheckFailed - A check failed, so print out the condition and the message
++  // that failed.  This provides a nice place to put a breakpoint if you want
++  // to see why something is not correct.
++  void CheckFailed(const Twine &Message) {
++    OS << Message << '\n';
+     Broken = true;
+   }
+ 
+-  void CheckFailed(const Twine &Message, const Comdat *C) {
+-    OS << Message.str() << "\n";
+-    WriteComdat(C);
+-    Broken = true;
++  template <typename T1, typename... Ts>
++  void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
++    CheckFailed(Message);
++    WriteTs(V1, Vs...);
+   }
+ };
++
+ class Verifier : public InstVisitor<Verifier>, VerifierSupport {
+   friend class InstVisitor<Verifier>;
+ 
+@@ -204,8 +197,10 @@
+ 
+ public:
+   explicit Verifier(raw_ostream &OS = dbgs())
+-      : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
+-        SawFrameAllocate(false) {}
++    : InstVisitor<Verifier>(),
++    VerifierSupport(OS), Context(nullptr), DT(),
++    InstsInThisBlock(), MDNodes(),
++    PersonalityFn(nullptr), SawFrameAllocate(false) { }
+ 
+   bool verify(const Function &F) {
+     M = F.getParent();
+@@ -538,8 +533,6 @@
+ void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
+                                    const GlobalAlias &GA, const Constant &C) {
+   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
+-    Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA);
+-
+     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
+       Assert1(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
+ 
+--- lib/Linker/LinkModules.cpp	2015-02-24 18:00:21.000000000 -0800
++++ lib/Linker/LinkModules.cpp	2015-12-07 12:26:23.891323205 -0800
+@@ -1194,7 +1194,7 @@
+     DI->setName(Arg.getName());  // Copy the name over.
+ 
+     // Add a mapping to our mapping.
+-    ValueMap[&Arg] = DI;
++    ValueMap[&Arg] = &*DI;
+     ++DI;
+   }
+ 
+@@ -1518,7 +1518,7 @@
+   // initializers (which could refer to functions not yet mapped over).
+   for (Module::global_iterator I = SrcM->global_begin(),
+        E = SrcM->global_end(); I != E; ++I)
+-    if (linkGlobalValueProto(I))
++    if (linkGlobalValueProto(&*I))
+       return true;
+ 
+   // Link the functions together between the two modules, without doing function
+@@ -1527,13 +1527,13 @@
+   // all of the global values that may be referenced are available in our
+   // ValueMap.
+   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
+-    if (linkGlobalValueProto(I))
++    if (linkGlobalValueProto(&*I))
+       return true;
+ 
+   // If there were any aliases, link them now.
+   for (Module::alias_iterator I = SrcM->alias_begin(),
+        E = SrcM->alias_end(); I != E; ++I)
+-    if (linkGlobalValueProto(I))
++    if (linkGlobalValueProto(&*I))
+       return true;
+ 
+   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
+--- lib/MC/MCAssembler.cpp	2015-01-16 16:38:54.000000000 -0800
++++ lib/MC/MCAssembler.cpp	2015-12-07 12:37:47.486088108 -0800
+@@ -315,11 +315,13 @@
+     if (ExactMatch)
+       ++MI;
+   }
++
+   iterator IP;
+   if (MI == SubsectionFragmentMap.end())
+     IP = end();
+   else
+-    IP = MI->second;
++    IP = MI->second->getIterator();
++
+   if (!ExactMatch && Subsection != 0) {
+     // The GNU as documentation claims that subsections have an alignment of 4,
+     // although this appears not to be the case.
+@@ -892,7 +894,7 @@
+     // Create dummy fragments to eliminate any empty sections, this simplifies
+     // layout.
+     if (it->getFragmentList().empty())
+-      new MCDataFragment(it);
++      new MCDataFragment(&*it);
+ 
+     it->setOrdinal(SectionIndex++);
+   }
+@@ -1091,7 +1093,7 @@
+       break;
+     }
+     if (RelaxedFrag && !FirstRelaxedFragment)
+-      FirstRelaxedFragment = I;
++      FirstRelaxedFragment = &*I;
+   }
+   if (FirstRelaxedFragment) {
+     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
+--- lib/MC/MCMachOStreamer.cpp	2014-09-17 02:25:36.000000000 -0700
++++ lib/MC/MCMachOStreamer.cpp	2015-12-07 12:41:51.654959723 -0800
+@@ -444,7 +444,7 @@
+     MCSymbolData *CurrentAtom = nullptr;
+     for (MCSectionData::iterator it2 = it->begin(),
+            ie2 = it->end(); it2 != ie2; ++it2) {
+-      if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
++      if (MCSymbolData *SD = DefiningSymbolMap.lookup(&*it2))
+         CurrentAtom = SD;
+       it2->setAtom(CurrentAtom);
+     }
+--- lib/MC/MCObjectStreamer.cpp	2014-12-12 13:48:03.000000000 -0800
++++ lib/MC/MCObjectStreamer.cpp	2015-12-07 12:52:20.758780735 -0800
+@@ -83,7 +83,7 @@
+   assert(getCurrentSectionData() && "No current section!");
+ 
+   if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
+-    return std::prev(CurInsertionPoint);
++    return &*std::prev(CurInsertionPoint);
+ 
+   return nullptr;
+ }
+--- lib/MC/MachObjectWriter.cpp	2015-01-16 16:38:54.000000000 -0800
++++ lib/MC/MachObjectWriter.cpp	2015-12-07 13:28:29.179917460 -0800
+@@ -839,9 +839,9 @@
+   uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
+   for (MCAssembler::const_iterator it = Asm.begin(),
+          ie = Asm.end(); it != ie; ++it) {
+-    std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
++    std::vector<MachO::any_relocation_info> &Relocs = Relocations[&*it];
+     unsigned NumRelocs = Relocs.size();
+-    uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
++    uint64_t SectionStart = SectionDataStart + getSectionAddress(&*it);
+     WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
+     RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
+   }
+@@ -918,9 +918,9 @@
+   // Write the actual section data.
+   for (MCAssembler::const_iterator it = Asm.begin(),
+          ie = Asm.end(); it != ie; ++it) {
+-    Asm.writeSectionData(it, Layout);
++    Asm.writeSectionData(&*it, Layout);
+ 
+-    uint64_t Pad = getPaddingSize(it, Layout);
++    uint64_t Pad = getPaddingSize(&*it, Layout);
+     for (unsigned int i = 0; i < Pad; ++i)
+       Write8(0);
+   }
+@@ -933,7 +933,7 @@
+          ie = Asm.end(); it != ie; ++it) {
+     // Write the section relocation entries, in reverse order to match 'as'
+     // (approximately, the exact algorithm is more complicated than this).
+-    std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
++    std::vector<MachO::any_relocation_info> &Relocs = Relocations[&*it];
+     for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
+       Write32(Relocs[e - i - 1].r_word0);
+       Write32(Relocs[e - i - 1].r_word1);
+--- lib/MC/WinCOFFObjectWriter.cpp	2015-02-09 19:52:36.000000000 -0800
++++ lib/MC/WinCOFFObjectWriter.cpp	2015-12-07 14:55:13.070245970 -0800
+@@ -1015,7 +1015,7 @@
+         assert(OS.tell() == (*i)->Header.PointerToRawData &&
+                "Section::PointerToRawData is insane!");
+ 
+-        Asm.writeSectionData(j, Layout);
++        Asm.writeSectionData(&*j, Layout);
+       }
+ 
+       if ((*i)->Relocations.size() > 0) {
+--- lib/Support/YAMLParser.cpp	2014-08-30 09:48:02.000000000 -0700
++++ lib/Support/YAMLParser.cpp	2015-11-27 18:09:35.106421600 -0800
+@@ -393,9 +393,10 @@
+   bool isBlankOrBreak(StringRef::iterator Position);
+ 
+   /// @brief If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
+-  void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
+-                             , unsigned AtColumn
+-                             , bool IsRequired);
++  /// Please cut the comma placement bullshit. Thank you.
++  void saveSimpleKeyCandidate(TokenQueueT::iterator Tok,
++                              unsigned AtColumn,
++                              bool IsRequired);
+ 
+   /// @brief Remove simple keys that can no longer be valid simple keys.
+   ///
+@@ -742,7 +743,7 @@
+ 
+     removeStaleSimpleKeyCandidates();
+     SimpleKey SK;
+-    SK.Tok = TokenQueue.front();
++    SK.Tok = TokenQueue.begin();
+     if (std::find(SimpleKeys.begin(), SimpleKeys.end(), SK)
+         == SimpleKeys.end())
+       break;
+@@ -896,9 +897,9 @@
+   return false;
+ }
+ 
+-void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
+-                                    , unsigned AtColumn
+-                                    , bool IsRequired) {
++void Scanner::saveSimpleKeyCandidate(TokenQueueT::iterator Tok,
++                                     unsigned AtColumn,
++                                     bool IsRequired) {
+   if (IsSimpleKeyAllowed) {
+     SimpleKey SK;
+     SK.Tok = Tok;
+@@ -1078,7 +1079,7 @@
+   TokenQueue.push_back(T);
+ 
+   // [ and { may begin a simple key.
+-  saveSimpleKeyCandidate(TokenQueue.back(), Column - 1, false);
++  saveSimpleKeyCandidate(--TokenQueue.end(), Column - 1, false);
+ 
+   // And may also be followed by a simple key.
+   IsSimpleKeyAllowed = true;
+@@ -1241,7 +1242,7 @@
+   T.Range = StringRef(Start, Current - Start);
+   TokenQueue.push_back(T);
+ 
+-  saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
++  saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
+ 
+   IsSimpleKeyAllowed = false;
+ 
+@@ -1319,7 +1320,7 @@
+   TokenQueue.push_back(T);
+ 
+   // Plain scalars can be simple keys.
+-  saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
++  saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
+ 
+   IsSimpleKeyAllowed = false;
+ 
+@@ -1354,7 +1355,7 @@
+   TokenQueue.push_back(T);
+ 
+   // Alias and anchors can be simple keys.
+-  saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
++  saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
+ 
+   IsSimpleKeyAllowed = false;
+ 
+@@ -1418,7 +1419,7 @@
+   TokenQueue.push_back(T);
+ 
+   // Tags can be simple keys.
+-  saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
++  saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
+ 
+   IsSimpleKeyAllowed = false;
+ 
+--- lib/Target/Sparc/SparcAsmPrinter.cpp	2014-08-04 14:25:23.000000000 -0700
++++ lib/Target/Sparc/SparcAsmPrinter.cpp	2015-12-07 11:54:08.441400090 -0800
+@@ -267,11 +267,11 @@
+     LowerGETPCXAndEmitMCInsts(MI, getSubtargetInfo());
+     return;
+   }
+-  MachineBasicBlock::const_instr_iterator I = MI;
++  MachineBasicBlock::const_instr_iterator I = MI->getIterator();
+   MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
+   do {
+     MCInst TmpInst;
+-    LowerSparcMachineInstrToMCInst(I, TmpInst, *this);
++    LowerSparcMachineInstrToMCInst(&*I, TmpInst, *this);
+     EmitToStreamer(OutStreamer, TmpInst);
+   } while ((++I != E) && I->isInsideBundle()); // Delay slot check.
+ }
+--- lib/Target/Sparc/SparcISelLowering.cpp	2015-01-07 16:51:32.000000000 -0800
++++ lib/Target/Sparc/SparcISelLowering.cpp	2015-12-07 11:59:14.697760005 -0800
+@@ -2916,8 +2916,7 @@
+   // to set, the condition code register to branch on, the true/false values to
+   // select between, and a branch opcode to use.
+   const BasicBlock *LLVM_BB = BB->getBasicBlock();
+-  MachineFunction::iterator It = BB;
+-  ++It;
++  MachineFunction::iterator It = ++BB->getIterator();
+ 
+   //  thisMBB:
+   //  ...
+@@ -3003,7 +3002,7 @@
+     .addReg(AddrReg).addImm(0);
+ 
+   // Split the basic block MBB before MI and insert the loop block in the hole.
+-  MachineFunction::iterator MFI = MBB;
++  MachineFunction::iterator MFI = MBB->getIterator();
+   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
+   MachineFunction *MF = MBB->getParent();
+   MachineBasicBlock *LoopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
+--- lib/Target/Sparc/SparcTargetObjectFile.cpp	2014-04-24 22:30:21.000000000 -0700
++++ lib/Target/Sparc/SparcTargetObjectFile.cpp	2015-12-15 12:44:57.569902985 -0800
+@@ -15,6 +15,17 @@
+ 
+ using namespace llvm;
+ 
++void SparcELFTargetObjectFile::Initialize(MCContext &CTX,
++                                          const TargetMachine &TM) {
++  TargetLoweringObjectFile::Initialize(CTX, TM);
++  std::string OS = TM.getTargetTriple().str();
++
++  if (OS.find("solaris") != std::string::npos)
++    InitializeELF(true);
++  else
++    InitializeELF(TM.Options.UseInitArray);
++}
++
+ const MCExpr *SparcELFTargetObjectFile::getTTypeGlobalReference(
+     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
+     const TargetMachine &TM, MachineModuleInfo *MMI,
+--- lib/Target/Sparc/SparcTargetObjectFile.h	2014-08-13 09:26:38.000000000 -0700
++++ lib/Target/Sparc/SparcTargetObjectFile.h	2015-12-15 12:37:54.653197100 -0800
+@@ -19,11 +19,11 @@
+ 
+ class SparcELFTargetObjectFile : public TargetLoweringObjectFileELF {
+ public:
+-  SparcELFTargetObjectFile() :
+-    TargetLoweringObjectFileELF()
+-  {}
++  SparcELFTargetObjectFile() : TargetLoweringObjectFileELF() { }
+ 
+-  const MCExpr *
++  virtual void Initialize(MCContext &CTX, const TargetMachine &TM) override;
++
++  const MCExpr*
+   getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding,
+                           Mangler &Mang, const TargetMachine &TM,
+                           MachineModuleInfo *MMI,
+--- lib/Target/X86/X86FastISel.cpp	2015-01-05 23:35:50.000000000 -0800
++++ lib/Target/X86/X86FastISel.cpp	2016-01-23 08:58:44.000000000 -0800
+@@ -275,8 +275,8 @@
+     return false;
+ 
+   // Make sure nothing is in the way
+-  BasicBlock::const_iterator Start = I;
+-  BasicBlock::const_iterator End = II;
++  BasicBlock::const_iterator Start(I);
++  BasicBlock::const_iterator End(II);
+   for (auto Itr = std::prev(Start); Itr != End; --Itr) {
+     // We only expect extractvalue instructions between the intrinsic and the
+     // instruction to be selected.
+--- lib/Target/X86/X86FixupLEAs.cpp	2015-01-05 02:15:49.000000000 -0800
++++ lib/Target/X86/X86FixupLEAs.cpp	2016-01-23 08:57:43.000000000 -0800
+@@ -190,7 +190,7 @@
+ static inline bool getPreviousInstr(MachineBasicBlock::iterator &I,
+                                     MachineFunction::iterator MFI) {
+   if (I == MFI->begin()) {
+-    if (MFI->isPredecessor(MFI)) {
++    if (MFI->isPredecessor(&*MFI)) {
+       I = --MFI->end();
+       return true;
+     } else
+--- lib/Target/X86/X86FloatingPoint.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Target/X86/X86FloatingPoint.cpp	2016-01-23 09:03:48.000000000 -0800
+@@ -321,7 +321,7 @@
+   // Process the function in depth first order so that we process at least one
+   // of the predecessors for every reachable block in the function.
+   SmallPtrSet<MachineBasicBlock*, 8> Processed;
+-  MachineBasicBlock *Entry = MF.begin();
++  MachineBasicBlock *Entry = &MF.front();
+ 
+   bool Changed = false;
+   for (MachineBasicBlock *BB : depth_first_ext(Entry, Processed))
+@@ -329,9 +329,9 @@
+ 
+   // Process any unreachable blocks in arbitrary order now.
+   if (MF.size() != Processed.size())
+-    for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
+-      if (Processed.insert(BB).second)
+-        Changed |= processBasicBlock(MF, *BB);
++    for (MachineBasicBlock &BB : MF)
++      if (Processed.insert(&BB).second)
++        Changed |= processBasicBlock(MF, BB);
+ 
+   LiveBundles.clear();
+ 
+@@ -348,13 +348,12 @@
+   LiveBundles.resize(Bundles->getNumBundles());
+ 
+   // Gather the actual live-in masks for all MBBs.
+-  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
+-    MachineBasicBlock *MBB = I;
+-    const unsigned Mask = calcLiveInMask(MBB);
++  for (MachineBasicBlock &MBB : MF) {
++    const unsigned Mask = calcLiveInMask(&MBB);
+     if (!Mask)
+       continue;
+     // Update MBB ingoing bundle mask.
+-    LiveBundles[Bundles->getBundle(MBB->getNumber(), false)].Mask |= Mask;
++    LiveBundles[Bundles->getBundle(MBB.getNumber(), false)].Mask |= Mask;
+   }
+ }
+ 
+--- lib/Target/X86/X86ISelDAGToDAG.cpp	2015-01-05 20:23:53.000000000 -0800
++++ lib/Target/X86/X86ISelDAGToDAG.cpp	2016-01-23 09:08:15.000000000 -0800
+@@ -458,7 +458,8 @@
+ 
+   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
+        E = CurDAG->allnodes_end(); I != E; ) {
+-    SDNode *N = I++;  // Preincrement iterator to avoid invalidation issues.
++    SDNode *N = &*I;  // Preincrement iterator to avoid invalidation issues.
++    ++I;
+ 
+     if (OptLevel != CodeGenOpt::None &&
+         // Only does this when target favors doesn't favor register indirect
+@@ -586,7 +587,7 @@
+   // If this is main, emit special code for main.
+   if (const Function *Fn = MF->getFunction())
+     if (Fn->hasExternalLinkage() && Fn->getName() == "main")
+-      EmitSpecialCodeForMain(MF->begin(), MF->getFrameInfo());
++      EmitSpecialCodeForMain(&MF->front(), MF->getFrameInfo());
+ }
+ 
+ static bool isDispSafeForFrameIndex(int64_t Val) {
+@@ -778,7 +779,7 @@
+ static void InsertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
+   if (N.getNode()->getNodeId() == -1 ||
+       N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
+-    DAG.RepositionNode(Pos.getNode(), N.getNode());
++    DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
+     N.getNode()->setNodeId(Pos.getNode()->getNodeId());
+   }
+ }
+--- lib/Target/X86/X86ISelLowering.cpp	2015-05-01 21:17:29.000000000 -0700
++++ lib/Target/X86/X86ISelLowering.cpp	2016-01-23 10:03:26.000000000 -0800
+@@ -20363,8 +20363,7 @@
+   DebugLoc DL = MI->getDebugLoc();
+ 
+   const BasicBlock *BB = MBB->getBasicBlock();
+-  MachineFunction::iterator I = MBB;
+-  ++I;
++  MachineFunction::iterator I = ++MBB->getIterator();
+ 
+   // For the v = xbegin(), we generate
+   //
+@@ -20613,7 +20612,7 @@
+     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
+     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
+ 
+-    MachineFunction::iterator MBBIter = MBB;
++    MachineFunction::iterator MBBIter = ++MBB->getIterator();
+     ++MBBIter;
+ 
+     // Insert the new basic blocks
+@@ -20784,8 +20783,7 @@
+   // stores were performed.
+   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
+   MachineFunction *F = MBB->getParent();
+-  MachineFunction::iterator MBBIter = MBB;
+-  ++MBBIter;
++  MachineFunction::iterator MBBIter = ++MBB->getIterator();
+   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
+   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
+   F->insert(MBBIter, XMMSaveMBB);
+@@ -20893,8 +20891,7 @@
+   // destination vreg to set, the condition code register to branch on, the
+   // true/false values to select between, and a branch opcode to use.
+   const BasicBlock *LLVM_BB = BB->getBasicBlock();
+-  MachineFunction::iterator It = BB;
+-  ++It;
++  MachineFunction::iterator It = ++BB->getIterator();
+ 
+   //  thisMBB:
+   //  ...
+@@ -20997,8 +20994,7 @@
+     sizeVReg = MI->getOperand(1).getReg(),
+     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
+ 
+-  MachineFunction::iterator MBBIter = BB;
+-  ++MBBIter;
++  MachineFunction::iterator MBBIter = ++BB->getIterator();
+ 
+   MF->insert(MBBIter, bumpMBB);
+   MF->insert(MBBIter, mallocMBB);
+@@ -21168,8 +21164,7 @@
+   MachineRegisterInfo &MRI = MF->getRegInfo();
+ 
+   const BasicBlock *BB = MBB->getBasicBlock();
+-  MachineFunction::iterator I = MBB;
+-  ++I;
++  MachineFunction::iterator I = ++MBB->getIterator();
+ 
+   // Memory Reference
+   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
+--- lib/Target/X86/X86PadShortFunction.cpp	2014-08-04 14:25:23.000000000 -0700
++++ lib/Target/X86/X86PadShortFunction.cpp	2016-01-23 10:05:38.000000000 -0800
+@@ -110,7 +110,7 @@
+   // Search through basic blocks and mark the ones that have early returns
+   ReturnBBs.clear();
+   VisitedBBs.clear();
+-  findReturns(MF.begin());
++  findReturns(&MF.front());
+ 
+   bool MadeChange = false;
+ 
+--- lib/Transforms/IPO/ArgumentPromotion.cpp	2014-12-15 06:09:53.000000000 -0800
++++ lib/Transforms/IPO/ArgumentPromotion.cpp	2015-11-29 18:37:06.014532943 -0800
+@@ -214,7 +214,8 @@
+   SmallVector<Argument*, 16> PointerArgs;
+   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
+     if (I->getType()->isPointerTy())
+-      PointerArgs.push_back(I);
++      PointerArgs.push_back(&*I);
++
+   if (PointerArgs.empty()) return nullptr;
+ 
+   // Second check: make sure that all callers are direct callers.  We can't
+@@ -435,7 +436,8 @@
+ 
+   // First, iterate the entry block and mark loads of (geps of) arguments as
+   // safe.
+-  BasicBlock *EntryBlock = Arg->getParent()->begin();
++  BasicBlock *EntryBlock = &Arg->getParent()->front();
++
+   // Declare this here so we can reuse it
+   IndicesVector Indices;
+   for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
+@@ -620,14 +622,14 @@
+   unsigned ArgIndex = 1;
+   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
+        ++I, ++ArgIndex) {
+-    if (ByValArgsToTransform.count(I)) {
++    if (ByValArgsToTransform.count(&*I)) {
+       // Simple byval argument? Just add all the struct element types.
+       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
+       StructType *STy = cast<StructType>(AgTy);
+       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
+         Params.push_back(STy->getElementType(i));
+       ++NumByValArgsPromoted;
+-    } else if (!ArgsToPromote.count(I)) {
++    } else if (!ArgsToPromote.count(&*I)) {
+       // Unchanged argument
+       Params.push_back(I->getType());
+       AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
+@@ -645,7 +647,7 @@
+ 
+       // In this table, we will track which indices are loaded from the argument
+       // (where direct loads are tracked as no indices).
+-      ScalarizeTable &ArgIndices = ScalarizedElements[I];
++      ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
+       for (User *U : I->users()) {
+         Instruction *UI = cast<Instruction>(U);
+         assert(isa<LoadInst>(UI) || isa<GetElementPtrInst>(UI));
+@@ -667,7 +669,7 @@
+         else
+           // Take any load, we will use it only to update Alias Analysis
+           OrigLoad = cast<LoadInst>(UI->user_back());
+-        OriginalLoads[std::make_pair(I, Indices)] = OrigLoad;
++        OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
+       }
+ 
+       // Add a parameter to the function for each element passed in.
+@@ -712,19 +714,15 @@
+ 
+   DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
+         << "From: " << *F);
+-  
++
+   // Recompute the parameter attributes list based on the new arguments for
+   // the function.
+   NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
+   AttributesVec.clear();
+ 
+-  F->getParent()->getFunctionList().insert(F, NF);
++  F->getParent()->getFunctionList().insert(F->getIterator(), NF);
+   NF->takeName(F);
+ 
+-  // Get the alias analysis information that we need to update to reflect our
+-  // changes.
+-  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
+-
+   // Get the callgraph information that we need to update to reflect our
+   // changes.
+   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
+@@ -753,7 +751,7 @@
+     ArgIndex = 1;
+     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
+          I != E; ++I, ++AI, ++ArgIndex)
+-      if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
++      if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
+         Args.push_back(*AI);          // Unmodified argument
+ 
+         if (CallPAL.hasAttributes(ArgIndex)) {
+@@ -761,7 +759,7 @@
+           AttributesVec.
+             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
+         }
+-      } else if (ByValArgsToTransform.count(I)) {
++      } else if (ByValArgsToTransform.count(&*I)) {
+         // Emit a GEP and load for each element of the struct.
+         Type *AgTy = cast<PointerType>(I->getType())->getElementType();
+         StructType *STy = cast<StructType>(AgTy);
+@@ -777,14 +775,14 @@
+         }
+       } else if (!I->use_empty()) {
+         // Non-dead argument: insert GEPs and loads as appropriate.
+-        ScalarizeTable &ArgIndices = ScalarizedElements[I];
++        ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
+         // Store the Value* version of the indices in here, but declare it now
+         // for reuse.
+         std::vector<Value*> Ops;
+         for (ScalarizeTable::iterator SI = ArgIndices.begin(),
+                E = ArgIndices.end(); SI != E; ++SI) {
+           Value *V = *AI;
+-          LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, *SI)];
++          LoadInst *OrigLoad = OriginalLoads[std::make_pair(&*I, *SI)];
+           if (!SI->empty()) {
+             Ops.reserve(SI->size());
+             Type *ElTy = V->getType();
+@@ -793,7 +791,7 @@
+               // Use i32 to index structs, and i64 for others (pointers/arrays).
+               // This satisfies GEP constraints.
+               Type *IdxTy = (ElTy->isStructTy() ?
+-                    Type::getInt32Ty(F->getContext()) : 
++                    Type::getInt32Ty(F->getContext()) :
+                     Type::getInt64Ty(F->getContext()));
+               Ops.push_back(ConstantInt::get(IdxTy, *II));
+               // Keep track of the type we're currently indexing.
+@@ -802,8 +800,8 @@
+             // And create a GEP to extract those indices.
+             V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
+             Ops.clear();
+-            AA.copyValue(OrigLoad->getOperand(0), V);
+           }
++
+           // Since we're replacing a load make sure we take the alignment
+           // of the previous load.
+           LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
+@@ -814,7 +812,6 @@
+           newLoad->setAAMetadata(AAInfo);
+ 
+           Args.push_back(newLoad);
+-          AA.copyValue(OrigLoad, Args.back());
+         }
+       }
+ 
+@@ -852,10 +849,6 @@
+     Args.clear();
+     AttributesVec.clear();
+ 
+-    // Update the alias analysis implementation to know that we are replacing
+-    // the old call with a new one.
+-    AA.replaceWithNewValue(Call, New);
+-
+     // Update the callgraph to know that the callsite has been transformed.
+     CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
+     CalleeNode->replaceCallEdge(Call, New, NF_CGN);
+@@ -877,23 +870,21 @@
+ 
+   // Loop over the argument list, transferring uses of the old arguments over to
+   // the new arguments, also transferring over the names as well.
+-  //
+   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
+        I2 = NF->arg_begin(); I != E; ++I) {
+-    if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
++    if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
+       // If this is an unmodified argument, move the name and users over to the
+       // new version.
+-      I->replaceAllUsesWith(I2);
+-      I2->takeName(I);
+-      AA.replaceWithNewValue(I, I2);
++      I->replaceAllUsesWith(&*I2);
++      I2->takeName(&*I);
+       ++I2;
+       continue;
+     }
+ 
+-    if (ByValArgsToTransform.count(I)) {
++    if (ByValArgsToTransform.count(&*I)) {
+       // In the callee, we create an alloca, and store each of the new incoming
+       // arguments into the alloca.
+-      Instruction *InsertPt = NF->begin()->begin();
++      Instruction *InsertPt = &NF->begin()->front();
+ 
+       // Just add all the struct element types.
+       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
+@@ -904,18 +895,17 @@
+ 
+       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
+         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
+-        Value *Idx = 
++        Value *Idx =
+           GetElementPtrInst::Create(TheAlloca, Idxs,
+-                                    TheAlloca->getName()+"."+Twine(i), 
++                                    TheAlloca->getName() + "." + Twine(i),
+                                     InsertPt);
+-        I2->setName(I->getName()+"."+Twine(i));
+-        new StoreInst(I2++, Idx, InsertPt);
++        I2->setName(I->getName() + "." +Twine(i));
++        new StoreInst(&*I2++, Idx, InsertPt);
+       }
+ 
+       // Anything that used the arg should now use the alloca.
+       I->replaceAllUsesWith(TheAlloca);
+-      TheAlloca->takeName(I);
+-      AA.replaceWithNewValue(I, TheAlloca);
++      TheAlloca->takeName(&*I);
+ 
+       // If the alloca is used in a call, we must clear the tail flag since
+       // the callee now uses an alloca from the caller.
+@@ -928,23 +918,20 @@
+       continue;
+     }
+ 
+-    if (I->use_empty()) {
+-      AA.deleteValue(I);
++    if (I->use_empty())
+       continue;
+-    }
+ 
+     // Otherwise, if we promoted this argument, then all users are load
+     // instructions (or GEPs with only load users), and all loads should be
+     // using the new argument that we added.
+-    ScalarizeTable &ArgIndices = ScalarizedElements[I];
++    ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
+ 
+     while (!I->use_empty()) {
+       if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
+         assert(ArgIndices.begin()->empty() &&
+                "Load element should sort to front!");
+         I2->setName(I->getName()+".val");
+-        LI->replaceAllUsesWith(I2);
+-        AA.replaceWithNewValue(LI, I2);
++        LI->replaceAllUsesWith(&*I2);
+         LI->eraseFromParent();
+         DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
+               << "' in function '" << F->getName() << "'\n");
+@@ -980,11 +967,10 @@
+         // the argument specified by ArgNo.
+         while (!GEP->use_empty()) {
+           LoadInst *L = cast<LoadInst>(GEP->user_back());
+-          L->replaceAllUsesWith(TheArg);
+-          AA.replaceWithNewValue(L, TheArg);
++          L->replaceAllUsesWith(&*TheArg);
+           L->eraseFromParent();
+         }
+-        AA.deleteValue(GEP);
++
+         GEP->eraseFromParent();
+       }
+     }
+@@ -993,12 +979,9 @@
+     std::advance(I2, ArgIndices.size());
+   }
+ 
+-  // Tell the alias analysis that the old function is about to disappear.
+-  AA.replaceWithNewValue(F, NF);
+ 
+-  
+   NF_CGN->stealCalledFunctionsFrom(CG[F]);
+-  
++
+   // Now that the old function is dead, delete it.  If there is a dangling
+   // reference to the CallgraphNode, just leave the dead function around for
+   // someone else to nuke.
+@@ -1007,7 +990,7 @@
+     delete CG.removeFunctionFromModule(CGN);
+   else
+     F->setLinkage(Function::ExternalLinkage);
+-  
++
+   return NF_CGN;
+ }
+ 
+--- lib/Transforms/IPO/ConstantMerge.cpp	2014-08-20 22:55:13.000000000 -0700
++++ lib/Transforms/IPO/ConstantMerge.cpp	2015-11-29 18:38:45.961868975 -0800
+@@ -130,7 +130,8 @@
+     // First: Find the canonical constants others will be merged with.
+     for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
+          GVI != E; ) {
+-      GlobalVariable *GV = GVI++;
++      GlobalVariable *GV = &*GVI;
++      ++GVI;
+ 
+       // If this GV is dead, remove it.
+       GV->removeDeadConstantUsers();
+@@ -172,7 +173,8 @@
+     // invalidating the Constant* pointers in CMap.
+     for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
+          GVI != E; ) {
+-      GlobalVariable *GV = GVI++;
++      GlobalVariable *GV = &*GVI;
++      ++GVI;
+ 
+       // Only process constants with initializers in the default address space.
+       if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
+--- lib/Transforms/IPO/DeadArgumentElimination.cpp	2014-10-07 08:10:23.000000000 -0700
++++ lib/Transforms/IPO/DeadArgumentElimination.cpp	2015-11-29 18:53:45.446590015 -0800
+@@ -229,7 +229,7 @@
+   // Create the new function body and insert it into the module...
+   Function *NF = Function::Create(NFTy, Fn.getLinkage());
+   NF->copyAttributesFrom(&Fn);
+-  Fn.getParent()->getFunctionList().insert(&Fn, NF);
++  Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF);
+   NF->takeName(&Fn);
+ 
+   // Loop over all of the callers of the function, transforming the call sites
+@@ -296,8 +296,8 @@
+   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
+        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
+     // Move the name and users over to the new version.
+-    I->replaceAllUsesWith(I2);
+-    I2->takeName(I);
++    I->replaceAllUsesWith(&*I2);
++    I2->takeName(&*I);
+   }
+ 
+   // Patch the pointer to LLVM function in debug info descriptor.
+@@ -351,12 +351,10 @@
+     return false;
+ 
+   SmallVector<unsigned, 8> UnusedArgs;
+-  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); 
+-       I != E; ++I) {
+-    Argument *Arg = I;
+ 
+-    if (Arg->use_empty() && !Arg->hasByValOrInAllocaAttr())
+-      UnusedArgs.push_back(Arg->getArgNo());
++  for (Argument &Arg : Fn.args()) {
++    if (Arg.use_empty() && !Arg.hasByValOrInAllocaAttr())
++      UnusedArgs.push_back(Arg.getArgNo());
+   }
+ 
+   if (UnusedArgs.empty())
+@@ -617,7 +615,7 @@
+     } else {
+       // See what the effect of this use is (recording any uses that cause
+       // MaybeLive in MaybeLiveArgUses). 
+-      Result = SurveyUses(AI, MaybeLiveArgUses);
++      Result = SurveyUses(&*AI, MaybeLiveArgUses);
+     }
+ 
+     // Mark the result.
+@@ -862,7 +860,7 @@
+   NF->setAttributes(NewPAL);
+   // Insert the new function before the old function, so we won't be processing
+   // it again.
+-  F->getParent()->getFunctionList().insert(F, NF);
++  F->getParent()->getFunctionList().insert(F->getIterator(), NF);
+   NF->takeName(F);
+ 
+   // Loop over all of the callers of the function, transforming the call sites
+@@ -966,7 +964,7 @@
+         if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
+           BasicBlock::iterator IP = II->getNormalDest()->begin();
+           while (isa<PHINode>(IP)) ++IP;
+-          InsertPt = IP;
++          InsertPt = &*IP;
+         }
+ 
+         // We used to return a struct. Instead of doing smart stuff with all the
+@@ -1014,8 +1012,8 @@
+     if (ArgAlive[i]) {
+       // If this is a live argument, move the name and users over to the new
+       // version.
+-      I->replaceAllUsesWith(I2);
+-      I2->takeName(I);
++      I->replaceAllUsesWith(&*I2);
++      I2->takeName(&*I);
+       ++I2;
+     } else {
+       // If this argument is dead, replace any uses of it with null constants
+@@ -1107,7 +1105,8 @@
+   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
+     // Increment now, because the function will probably get removed (ie.
+     // replaced by a new one).
+-    Function *F = I++;
++    Function *F = &*I;
++    ++I;
+     Changed |= RemoveDeadStuffFromFunction(F);
+   }
+ 
+--- lib/Transforms/IPO/ExtractGV.cpp	2014-10-28 04:54:52.000000000 -0700
++++ lib/Transforms/IPO/ExtractGV.cpp	2015-11-29 18:57:50.191073612 -0800
+@@ -83,7 +83,7 @@
+       for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+            I != E; ++I) {
+         bool Delete =
+-          deleteStuff == (bool)Named.count(I) && !I->isDeclaration();
++          deleteStuff == (bool) Named.count(&*I) && !I->isDeclaration();
+         if (!Delete) {
+           if (I->hasAvailableExternallyLinkage())
+             continue;
+@@ -100,7 +100,7 @@
+       // Visit the Functions.
+       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
+         bool Delete =
+-          deleteStuff == (bool)Named.count(I) && !I->isDeclaration();
++          deleteStuff == (bool) Named.count(&*I) && !I->isDeclaration();
+         if (!Delete) {
+           if (I->hasAvailableExternallyLinkage())
+             continue;
+@@ -108,8 +108,10 @@
+ 
+         makeVisible(*I, Delete);
+ 
+-        if (Delete)
++        if (Delete) {
+           I->deleteBody();
++          I->setComdat(nullptr);
++        }
+       }
+ 
+       // Visit the Aliases.
+@@ -118,7 +120,7 @@
+         Module::alias_iterator CurI = I;
+         ++I;
+ 
+-        bool Delete = deleteStuff == (bool)Named.count(CurI);
++        bool Delete = deleteStuff == (bool) Named.count(&*CurI);
+         makeVisible(*CurI, Delete);
+ 
+         if (Delete) {
+@@ -136,8 +138,9 @@
+                                  nullptr, CurI->getName());
+ 
+           }
++
+           CurI->replaceAllUsesWith(Declaration);
+-          delete CurI;
++          delete &*CurI;
+         }
+       }
+ 
+--- lib/Transforms/IPO/FunctionAttrs.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/IPO/FunctionAttrs.cpp	2015-11-29 19:01:30.757096968 -0800
+@@ -365,7 +365,7 @@
+           return true;
+         }
+         if (PI == U) {
+-          Uses.push_back(AI);
++          Uses.push_back(&*AI);
+           Found = true;
+           break;
+         }
+@@ -489,15 +489,19 @@
+                    "More params than args in non-varargs call.");
+             return Attribute::None;
+           }
++
+           Captures &= !CS.doesNotCapture(A - B);
+-          if (SCCNodes.count(AI))
++          if (SCCNodes.count(&*AI))
+             continue;
++
+           if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
+             return Attribute::None;
++
+           if (!CS.doesNotAccessMemory(A - B))
+             IsRead = true;
+         }
+       }
++
+       AddUsersToWorklistIfCapturing();
+       break;
+     }
+@@ -574,7 +578,7 @@
+       bool HasNonLocalUses = false;
+       if (!A->hasNoCaptureAttr()) {
+         ArgumentUsesTracker Tracker(SCCNodes);
+-        PointerMayBeCaptured(A, &Tracker);
++        PointerMayBeCaptured(&*A, &Tracker);
+         if (!Tracker.Captured) {
+           if (Tracker.Uses.empty()) {
+             // If it's trivially not captured, mark it nocapture now.
+@@ -585,7 +589,7 @@
+             // If it's not trivially captured and not trivially not captured,
+             // then it must be calling into another function in our SCC. Save
+             // its particulars for Argument-SCC analysis later.
+-            ArgumentGraphNode *Node = AG[A];
++            ArgumentGraphNode *Node = AG[&*A];
+             for (SmallVectorImpl<Argument*>::iterator UI = Tracker.Uses.begin(),
+                      UE = Tracker.Uses.end(); UI != UE; ++UI) {
+               Node->Uses.push_back(AG[*UI]);
+@@ -602,8 +606,8 @@
+         // will be dependent on the iteration order through the functions in the
+         // SCC.
+         SmallPtrSet<Argument*, 8> Self;
+-        Self.insert(A);
+-        Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
++        Self.insert(&*A);
++        Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
+         if (R != Attribute::None) {
+           AttrBuilder B;
+           B.addAttribute(R);
+--- lib/Transforms/IPO/GlobalDCE.cpp	2014-12-02 18:08:38.000000000 -0800
++++ lib/Transforms/IPO/GlobalDCE.cpp	2015-11-29 19:08:57.774680942 -0800
+@@ -84,7 +84,7 @@
+     // Functions with external linkage are needed if they have a body
+     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
+       if (!I->isDiscardableIfUnused())
+-        GlobalIsNeeded(I);
++        GlobalIsNeeded(&*I);
+     }
+   }
+ 
+@@ -95,7 +95,7 @@
+     // initializer.
+     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
+       if (!I->isDiscardableIfUnused())
+-        GlobalIsNeeded(I);
++        GlobalIsNeeded(&*I);
+     }
+   }
+ 
+@@ -104,7 +104,7 @@
+     Changed |= RemoveUnusedGlobalValue(*I);
+     // Externally visible aliases are needed.
+     if (!I->isDiscardableIfUnused()) {
+-      GlobalIsNeeded(I);
++      GlobalIsNeeded(&*I);
+     }
+   }
+ 
+@@ -116,8 +116,8 @@
+   std::vector<GlobalVariable*> DeadGlobalVars;   // Keep track of dead globals
+   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+        I != E; ++I)
+-    if (!AliveGlobals.count(I)) {
+-      DeadGlobalVars.push_back(I);         // Keep track of dead globals
++    if (!AliveGlobals.count(&*I)) {
++      DeadGlobalVars.push_back(&*I);         // Keep track of dead globals
+       if (I->hasInitializer()) {
+         Constant *Init = I->getInitializer();
+         I->setInitializer(nullptr);
+@@ -129,8 +129,8 @@
+   // The second pass drops the bodies of functions which are dead...
+   std::vector<Function*> DeadFunctions;
+   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+-    if (!AliveGlobals.count(I)) {
+-      DeadFunctions.push_back(I);         // Keep track of dead globals
++    if (!AliveGlobals.count(&*I)) {
++      DeadFunctions.push_back(&*I);         // Keep track of dead globals
+       if (!I->isDeclaration())
+         I->deleteBody();
+     }
+@@ -139,8 +139,8 @@
+   std::vector<GlobalAlias*> DeadAliases;
+   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
+        ++I)
+-    if (!AliveGlobals.count(I)) {
+-      DeadAliases.push_back(I);
++    if (!AliveGlobals.count(&*I)) {
++      DeadAliases.push_back(&*I);
+       I->setAliasee(nullptr);
+     }
+ 
+--- lib/Transforms/IPO/GlobalOpt.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/IPO/GlobalOpt.cpp	2015-11-29 19:20:51.649538813 -0800
+@@ -493,12 +493,13 @@
+     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
+       Constant *In = Init->getAggregateElement(i);
+       assert(In && "Couldn't get element of initializer?");
+-      GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
+-                                               GlobalVariable::InternalLinkage,
+-                                               In, GV->getName()+"."+Twine(i),
+-                                               GV->getThreadLocalMode(),
+-                                              GV->getType()->getAddressSpace());
+-      Globals.insert(GV, NGV);
++      GlobalVariable *NGV =
++        new GlobalVariable(STy->getElementType(i), false,
++                           GlobalVariable::InternalLinkage,
++                           In, GV->getName()+"."+Twine(i),
++                           GV->getThreadLocalMode(),
++                           GV->getType()->getAddressSpace());
++      Globals.insert(GV->getIterator(), NGV);
+       NewGlobals.push_back(NGV);
+ 
+       // Calculate the known alignment of the field.  If theinal aggregate
+@@ -526,12 +527,13 @@
+       Constant *In = Init->getAggregateElement(i);
+       assert(In && "Couldn't get element of initializer?");
+ 
+-      GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
+-                                               GlobalVariable::InternalLinkage,
+-                                               In, GV->getName()+"."+Twine(i),
+-                                               GV->getThreadLocalMode(),
+-                                              GV->getType()->getAddressSpace());
+-      Globals.insert(GV, NGV);
++      GlobalVariable *NGV =
++        new GlobalVariable(STy->getElementType(), false,
++                           GlobalVariable::InternalLinkage,
++                           In, GV->getName()+"."+Twine(i),
++                           GV->getThreadLocalMode(),
++                           GV->getType()->getAddressSpace());
++      Globals.insert(GV->getIterator(), NGV);
+       NewGlobals.push_back(NGV);
+ 
+       // Calculate the known alignment of the field.  If theinal aggregate
+@@ -936,7 +938,7 @@
+       cast<StoreInst>(InitBool->user_back())->eraseFromParent();
+     delete InitBool;
+   } else
+-    GV->getParent()->getGlobalList().insert(GV, InitBool);
++    GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool);
+ 
+   // Now the GV is dead, nuke it and the malloc..
+   GV->eraseFromParent();
+@@ -1338,7 +1340,8 @@
+ 
+   // Split the basic block at the old malloc.
+   BasicBlock *OrigBB = CI->getParent();
+-  BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
++  BasicBlock *ContBB =
++    OrigBB->splitBasicBlock(CI->getIterator(), "malloc_cont");
+ 
+   // Create the block to check the first condition.  Put all these blocks at the
+   // end of the function as they are unlikely to be executed.
+@@ -1505,7 +1508,8 @@
+     // (2048 bytes currently), as we don't want to introduce a 16M global or
+     // something.
+     if (NElements->getZExtValue() * DL->getTypeAllocSize(AllocTy) < 2048) {
+-      GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI);
++      GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy,
++                                          NElements, DL, TLI)->getIterator();
+       return true;
+     }
+ 
+@@ -1551,7 +1555,7 @@
+     }
+ 
+     GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true),
+-                               DL, TLI);
++                               DL, TLI)->getIterator();
+     return true;
+   }
+ 
+@@ -1626,7 +1630,7 @@
+                                              GV->getName()+".b",
+                                              GV->getThreadLocalMode(),
+                                              GV->getType()->getAddressSpace());
+-  GV->getParent()->getGlobalList().insert(GV, NewGV);
++  GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV);
+ 
+   Constant *InitVal = GV->getInitializer();
+   assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
+@@ -1807,7 +1811,7 @@
+     if (DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>()) {
+       const DataLayout &DL = DLP->getDataLayout();
+       if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
+-        GVI = FirstNewGV;  // Don't skip the newly produced globals!
++        GVI = FirstNewGV->getIterator();  // Don't skip the newly produced globals!
+         return true;
+       }
+     }
+@@ -1830,7 +1834,7 @@
+           GV->eraseFromParent();
+           ++NumDeleted;
+         } else {
+-          GVI = GV;
++          GVI = GV->getIterator();
+         }
+         ++NumSubstitute;
+         return true;
+@@ -1905,7 +1909,7 @@
+   bool Changed = false;
+   // Optimize functions.
+   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
+-    Function *F = FI++;
++    Function *F = &*FI++;
+     // Functions without names cannot be referenced outside this module.
+     if (!F->hasName() && !F->isDeclaration() && !F->hasLocalLinkage())
+       F->setLinkage(GlobalValue::InternalLinkage);
+@@ -1947,7 +1951,7 @@
+ 
+   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
+        GVI != E; ) {
+-    GlobalVariable *GV = GVI++;
++    GlobalVariable *GV = &*GVI++;
+     // Global variables without names cannot be referenced outside this module.
+     if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
+       GV->setLinkage(GlobalValue::InternalLinkage);
+@@ -2446,7 +2450,7 @@
+       InstResult = AllocaTmps.back().get();
+       DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
+     } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
+-      CallSite CS(CurInst);
++      CallSite CS(&*CurInst);
+ 
+       // Debug info can safely be ignored here.
+       if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
+@@ -2608,7 +2612,7 @@
+       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
+         InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
+ 
+-      setVal(CurInst, InstResult);
++      setVal(&*CurInst, InstResult);
+     }
+ 
+     // If we just processed an invoke, we finished evaluating the block.
+@@ -2639,7 +2643,7 @@
+   unsigned ArgNo = 0;
+   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
+        ++AI, ++ArgNo)
+-    setVal(AI, ActualArgs[ArgNo]);
++    setVal(&*AI, ActualArgs[ArgNo]);
+ 
+   // ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
+   // we can only evaluate any one basic block at most once.  This set keeps
+@@ -2647,7 +2651,7 @@
+   SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
+ 
+   // CurBB - The current basic block we're evaluating.
+-  BasicBlock *CurBB = F->begin();
++  BasicBlock *CurBB = &F->front();
+ 
+   BasicBlock::iterator CurInst = CurBB->begin();
+ 
+@@ -2897,15 +2901,15 @@
+ 
+     if (RenameTarget) {
+       // Give the aliasee the name, linkage and other attributes of the alias.
+-      Target->takeName(J);
++      Target->takeName(&*J);
+       Target->setLinkage(J->getLinkage());
+       Target->setVisibility(J->getVisibility());
+       Target->setDLLStorageClass(J->getDLLStorageClass());
+ 
+-      if (Used.usedErase(J))
++      if (Used.usedErase(&*J))
+         Used.usedInsert(Target);
+ 
+-      if (Used.compilerUsedErase(J))
++      if (Used.compilerUsedErase(&*J))
+         Used.compilerUsedInsert(Target);
+     } else if (mayHaveOtherReferences(*J, Used))
+       continue;
+--- lib/Transforms/IPO/Internalize.cpp	2014-08-24 16:23:06.000000000 -0700
++++ lib/Transforms/IPO/Internalize.cpp	2015-11-29 19:22:14.785278600 -0800
+@@ -162,7 +162,7 @@
+ 
+     if (ExternalNode)
+       // Remove a callgraph edge from the external node to this function.
+-      ExternalNode->removeOneAbstractEdgeTo((*CG)[I]);
++      ExternalNode->removeOneAbstractEdgeTo((*CG)[&*I]);
+ 
+     Changed = true;
+     ++NumFunctions;
+--- lib/Transforms/IPO/LoopExtractor.cpp	2014-07-21 10:06:51.000000000 -0700
++++ lib/Transforms/IPO/LoopExtractor.cpp	2015-11-29 19:23:56.327652268 -0800
+@@ -259,7 +259,7 @@
+     // Figure out which index the basic block is in its function.
+     Function::iterator BBI = MF->begin();
+     std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
+-    TranslatedBlocksToNotExtract.insert(BBI);
++    TranslatedBlocksToNotExtract.insert(&*BBI);
+   }
+ 
+   while (!BlocksToNotExtractByName.empty()) {
+@@ -278,7 +278,7 @@
+         BasicBlock &BB = *BI;
+         if (BB.getName() != BlockName) continue;
+ 
+-        TranslatedBlocksToNotExtract.insert(BI);
++        TranslatedBlocksToNotExtract.insert(&*BI);
+       }
+     }
+ 
+@@ -291,8 +291,8 @@
+   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
+     SplitLandingPadPreds(&*F);
+     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
+-      if (!TranslatedBlocksToNotExtract.count(BB))
+-        BlocksToExtract.push_back(BB);
++      if (!TranslatedBlocksToNotExtract.count(&*BB))
++        BlocksToExtract.push_back(&*BB);
+   }
+ 
+   for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i) {
+--- lib/Transforms/IPO/MergeFunctions.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/IPO/MergeFunctions.cpp	2015-11-29 19:32:19.065098905 -0800
+@@ -929,7 +929,7 @@
+   BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
+ 
+   do {
+-    if (int Res = cmpValues(InstL, InstR))
++    if (int Res = cmpValues(&*InstL, &*InstR))
+       return Res;
+ 
+     const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
+@@ -947,7 +947,7 @@
+       if (int Res = cmpGEPs(GEPL, GEPR))
+         return Res;
+     } else {
+-      if (int Res = cmpOperations(InstL, InstR))
++      if (int Res = cmpOperations(&*InstL, &*InstR))
+         return Res;
+       assert(InstL->getNumOperands() == InstR->getNumOperands());
+ 
+@@ -1019,7 +1019,7 @@
+                                     ArgRI = FnR->arg_begin(),
+                                     ArgLE = FnL->arg_end();
+        ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
+-    if (cmpValues(ArgLI, ArgRI) != 0)
++    if (cmpValues(&*ArgLI, &*ArgRI) != 0)
+       llvm_unreachable("Arguments repeat!");
+   }
+ 
+@@ -1217,7 +1217,7 @@
+ 
+   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
+     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
+-      Deferred.push_back(WeakVH(I));
++      Deferred.push_back(WeakVH(&*I));
+   }
+ 
+   do {
+@@ -1342,7 +1342,7 @@
+   FunctionType *FFTy = F->getFunctionType();
+   for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
+        AI != AE; ++AI) {
+-    Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
++    Args.push_back(createCast(Builder, &*AI, FFTy->getParamType(i)));
+     ++i;
+   }
+ 
+--- lib/Transforms/IPO/PartialInlining.cpp	2014-07-21 10:06:51.000000000 -0700
++++ lib/Transforms/IPO/PartialInlining.cpp	2015-11-30 05:52:13.004988742 -0800
+@@ -50,7 +50,7 @@
+ 
+ Function* PartialInliner::unswitchFunction(Function* F) {
+   // First, verify that this function is an unswitching candidate...
+-  BasicBlock* entryBlock = F->begin();
++  BasicBlock* entryBlock = &F->front();
+   BranchInst *BR = dyn_cast<BranchInst>(entryBlock->getTerminator());
+   if (!BR || BR->isUnconditional())
+     return nullptr;
+@@ -88,10 +88,10 @@
+   // sequence of PHIs, some of which will go in the extracted region, and some
+   // of which will go outside.
+   BasicBlock* preReturn = newReturnBlock;
+-  newReturnBlock = newReturnBlock->splitBasicBlock(
+-                                              newReturnBlock->getFirstNonPHI());
++  newReturnBlock =
++    newReturnBlock->splitBasicBlock(newReturnBlock->getFirstNonPHI()->getIterator());
+   BasicBlock::iterator I = preReturn->begin();
+-  BasicBlock::iterator Ins = newReturnBlock->begin();
++  Instruction *Ins = &newReturnBlock->front();
+   while (I != preReturn->end()) {
+     PHINode* OldPhi = dyn_cast<PHINode>(I);
+     if (!OldPhi) break;
+@@ -100,7 +100,7 @@
+     OldPhi->replaceAllUsesWith(retPhi);
+     Ins = newReturnBlock->getFirstNonPHI();
+     
+-    retPhi->addIncoming(I, preReturn);
++    retPhi->addIncoming(&*I, preReturn);
+     retPhi->addIncoming(OldPhi->getIncomingValueForBlock(newEntryBlock),
+                         newEntryBlock);
+     OldPhi->removeIncomingValue(newEntryBlock);
+@@ -116,7 +116,7 @@
+        FE = duplicateFunction->end(); FI != FE; ++FI)
+     if (&*FI != newEntryBlock && &*FI != newReturnBlock &&
+         &*FI != newNonReturnBlock)
+-      toExtract.push_back(FI);
++      toExtract.push_back(&*FI);
+       
+   // The CodeExtractor needs a dominator tree.
+   DominatorTree DT;
+--- lib/Transforms/IPO/PruneEH.cpp	2015-01-12 19:46:47.000000000 -0800
++++ lib/Transforms/IPO/PruneEH.cpp	2015-11-30 05:53:43.868963013 -0800
+@@ -218,7 +218,7 @@
+ 
+           // Remove the uncond branch and add an unreachable.
+           BB->getInstList().pop_back();
+-          new UnreachableInst(BB->getContext(), BB);
++          new UnreachableInst(BB->getContext(), &*BB);
+ 
+           DeleteBasicBlock(New);  // Delete the new BB.
+           MadeChange = true;
+--- lib/Transforms/IPO/StripDeadPrototypes.cpp	2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/IPO/StripDeadPrototypes.cpp	2015-11-30 05:54:57.769272028 -0800
+@@ -47,7 +47,9 @@
+   
+   // Erase dead function prototypes.
+   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
+-    Function *F = I++;
++    Function *F = &*I;
++    ++I;
++
+     // Function must be a prototype and unused.
+     if (F->isDeclaration() && F->use_empty()) {
+       F->eraseFromParent();
+@@ -59,7 +61,9 @@
+   // Erase dead global var prototypes.
+   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+        I != E; ) {
+-    GlobalVariable *GV = I++;
++    GlobalVariable *GV = &*I;
++    ++I;
++
+     // Global must be a prototype and unused.
+     if (GV->isDeclaration() && GV->use_empty())
+       GV->eraseFromParent();
+--- lib/Transforms/IPO/StripSymbols.cpp	2014-12-09 10:38:53.000000000 -0800
++++ lib/Transforms/IPO/StripSymbols.cpp	2015-11-30 06:01:52.193630900 -0800
+@@ -211,13 +211,13 @@
+ 
+   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+        I != E; ++I) {
+-    if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
++    if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
+       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
+         I->setName("");     // Internal symbols can't participate in linkage
+   }
+ 
+   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
+-    if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
++    if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
+       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
+         I->setName("");     // Internal symbols can't participate in linkage
+     StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
+--- lib/Transforms/InstCombine/InstCombineCalls.cpp	2015-01-22 11:40:47.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombineCalls.cpp	2015-11-30 06:53:40.815329138 -0800
+@@ -1010,15 +1010,14 @@
+     // happen when variable allocas are DCE'd.
+     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
+       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
+-        BasicBlock::iterator BI = SS;
+-        if (&*++BI == II)
++        if (&*++SS->getIterator() == II)
+           return EraseInstFromFunction(CI);
+       }
+     }
+ 
+     // Scan down this block to see if there is another stack restore in the
+     // same block without an intervening call/alloca.
+-    BasicBlock::iterator BI = II;
++    BasicBlock::iterator BI(II);
+     TerminatorInst *TI = II->getParent()->getTerminator();
+     bool CannotRemove = false;
+     for (++BI; &*BI != TI; ++BI) {
+@@ -1235,9 +1234,9 @@
+                                                Value *TrampMem) {
+   // Visit all the previous instructions in the basic block, and try to find a
+   // init.trampoline which has a direct path to the adjust.trampoline.
+-  for (BasicBlock::iterator I = AdjustTramp,
++  for (BasicBlock::iterator I = AdjustTramp->getIterator(),
+        E = AdjustTramp->getParent()->begin(); I != E; ) {
+-    Instruction *Inst = --I;
++    Instruction *Inst = &*--I;
+     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
+       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
+           II->getOperand(0) == TrampMem)
+--- lib/Transforms/InstCombine/InstCombineCasts.cpp	2014-12-12 10:48:37.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombineCasts.cpp	2015-11-30 07:19:19.812837233 -0800
+@@ -86,7 +86,7 @@
+   PointerType *PTy = cast<PointerType>(CI.getType());
+ 
+   BuilderTy AllocaBuilder(*Builder);
+-  AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
++  AllocaBuilder.SetInsertPoint(&AI);
+ 
+   // Get the type really allocated and the type casted to.
+   Type *AllocElTy = AI.getAllocatedType();
+--- lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp	2015-02-12 19:19:15.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp	2015-11-30 07:27:36.109476800 -0800
+@@ -187,8 +187,9 @@
+       // Scan to the end of the allocation instructions, to skip over a block of
+       // allocas if possible...also skip interleaved debug info
+       //
+-      BasicBlock::iterator It = New;
+-      while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
++      BasicBlock::iterator It(New);
++      while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
++        ++It;
+ 
+       // Now that I is pointing to the first non-allocation-inst in the block,
+       // insert our getelementptr instruction...
+@@ -419,7 +420,7 @@
+   // Do really simple store-to-load forwarding and load CSE, to catch cases
+   // where there are several consecutive memory accesses to the same location,
+   // separated by a few arithmetic operations.
+-  BasicBlock::iterator BBI = &LI;
++  BasicBlock::iterator BBI(LI);
+   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
+     return ReplaceInstUsesWith(
+         LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
+@@ -644,7 +645,7 @@
+   // Do really simple DSE, to catch cases where there are several consecutive
+   // stores to the same location, separated by a few arithmetic operations. This
+   // situation often occurs with bitfield accesses.
+-  BasicBlock::iterator BBI = &SI;
++  BasicBlock::iterator BBI(SI);
+   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
+        --ScanInsts) {
+     --BBI;
+@@ -703,7 +704,7 @@
+   // If this store is the last instruction in the basic block (possibly
+   // excepting debug info instructions), and if the block ends with an
+   // unconditional branch, try to move it to the successor block.
+-  BBI = &SI;
++  BBI = SI.getIterator();
+   do {
+     ++BBI;
+   } while (isa<DbgInfoIntrinsic>(BBI) ||
+@@ -759,7 +760,7 @@
+     return false;
+ 
+   // Verify that the other block ends in a branch and is not otherwise empty.
+-  BasicBlock::iterator BBI = OtherBB->getTerminator();
++  BasicBlock::iterator BBI(OtherBB->getTerminator());
+   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
+   if (!OtherBr || BBI == OtherBB->begin())
+     return false;
+--- lib/Transforms/InstCombine/InstCombineMulDivRem.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombineMulDivRem.cpp	2015-11-30 07:30:31.455813053 -0800
+@@ -736,7 +736,7 @@
+     return true;
+ 
+   // Scan the current block backward, looking for other uses of SI.
+-  BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
++  BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
+ 
+   while (BBI != BBFront) {
+     --BBI;
+@@ -750,10 +750,10 @@
+          I != E; ++I) {
+       if (*I == SI) {
+         *I = SI->getOperand(NonNullOperand);
+-        Worklist.Add(BBI);
++        Worklist.Add(&*BBI);
+       } else if (*I == SelectCond) {
+         *I = Builder->getInt1(NonNullOperand == 1);
+-        Worklist.Add(BBI);
++        Worklist.Add(&*BBI);
+       }
+     }
+ 
+--- lib/Transforms/InstCombine/InstCombinePHI.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombinePHI.cpp	2015-11-30 07:32:38.250246960 -0800
+@@ -247,7 +247,7 @@
+ /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
+ /// to a register.
+ static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
+-  BasicBlock::iterator BBI = L, E = L->getParent()->end();
++  BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
+ 
+   for (++BBI; BBI != E; ++BBI)
+     if (BBI->mayWriteToMemory())
+@@ -744,7 +744,7 @@
+         }
+ 
+         // Otherwise, do an extract in the predecessor.
+-        Builder->SetInsertPoint(Pred, Pred->getTerminator());
++        Builder->SetInsertPoint(Pred->getTerminator());
+         Value *Res = InVal;
+         if (Offset)
+           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
+--- lib/Transforms/InstCombine/InstCombineVectorOps.cpp	2014-07-07 15:13:58.000000000 -0700
++++ lib/Transforms/InstCombine/InstCombineVectorOps.cpp	2015-11-30 07:47:54.223248158 -0800
+@@ -162,8 +162,7 @@
+       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
+       BasicBlock::iterator InsertPos;
+       if (pos && !isa<PHINode>(pos)) {
+-        InsertPos = pos;
+-        ++InsertPos;
++        InsertPos = ++pos->getIterator();
+       } else {
+         InsertPos = inBB->getFirstInsertionPt();
+       }
+--- lib/Transforms/InstCombine/InstCombine.h	2015-01-06 16:39:50.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombine.h	2015-11-30 06:47:44.140493020 -0800
+@@ -297,7 +297,7 @@
+     assert(New && !New->getParent() &&
+            "New instruction already inserted into a basic block!");
+     BasicBlock *BB = Old.getParent();
+-    BB->getInstList().insert(&Old, New); // Insert inst
++    BB->getInstList().insert(Old.getIterator(), New); // Insert inst
+     Worklist.Add(New);
+     return New;
+   }
+--- lib/Transforms/InstCombine/InstructionCombining.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/InstCombine/InstructionCombining.cpp	2015-11-30 09:32:37.959104590 -0800
+@@ -1417,13 +1417,13 @@
+     if (DI == -1) {
+       // All the GEPs feeding the PHI are identical. Clone one down into our
+       // BB so that it can be merged with the current GEP.
+-      GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
+-                                            NewGEP);
++      GEP.getParent()->getInstList().insert(
++        GEP.getParent()->getFirstNonPHI()->getIterator(), NewGEP);
+     } else {
+       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
+       // into the current block so it can be merged, and create a new PHI to
+       // set that index.
+-      Instruction *InsertPt = Builder->GetInsertPoint();
++      Instruction *InsertPt = &*Builder->GetInsertPoint();
+       Builder->SetInsertPoint(PN);
+       PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
+                                           PN->getNumOperands());
+@@ -1434,8 +1434,8 @@
+                            PN->getIncomingBlock(I));
+ 
+       NewGEP->setOperand(DI, NewPN);
+-      GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
+-                                            NewGEP);
++      GEP.getParent()->getInstList().insert(
++        GEP.getParent()->getFirstNonPHI()->getIterator(), NewGEP);
+       NewGEP->setOperand(DI, NewPN);
+     }
+ 
+@@ -1768,7 +1768,7 @@
+           if (Instruction *I = visitBitCast(*BCI)) {
+             if (I != BCI) {
+               I->takeName(BCI);
+-              BCI->getParent()->getInstList().insert(BCI, I);
++              BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
+               ReplaceInstUsesWith(*BCI, I);
+             }
+             return &GEP;
+@@ -2269,7 +2269,7 @@
+ 
+       // We need to insert these at the location of the old load, not at that of
+       // the extractvalue.
+-      Builder->SetInsertPoint(L->getParent(), L);
++      Builder->SetInsertPoint(L);
+       Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
+       // Returning the load directly will cause the main loop to insert it in
+       // the wrong spot, so use ReplaceInstUsesWith().
+@@ -2648,14 +2648,14 @@
+   // We can only sink load instructions if there is nothing between the load and
+   // the end of block that could change the value.
+   if (I->mayReadFromMemory()) {
+-    for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
+-         Scan != E; ++Scan)
++    for (BasicBlock::iterator Scan = I->getIterator(),
++         E = I->getParent()->end(); Scan != E; ++Scan)
+       if (Scan->mayWriteToMemory())
+         return false;
+   }
+ 
+   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
+-  I->moveBefore(InsertPos);
++  I->moveBefore(&*InsertPos);
+   ++NumSunkInst;
+   return true;
+ }
+@@ -2690,7 +2690,8 @@
+       continue;
+ 
+     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
+-      Instruction *Inst = BBI++;
++      Instruction *Inst = &*BBI;
++      ++BBI;
+ 
+       // DCE instruction if trivially dead.
+       if (isInstructionTriviallyDead(Inst, TLI)) {
+@@ -2787,22 +2788,21 @@
+     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
+     // track of which blocks we visit.
+     SmallPtrSet<BasicBlock*, 64> Visited;
+-    MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
++    MadeIRChange |= AddReachableCodeToWorklist(&F.front(), Visited, *this, DL,
+                                                TLI);
+ 
+     // Do a quick scan over the function.  If we find any blocks that are
+     // unreachable, remove any instructions inside of them.  This prevents
+     // the instcombine code from having to deal with some bad special cases.
+     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
+-      if (Visited.count(BB)) continue;
++      if (Visited.count(&*BB)) continue;
+ 
+       // Delete the instructions backwards, as it has a reduced likelihood of
+       // having to update as many def-use and use-def chains.
+       Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
+       while (EndInst != BB->begin()) {
+         // Delete the next to last instruction.
+-        BasicBlock::iterator I = EndInst;
+-        Instruction *Inst = --I;
++        Instruction *Inst = &*--EndInst->getIterator();
+         if (!Inst->use_empty())
+           Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
+         if (isa<LandingPadInst>(Inst)) {
+@@ -2884,7 +2884,7 @@
+     }
+ 
+     // Now that we have an instruction, try combining it to simplify it.
+-    Builder->SetInsertPoint(I->getParent(), I);
++    Builder->SetInsertPoint(I);
+     Builder->SetCurrentDebugLocation(I->getDebugLoc());
+ 
+ #ifndef NDEBUG
+@@ -2914,7 +2914,7 @@
+ 
+         // Insert the new instruction into the basic block...
+         BasicBlock *InstParent = I->getParent();
+-        BasicBlock::iterator InsertPos = I;
++        BasicBlock::iterator InsertPos = I->getIterator();
+ 
+         // If we replace a PHI with something that isn't a PHI, fix up the
+         // insertion point.
+--- lib/Transforms/Instrumentation/AddressSanitizer.cpp	2015-02-03 10:58:33.000000000 -0800
++++ lib/Transforms/Instrumentation/AddressSanitizer.cpp	2016-01-23 20:36:01.000000000 -0800
+@@ -158,10 +158,11 @@
+                 "this number of memory accesses, use callbacks instead of "
+                 "inline checks (-1 means never use callbacks)."),
+        cl::Hidden, cl::init(7000));
++static std::string AsanInitString("__asan_");
+ static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
+        "asan-memory-access-callback-prefix",
+        cl::desc("Prefix for memory access callbacks"), cl::Hidden,
+-       cl::init("__asan_"));
++       cl::init(AsanInitString));
+ static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
+        cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
+ 
+@@ -1007,7 +1008,8 @@
+ void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
+                                                   GlobalValue *ModuleName) {
+   // Set up the arguments to our poison/unpoison functions.
+-  IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
++  IRBuilder<> IRB(&GlobalInit.front(),
++                  GlobalInit.front().getFirstInsertionPt());
+ 
+   // Add a call to poison all external globals before the given function starts.
+   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
+@@ -1402,7 +1404,7 @@
+   // We cannot just ignore these methods, because they may call other
+   // instrumented functions.
+   if (F.getName().find(" load]") != std::string::npos) {
+-    IRBuilder<> IRB(F.begin()->begin());
++    IRBuilder<> IRB(&F.front(), F.front().begin());
+     IRB.CreateCall(AsanInitFunction);
+     return true;
+   }
+--- lib/Transforms/Instrumentation/BoundsChecking.cpp	2014-04-24 22:29:35.000000000 -0700
++++ lib/Transforms/Instrumentation/BoundsChecking.cpp	2015-11-30 11:29:13.966151410 -0800
+@@ -108,7 +108,7 @@
+   }
+   ++ChecksAdded;
+ 
+-  Instruction *Inst = Builder->GetInsertPoint();
++  BasicBlock::iterator Inst = Builder->GetInsertPoint();
+   BasicBlock *OldBB = Inst->getParent();
+   BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
+   OldBB->getTerminator()->eraseFromParent();
+--- lib/Transforms/Instrumentation/DataFlowSanitizer.cpp	2014-12-05 13:22:32.000000000 -0800
++++ lib/Transforms/Instrumentation/DataFlowSanitizer.cpp	2015-11-30 13:39:14.566562460 -0800
+@@ -580,7 +580,7 @@
+     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
+     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
+     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
+-      DFSF.ValShadowMap[ValAI] = ShadowAI;
++      DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
+     DFSanVisitor(DFSF).visitCallInst(*CI);
+     if (!FT->getReturnType()->isVoidTy())
+       new StoreInst(DFSF.getShadow(RI->getReturnValue()),
+@@ -648,16 +648,16 @@
+ 
+   std::vector<Function *> FnsToInstrument;
+   llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
+-  for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
+-    if (!i->isIntrinsic() &&
+-        i != DFSanUnionFn &&
+-        i != DFSanCheckedUnionFn &&
+-        i != DFSanUnionLoadFn &&
+-        i != DFSanUnimplementedFn &&
+-        i != DFSanSetLabelFn &&
+-        i != DFSanNonzeroLabelFn &&
+-        i != DFSanVarargWrapperFn)
+-      FnsToInstrument.push_back(&*i);
++  for (Function &i : M) {
++    if (!i.isIntrinsic() &&
++        &i != DFSanUnionFn &&
++        &i != DFSanCheckedUnionFn &&
++        &i != DFSanUnionLoadFn &&
++        &i != DFSanUnimplementedFn &&
++        &i != DFSanSetLabelFn &&
++        &i != DFSanNonzeroLabelFn &&
++        &i != DFSanVarargWrapperFn)
++      FnsToInstrument.push_back(&i);
+   }
+ 
+   // Give function aliases prefixes when necessary, and build wrappers where the
+@@ -715,7 +715,7 @@
+                                     NewFArg = NewF->arg_begin(),
+                                     FArgEnd = F.arg_end();
+              FArg != FArgEnd; ++FArg, ++NewFArg) {
+-          FArg->replaceAllUsesWith(NewFArg);
++          FArg->replaceAllUsesWith(&*NewFArg);
+         }
+         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
+ 
+@@ -847,7 +847,7 @@
+         if (Instruction *I = dyn_cast<Instruction>(V))
+           Pos = I->getNextNode();
+         else
+-          Pos = DFSF.F->getEntryBlock().begin();
++          Pos = &DFSF.F->getEntryBlock().front();
+         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
+           Pos = Pos->getNextNode();
+         IRBuilder<> IRB(Pos);
+@@ -869,7 +869,7 @@
+   if (DFS.ArgTLS)
+     return ArgTLSPtr = DFS.ArgTLS;
+ 
+-  IRBuilder<> IRB(F->getEntryBlock().begin());
++  IRBuilder<> IRB(&F->getEntryBlock().front());
+   return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
+ }
+ 
+@@ -879,7 +879,7 @@
+   if (DFS.RetvalTLS)
+     return RetvalTLSPtr = DFS.RetvalTLS;
+ 
+-  IRBuilder<> IRB(F->getEntryBlock().begin());
++  IRBuilder<> IRB(&F->getEntryBlock().front());
+   return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
+ }
+ 
+@@ -911,7 +911,7 @@
+         Function::arg_iterator i = F->arg_begin();
+         while (ArgIdx--)
+           ++i;
+-        Shadow = i;
++        Shadow = &*i;
+         assert(Shadow->getType() == DFS.ShadowTy);
+         break;
+       }
+@@ -996,7 +996,7 @@
+     Call->addAttribute(2, Attribute::ZExt);
+ 
+     BasicBlock *Tail = BI->getSuccessor(0);
+-    PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
++    PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
+     Phi->addIncoming(Call, Call->getParent());
+     Phi->addIncoming(V1, Head);
+ 
+@@ -1109,7 +1109,7 @@
+     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
+ 
+     BasicBlock *Head = Pos->getParent();
+-    BasicBlock *Tail = Head->splitBasicBlock(Pos);
++    BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
+ 
+     if (DomTreeNode *OldNode = DT.getNode(Head)) {
+       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
+@@ -1476,7 +1476,7 @@
+           auto LabelVAAlloca =
+               new AllocaInst(ArrayType::get(DFSF.DFS.ShadowTy,
+                                             CS.arg_size() - FT->getNumParams()),
+-                             "labelva", DFSF.F->getEntryBlock().begin());
++                             "labelva", &DFSF.F->getEntryBlock().front());
+ 
+           for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
+             auto LabelVAPtr = IRB.CreateStructGEP(LabelVAAlloca, n);
+@@ -1490,7 +1490,7 @@
+           if (!DFSF.LabelReturnAlloca) {
+             DFSF.LabelReturnAlloca =
+                 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
+-                               DFSF.F->getEntryBlock().begin());
++                               &DFSF.F->getEntryBlock().front());
+           }
+           Args.push_back(DFSF.LabelReturnAlloca);
+         }
+@@ -1529,11 +1529,11 @@
+   if (!CS.getType()->isVoidTy()) {
+     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
+       if (II->getNormalDest()->getSinglePredecessor()) {
+-        Next = II->getNormalDest()->begin();
++        Next = &II->getNormalDest()->front();
+       } else {
+         BasicBlock *NewBB =
+             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
+-        Next = NewBB->begin();
++        Next = &NewBB->front();
+       }
+     } else {
+       Next = CS->getNextNode();
+@@ -1568,7 +1568,7 @@
+       unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
+       ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
+       AllocaInst *VarArgShadow =
+-          new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
++          new AllocaInst(VarArgArrayTy, "", &DFSF.F->getEntryBlock().front());
+       Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
+       for (unsigned n = 0; i != e; ++i, ++n) {
+         IRB.CreateStore(DFSF.getShadow(*i),
+--- lib/Transforms/Instrumentation/GCOVProfiling.cpp	2015-05-04 12:18:18.000000000 -0700
++++ lib/Transforms/Instrumentation/GCOVProfiling.cpp	2016-01-23 20:38:11.000000000 -0800
+@@ -44,8 +44,10 @@
+ 
+ #define DEBUG_TYPE "insert-gcov-profiling"
+ 
++static std::string VersionInitString("402*");
+ static cl::opt<std::string>
+-DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
++DefaultGCOVVersion("default-gcov-version",
++                   cl::init(VersionInitString), cl::Hidden,
+                    cl::ValueRequired);
+ static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
+                                                 cl::init(false), cl::Hidden);
+@@ -351,8 +353,8 @@
+       std::string EdgeDestinations;
+       raw_string_ostream EDOS(EdgeDestinations);
+       Function *F = Blocks.begin()->first->getParent();
+-      for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
+-        GCOVBlock &Block = getBlock(I);
++      for (BasicBlock &I : *F) {
++        GCOVBlock &Block = getBlock(&I);
+         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
+           EDOS << Block.OutEdges[i]->Number;
+       }
+@@ -393,8 +395,8 @@
+       // Emit edges between blocks.
+       if (Blocks.empty()) return;
+       Function *F = Blocks.begin()->first->getParent();
+-      for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
+-        GCOVBlock &Block = getBlock(I);
++      for (BasicBlock &I : *F) {
++        GCOVBlock &Block = getBlock(&I);
+         if (Block.OutEdges.empty()) continue;
+ 
+         writeBytes(EdgeTag, 4);
+@@ -409,8 +411,8 @@
+       }
+ 
+       // Emit lines for each block.
+-      for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
+-        getBlock(I).writeOut();
++      for (BasicBlock &I : *F) {
++        getBlock(&I).writeOut();
+       }
+     }
+ 
+@@ -522,7 +524,7 @@
+       GCOVFunction &Func = *Funcs.back();
+ 
+       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
+-        GCOVBlock &Block = Func.getBlock(BB);
++        GCOVBlock &Block = Func.getBlock(&*BB);
+         TerminatorInst *TI = BB->getTerminator();
+         if (int successors = TI->getNumSuccessors()) {
+           for (int i = 0; i != successors; ++i) {
+@@ -618,7 +620,7 @@
+         int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
+         if (Successors) {
+           if (Successors == 1) {
+-            IRBuilder<> Builder(BB->getFirstInsertionPt());
++            IRBuilder<> Builder(&*BB->getFirstInsertionPt());
+             Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
+                                                                 Edge);
+             Value *Count = Builder.CreateLoad(Counter);
+@@ -637,7 +639,7 @@
+             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
+             Builder.CreateStore(Count, Counter);
+           } else {
+-            ComplexEdgePreds.insert(BB);
++            ComplexEdgePreds.insert(&*BB);
+             for (int i = 0; i != Successors; ++i)
+               ComplexEdgeSuccs.insert(TI->getSuccessor(i));
+           }
+@@ -653,13 +655,13 @@
+         GlobalVariable *EdgeState = getEdgeStateValue();
+ 
+         for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
+-          IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
++          IRBuilder<> Builder(&*ComplexEdgePreds[i + 1]->getFirstInsertionPt());
+           Builder.CreateStore(Builder.getInt32(i), EdgeState);
+         }
+ 
+         for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
+           // Call runtime to perform increment.
+-          IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
++          IRBuilder<> Builder(&*ComplexEdgeSuccs[i + 1]->getFirstInsertionPt());
+           Value *CounterPtrArray =
+             Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
+                                                i * ComplexEdgePreds.size());
+@@ -743,8 +745,8 @@
+         IRBuilder<> Builder(Succ);
+         Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
+                                                             Edge + i);
+-        EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
+-                  (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
++        EdgeTable[((Succs.idFor(Succ) - 1) * Preds.size()) +
++                  (Preds.idFor(&*BB) - 1)] = cast<Constant>(Counter);
+       }
+     }
+     Edge += Successors;
+@@ -913,7 +915,7 @@
+ 
+   // uint32_t pred = *predecessor;
+   // if (pred == 0xffffffff) return;
+-  Argument *Arg = Fn->arg_begin();
++  Argument *Arg = &*Fn->arg_begin();
+   Arg->setName("predecessor");
+   Value *Pred = Builder.CreateLoad(Arg, "pred");
+   Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
+@@ -924,7 +926,7 @@
+   // uint64_t *counter = counters[pred];
+   // if (!counter) return;
+   Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
+-  Arg = std::next(Fn->arg_begin());
++  Arg = &*std::next(Fn->arg_begin());
+   Arg->setName("counters");
+   Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
+   Value *Counter = Builder.CreateLoad(GEP, "counter");
+--- lib/Transforms/Instrumentation/InstrProfiling.cpp	2015-02-10 20:41:09.000000000 -0800
++++ lib/Transforms/Instrumentation/InstrProfiling.cpp	2015-11-30 19:51:07.408467787 -0800
+@@ -143,7 +143,7 @@
+ void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
+   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
+ 
+-  IRBuilder<> Builder(Inc->getParent(), *Inc);
++  IRBuilder<> Builder(Inc);
+   uint64_t Index = Inc->getIndex()->getZExtValue();
+   llvm::Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
+   llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount");
+--- lib/Transforms/Instrumentation/MemorySanitizer.cpp	2015-02-06 14:06:43.000000000 -0800
++++ lib/Transforms/Instrumentation/MemorySanitizer.cpp	2015-11-30 19:55:19.370562015 -0800
+@@ -603,7 +603,7 @@
+         Value *Cmp = IRB.CreateICmpNE(
+             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
+         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
+-            Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
++            Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
+         IRBuilder<> IRBNew(CheckTerm);
+         IRBNew.CreateAlignedStore(updateOrigin(Origin, IRBNew),
+                                   getOriginPtr(Addr, IRBNew, Alignment),
+@@ -2396,9 +2396,10 @@
+     // Until we have full dynamic coverage, make sure the retval shadow is 0.
+     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
+     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
+-    Instruction *NextInsn = nullptr;
++    BasicBlock::iterator NextInsn;
+     if (CS.isCall()) {
+-      NextInsn = I.getNextNode();
++      NextInsn = ++I.getIterator();
++      assert(NextInsn != I.getParent()->end());
+     } else {
+       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
+       if (!NormalDest->getSinglePredecessor()) {
+@@ -2410,10 +2411,10 @@
+         return;
+       }
+       NextInsn = NormalDest->getFirstInsertionPt();
+-      assert(NextInsn &&
++      assert(NextInsn != NormalDest->end() &&
+              "Could not find insertion point for retval shadow load");
+     }
+-    IRBuilder<> IRBAfter(NextInsn);
++    IRBuilder<> IRBAfter(&*NextInsn);
+     Value *RetvalShadow =
+       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
+                                  kShadowTLSAlignment, "_msret");
+--- lib/Transforms/Instrumentation/SanitizerCoverage.cpp	2015-01-02 16:54:43.000000000 -0800
++++ lib/Transforms/Instrumentation/SanitizerCoverage.cpp	2015-11-30 19:58:56.426390313 -0800
+@@ -275,7 +275,8 @@
+   bool IsEntryBB = &BB == &F.getEntryBlock();
+   DebugLoc EntryLoc =
+       IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
+-  IRBuilder<> IRB(IP);
++
++  IRBuilder<> IRB(&*IP);
+   IRB.SetCurrentDebugLocation(EntryLoc);
+   SmallVector<Value *, 1> Indices;
+   Value *GuardP = IRB.CreateAdd(
+@@ -290,7 +291,7 @@
+                     MDNode::get(*C, None));
+   Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
+   Instruction *Ins = SplitBlockAndInsertIfThen(
+-      Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
++      Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
+   IRB.SetInsertPoint(Ins);
+   IRB.SetCurrentDebugLocation(EntryLoc);
+   // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
+@@ -300,7 +301,7 @@
+   if (ClExperimentalTracing) {
+     // Experimental support for tracing.
+     // Insert a callback with the same guard variable as used for coverage.
+-    IRB.SetInsertPoint(IP);
++    IRB.SetInsertPoint(&*IP);
+     IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
+   }
+ }
+--- lib/Transforms/ObjCARC/DependencyAnalysis.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/ObjCARC/DependencyAnalysis.cpp	2015-11-30 20:05:22.864307715 -0800
+@@ -209,7 +209,7 @@
+                                 SmallPtrSetImpl<Instruction *> &DependingInsts,
+                                 SmallPtrSetImpl<const BasicBlock *> &Visited,
+                                 ProvenanceAnalysis &PA) {
+-  BasicBlock::iterator StartPos = StartInst;
++  BasicBlock::iterator StartPos = StartInst->getIterator();
+ 
+   SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
+   Worklist.push_back(std::make_pair(StartBB, StartPos));
+@@ -235,7 +235,7 @@
+         break;
+       }
+ 
+-      Instruction *Inst = --LocalStartPos;
++      Instruction *Inst = &*--LocalStartPos;
+       if (Depends(Flavor, Inst, Arg, PA)) {
+         DependingInsts.insert(Inst);
+         break;
+--- lib/Transforms/ObjCARC/ObjCARCAPElim.cpp	2014-05-16 13:39:27.000000000 -0700
++++ lib/Transforms/ObjCARC/ObjCARCAPElim.cpp	2015-11-30 20:09:20.487861680 -0800
+@@ -72,12 +72,9 @@
+   if (const Function *Callee = CS.getCalledFunction()) {
+     if (Callee->isDeclaration() || Callee->mayBeOverridden())
+       return true;
+-    for (Function::const_iterator I = Callee->begin(), E = Callee->end();
+-         I != E; ++I) {
+-      const BasicBlock *BB = I;
+-      for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
+-           J != F; ++J)
+-        if (ImmutableCallSite JCS = ImmutableCallSite(J))
++    for (const BasicBlock &BB : *Callee) {
++      for (const Instruction &I : BB)
++        if (ImmutableCallSite JCS = ImmutableCallSite(&I))
+           // This recursion depth limit is arbitrary. It's just great
+           // enough to cover known interesting testcases.
+           if (Depth < 3 &&
+@@ -96,7 +93,7 @@
+ 
+   Instruction *Push = nullptr;
+   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
+-    Instruction *Inst = I++;
++    Instruction *Inst = &*I++;
+     switch (GetBasicInstructionClass(Inst)) {
+     case IC_AutoreleasepoolPush:
+       Push = Inst;
+@@ -169,7 +166,7 @@
+     if (std::next(F->begin()) != F->end())
+       continue;
+     // Ok, a single-block constructor function definition. Try to optimize it.
+-    Changed |= OptimizeBB(F->begin());
++    Changed |= OptimizeBB(&F->front());
+   }
+ 
+   return Changed;
+--- lib/Transforms/ObjCARC/ObjCARCContract.cpp	2014-11-11 13:30:22.000000000 -0800
++++ lib/Transforms/ObjCARC/ObjCARCContract.cpp	2015-12-01 09:48:41.817465473 -0800
+@@ -123,9 +123,10 @@
+     return false;
+ 
+   // Check that the call is next to the retain.
+-  BasicBlock::const_iterator I = Call;
++  BasicBlock::const_iterator I = ++Call->getIterator();
++  while (IsNoopInstruction(&*I))
+   ++I;
+-  while (IsNoopInstruction(I)) ++I;
++
+   if (&*I != Retain)
+     return false;
+ 
+@@ -202,69 +203,166 @@
+   return true;
+ }
+ 
+-/// Attempt to merge an objc_release with a store, load, and objc_retain to form
+-/// an objc_storeStrong. This can be a little tricky because the instructions
+-/// don't always appear in order, and there may be unrelated intervening
+-/// instructions.
+-void ObjCARCContract::ContractRelease(Instruction *Release,
+-                                      inst_iterator &Iter) {
+-  LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
+-  if (!Load || !Load->isSimple()) return;
+-
+-  // For now, require everything to be in one basic block.
+-  BasicBlock *BB = Release->getParent();
+-  if (Load->getParent() != BB) return;
+ 
+-  // Walk down to find the store and the release, which may be in either order.
+-  BasicBlock::iterator I = Load, End = BB->end();
+-  ++I;
+-  AliasAnalysis::Location Loc = AA->getLocation(Load);
++static StoreInst* findSafeStoreForStoreStrongContraction(LoadInst *Load,
++                                                         Instruction *Release,
++                                                         ProvenanceAnalysis &PA,
++                                                         AliasAnalysis *AA) {
+   StoreInst *Store = nullptr;
+   bool SawRelease = false;
+-  for (; !Store || !SawRelease; ++I) {
+-    if (I == End)
+-      return;
+ 
+-    Instruction *Inst = I;
++  // Get the location associated with Load.
++  AliasAnalysis::Location Loc = AA->getLocation(Load);
++
++  // Walk down to find the store and the release, which may be in either order.
++  for (auto I = std::next(BasicBlock::iterator(Load)),
++            E = Load->getParent()->end();
++       I != E; ++I) {
++    // If we found the store we were looking for and saw the release,
++    // break. There is no more work to be done.
++    if (Store && SawRelease)
++      break;
++
++    // Now we know that we have not seen either the store or the release. If I
++    // is the release, mark that we saw the release and continue.
++    Instruction *Inst = &*I;
+     if (Inst == Release) {
+       SawRelease = true;
+       continue;
+     }
+ 
+-    InstructionClass Class = GetBasicInstructionClass(Inst);
+-
+-    // Unrelated retains are harmless.
+-    if (IsRetain(Class))
++    // Otherwise, we check if Inst is a "good" store. Grab the instruction class
++    // of Inst.
++    InstructionClass IC = GetBasicInstructionClass(Inst);
++
++    // If Inst is an unrelated retain, we don't care about it.
++    //
++    // TODO: This is one area where the optimization could be made more
++    // aggressive.
++    if (IsRetain(IC))
+       continue;
+ 
++    // If we have seen the store, but not the release...
+     if (Store) {
+-      // The store is the point where we're going to put the objc_storeStrong,
+-      // so make sure there are no uses after it.
+-      if (CanUse(Inst, Load, PA, Class))
+-        return;
+-    } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
+-      // We are moving the load down to the store, so check for anything
+-      // else which writes to the memory between the load and the store.
+-      Store = dyn_cast<StoreInst>(Inst);
+-      if (!Store || !Store->isSimple()) return;
+-      if (Store->getPointerOperand() != Loc.Ptr) return;
++      // We need to make sure that it is safe to move the release from its
++      // current position to the store. This implies proving that any
++      // instruction in between Store and the Release conservatively can not use
++      // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
++      // continue...
++      if (!CanUse(Inst, Load, PA, IC)) {
++        continue;
++      }
++
++      // Otherwise, be conservative and return nullptr.
++      return nullptr;
+     }
++
++    // Ok, now we know we have not seen a store yet. See if Inst can write to
++    // our load location, if it can not, just ignore the instruction.
++    if (!(AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod))
++      continue;
++
++    Store = dyn_cast<StoreInst>(Inst);
++
++    // If Inst can, then check if Inst is a simple store. If Inst is not a
++    // store or a store that is not simple, then we have some we do not
++    // understand writing to this memory implying we can not move the load
++    // over the write to any subsequent store that we may find.
++    if (!Store || !Store->isSimple())
++      return nullptr;
++
++    // Then make sure that the pointer we are storing to is Ptr. If so, we
++    // found our Store!
++    if (Store->getPointerOperand() == Loc.Ptr)
++      continue;
++
++    // Otherwise, we have an unknown store to some other ptr that clobbers
++    // Loc.Ptr. Bail!
++    return nullptr;
+   }
+ 
+-  Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
++  // If we did not find the store or did not see the release, fail.
++  if (!Store || !SawRelease)
++    return nullptr;
++
++  // We succeeded!
++  return Store;
++}
++
++static Instruction*
++findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
++                                    Instruction *Release,
++                                    ProvenanceAnalysis &PA) {
++  // Walk up from the Store to find the retain.
++  BasicBlock::iterator I = Store->getIterator();
++  BasicBlock::iterator Begin = Store->getParent()->begin();
++  while ((I != Begin) && (GetBasicInstructionClass(&*I) != IC_Retain)) {
++    Instruction *Inst = &*I;
++
++    // This is not exactly correct, but it's non-portable to 3.6.2.
++    if (Inst != Release)
++      return nullptr;
+ 
+-  // Walk up to find the retain.
+-  I = Store;
+-  BasicBlock::iterator Begin = BB->begin();
+-  while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
+     --I;
+-  Instruction *Retain = I;
+-  if (GetBasicInstructionClass(Retain) != IC_Retain) return;
+-  if (GetObjCArg(Retain) != New) return;
++  }
++
++  Instruction *Retain = &*I;
++  if (GetBasicInstructionClass(Retain) != IC_Retain)
++    return nullptr;
++
++  if (GetObjCArg(Retain) != New)
++    return nullptr;
++
++  return Retain;
++}
++
++/// Attempt to merge an objc_release with a store, load, and objc_retain to form
++/// an objc_storeStrong. This can be a little tricky because the instructions
++/// don't always appear in order, and there may be unrelated intervening
++/// instructions.
++void ObjCARCContract::ContractRelease(Instruction *Release,
++                                      inst_iterator &Iter) {
++  // See if we are releasing something that we just loaded.
++  auto *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
++  if (!Load || !Load->isSimple())
++    return;
++
++  // For now, require everything to be in one basic block.
++  BasicBlock *BB = Release->getParent();
++  if (Load->getParent() != BB)
++    return;
++
++  // First scan down the BB from Load, looking for a store of the RCIdentityRoot
++  // of Load's
++  StoreInst *Store =
++      findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
++  // If we fail, bail.
++  if (!Store)
++    return;
++
++  // Then find what new_value's RCIdentity Root is.
++  Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
++
++  // Then walk up the BB and look for a retain on New without any intervening
++  // instructions which conservatively might decrement ref counts.
++  Instruction *Retain =
++      findRetainForStoreStrongContraction(New, Store, Release, PA);
++
++  // If we fail, bail.
++  if (!Retain)
++    return;
+ 
+   Changed = true;
+   ++NumStoreStrongs;
+ 
++  DEBUG(
++      llvm::dbgs() << "    Contracting retain, release into objc_storeStrong.\n"
++                   << "        Old:\n"
++                   << "            Store:   " << *Store << "\n"
++                   << "            Release: " << *Release << "\n"
++                   << "            Retain:  " << *Retain << "\n"
++                   << "            Load:    " << *Load << "\n");
++
+   LLVMContext &C = Release->getContext();
+   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
+   Type *I8XX = PointerType::getUnqual(I8X);
+@@ -274,6 +372,7 @@
+     Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
+   if (Args[1]->getType() != I8X)
+     Args[1] = new BitCastInst(Args[1], I8X, "", Store);
++    
+   Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_StoreStrong);
+   CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
+   StoreStrong->setDoesNotThrow();
+@@ -284,7 +383,11 @@
+   // we can set the tail flag once we know it's safe.
+   StoreStrongCalls.insert(StoreStrong);
+ 
+-  if (&*Iter == Store) ++Iter;
++  DEBUG(llvm::dbgs() << "        New Store Strong: " << *StoreStrong << "\n");
++
++  if (&*Iter == Store)
++    ++Iter;
++  
+   Store->eraseFromParent();
+   Release->eraseFromParent();
+   EraseInstruction(Retain);
+@@ -371,7 +474,8 @@
+       // insert it now.
+       if (!RetainRVMarker)
+         break;
+-      BasicBlock::iterator BBI = Inst;
++
++      BasicBlock::iterator BBI = Inst->getIterator();
+       BasicBlock *InstParent = Inst->getParent();
+ 
+       // Step up to see if the call immediately precedes the RetainRV call.
+@@ -382,11 +486,11 @@
+           BasicBlock *Pred = InstParent->getSinglePredecessor();
+           if (!Pred)
+             goto decline_rv_optimization;
+-          BBI = Pred->getTerminator();
++          BBI = Pred->getTerminator()->getIterator();
+           break;
+         }
+         --BBI;
+-      } while (IsNoopInstruction(BBI));
++      } while (IsNoopInstruction(&*BBI));
+ 
+       if (&*BBI == GetObjCArg(Inst)) {
+         DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
+--- lib/Transforms/ObjCARC/ObjCARCOpts.cpp	2014-12-09 10:38:53.000000000 -0800
++++ lib/Transforms/ObjCARC/ObjCARCOpts.cpp	2016-01-23 21:53:49.000000000 -0800
+@@ -798,19 +798,22 @@
+ 
+ /// Enable/disable ARC sequence annotations.
+ static cl::opt<bool>
+-EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
++EnableARCAnnotations("enable-objc-arc-annotations",
+                      cl::desc("Enable emission of arc data flow analysis "
+-                              "annotations"));
++                              "annotations"),
++                     cl::init(false));
+ static cl::opt<bool>
+-DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
++DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards",
+                           cl::desc("Disable check for cfg hazards when "
+-                                   "annotating"));
++                                   "annotating"),
++                          cl::init(false));
++static std::string EmptyInitString("");
+ static cl::opt<std::string>
+ ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
+-                              cl::init(""),
+                               cl::desc("filter out all data flow annotations "
+                                        "but those that apply to the given "
+-                                       "target llvm identifier."));
++                                       "target llvm identifier."),
++                              cl::init(EmptyInitString));
+ 
+ /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
+ /// instruction so that we can track backwards when post processing via the llvm
+@@ -1195,16 +1198,17 @@
+   ImmutableCallSite CS(Arg);
+   if (const Instruction *Call = CS.getInstruction()) {
+     if (Call->getParent() == RetainRV->getParent()) {
+-      BasicBlock::const_iterator I = Call;
++      BasicBlock::const_iterator I(Call);
+       ++I;
+-      while (IsNoopInstruction(I)) ++I;
++      while (IsNoopInstruction(&*I)) ++I;
+       if (&*I == RetainRV)
+         return false;
+     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
+       BasicBlock *RetainRVParent = RetainRV->getParent();
+       if (II->getNormalDest() == RetainRVParent) {
+         BasicBlock::const_iterator I = RetainRVParent->begin();
+-        while (IsNoopInstruction(I)) ++I;
++        while (IsNoopInstruction(&*I))
++          ++I;
+         if (&*I == RetainRV)
+           return false;
+       }
+@@ -1213,18 +1217,21 @@
+ 
+   // Check for being preceded by an objc_autoreleaseReturnValue on the same
+   // pointer. In this case, we can delete the pair.
+-  BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
++  BasicBlock::iterator I = RetainRV->getIterator(),
++                      Begin = RetainRV->getParent()->begin();
+   if (I != Begin) {
+-    do --I; while (I != Begin && IsNoopInstruction(I));
+-    if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
+-        GetObjCArg(I) == Arg) {
++    do
++      --I;
++    while (I != Begin && IsNoopInstruction(&*I));
++    if (GetBasicInstructionClass(&*I) == IC_AutoreleaseRV &&
++        GetObjCArg(&*I) == Arg) {
+       Changed = true;
+       ++NumPeeps;
+ 
+       DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
+                    << "Erasing " << *RetainRV << "\n");
+ 
+-      EraseInstruction(I);
++      EraseInstruction(&*I);
+       EraseInstruction(RetainRV);
+       return true;
+     }
+@@ -1861,9 +1868,9 @@
+         // one of its successor blocks, since we can't insert code after it
+         // in its own block, and we don't want to split critical edges.
+         if (isa<InvokeInst>(Inst))
+-          S.InsertReverseInsertPt(BB->getFirstInsertionPt());
++          S.InsertReverseInsertPt(&*BB->getFirstInsertionPt());
+         else
+-          S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
++          S.InsertReverseInsertPt(&*++Inst->getIterator());
+         S.SetSeq(S_Use);
+         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
+       } else if (Seq == S_Release && IsUser(Class)) {
+@@ -1875,9 +1882,9 @@
+         assert(!S.HasReverseInsertPts());
+         // As above; handle invoke specially.
+         if (isa<InvokeInst>(Inst))
+-          S.InsertReverseInsertPt(BB->getFirstInsertionPt());
++          S.InsertReverseInsertPt(&*BB->getFirstInsertionPt());
+         else
+-          S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
++          S.InsertReverseInsertPt(&*++Inst->getIterator());
+       }
+       break;
+     case S_Stop:
+@@ -1934,7 +1941,7 @@
+ 
+   // Visit all the instructions, bottom-up.
+   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
+-    Instruction *Inst = std::prev(I);
++    Instruction *Inst = &*std::prev(I);
+ 
+     // Invoke instructions are visited as part of their successors (below).
+     if (isa<InvokeInst>(Inst))
+@@ -2144,7 +2151,7 @@
+ 
+   // Visit all the instructions, top-down.
+   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
+-    Instruction *Inst = I;
++    Instruction *Inst = &*I;
+ 
+     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
+ 
+@@ -2219,7 +2226,7 @@
+   // as exits due to ignored edges.
+   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
+   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+-    BasicBlock *ExitBB = I;
++    BasicBlock *ExitBB = &*I;
+     BBState &MyStates = BBStates[ExitBB];
+     if (!MyStates.isExit())
+       continue;
+@@ -2655,7 +2662,7 @@
+     // analysis too, but that would want caching. A better approach would be to
+     // use the technique that EarlyCSE uses.
+     inst_iterator Current = std::prev(I);
+-    BasicBlock *CurrentBB = Current.getBasicBlockIterator();
++    BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
+     for (BasicBlock::iterator B = CurrentBB->begin(),
+                               J = Current.getInstructionIterator();
+          J != B; --J) {
+@@ -2910,9 +2917,8 @@
+ 
+   SmallPtrSet<Instruction *, 4> DependingInstructions;
+   SmallPtrSet<const BasicBlock *, 4> Visited;
+-  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
+-    BasicBlock *BB = FI;
+-    ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
++  for (BasicBlock &BB: F) {
++    ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
+ 
+     DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
+ 
+@@ -2925,7 +2931,7 @@
+     // dependent on Arg such that there are no instructions dependent on Arg
+     // that need a positive ref count in between the autorelease and Ret.
+     CallInst *Autorelease =
+-      FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
++      FindPredecessorAutoreleaseWithSafePath(Arg, &BB, Ret,
+                                              DependingInstructions, Visited,
+                                              PA);
+     DependingInstructions.clear();
+@@ -2935,7 +2941,7 @@
+       continue;
+ 
+     CallInst *Retain =
+-      FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
++      FindPredecessorRetainWithSafePath(Arg, &BB, Autorelease,
+                                         DependingInstructions, Visited, PA);
+     DependingInstructions.clear();
+     Visited.clear();
+--- lib/Transforms/ObjCARC/ObjCARCUtil.cpp	2013-07-10 11:49:00.000000000 -0700
++++ lib/Transforms/ObjCARC/ObjCARCUtil.cpp	2015-12-06 09:20:57.733406625 -0800
+@@ -91,7 +91,9 @@
+       .Default(IC_CallOrUser);
+ 
+   // One argument.
+-  const Argument *A0 = AI++;
++  const Argument *A0 = &*AI;
++  ++AI;
++
+   if (AI == AE)
+     // Argument is a pointer.
+     if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
+@@ -127,7 +129,9 @@
+     }
+ 
+   // Two arguments, first is i8**.
+-  const Argument *A1 = AI++;
++  const Argument *A1 = &*AI;
++  ++AI;
++
+   if (AI == AE)
+     if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
+       if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
+--- lib/Transforms/Scalar/ADCE.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/ADCE.cpp	2015-11-28 19:38:59.304881103 -0800
+@@ -63,8 +63,8 @@
+         isa<DbgInfoIntrinsic>(I.getInstructionIterator()) ||
+         isa<LandingPadInst>(I.getInstructionIterator()) ||
+         I->mayHaveSideEffects()) {
+-      alive.insert(I.getInstructionIterator());
+-      worklist.push_back(I.getInstructionIterator());
++      alive.insert(&*I);
++      worklist.push_back(&*I);
+     }
+ 
+   // Propagate liveness backwards to operands.
+@@ -82,8 +82,8 @@
+   // value of the function, and may therefore be deleted safely.
+   // NOTE: We reuse the worklist vector here for memory efficiency.
+   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
+-    if (!alive.count(I.getInstructionIterator())) {
+-      worklist.push_back(I.getInstructionIterator());
++    if (!alive.count(&*I)) {
++      worklist.push_back(&*I);
+       I->dropAllReferences();
+     }
+ 
+--- lib/Transforms/Scalar/ConstantHoisting.cpp	2014-10-04 09:55:56.000000000 -0700
++++ lib/Transforms/Scalar/ConstantHoisting.cpp	2015-11-28 19:44:37.366065720 -0800
+@@ -361,9 +361,9 @@
+ /// into an instruction itself.
+ void ConstantHoisting::collectConstantCandidates(Function &Fn) {
+   ConstCandMapType ConstCandMap;
+-  for (Function::iterator BB : Fn)
+-    for (BasicBlock::iterator Inst : *BB)
+-      collectConstantCandidates(ConstCandMap, Inst);
++  for (BasicBlock &BB : Fn)
++    for (Instruction &Inst : BB)
++      collectConstantCandidates(ConstCandMap, &Inst);
+ }
+ 
+ /// \brief Find the base constant within the given range and rebase all other
+--- lib/Transforms/Scalar/CorrelatedValuePropagation.cpp	2014-09-07 13:29:59.000000000 -0700
++++ lib/Transforms/Scalar/CorrelatedValuePropagation.cpp	2015-11-28 19:45:51.045707253 -0800
+@@ -296,7 +296,8 @@
+   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
+     bool BBChanged = false;
+     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
+-      Instruction *II = BI++;
++      Instruction *II = &*BI;
++      ++BI;
+       switch (II->getOpcode()) {
+       case Instruction::Select:
+         BBChanged |= processSelect(cast<SelectInst>(II));
+--- lib/Transforms/Scalar/DCE.cpp	2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/Scalar/DCE.cpp	2015-11-28 19:46:43.738032658 -0800
+@@ -45,7 +45,8 @@
+       TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
+       bool Changed = false;
+       for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) {
+-        Instruction *Inst = DI++;
++        Instruction *Inst = &*DI;
++        ++DI;
+         if (isInstructionTriviallyDead(Inst, TLI)) {
+           Inst->eraseFromParent();
+           Changed = true;
+--- lib/Transforms/Scalar/DeadStoreElimination.cpp	2014-10-17 04:56:00.000000000 -0700
++++ lib/Transforms/Scalar/DeadStoreElimination.cpp	2015-11-28 20:06:21.344415630 -0800
+@@ -64,11 +64,11 @@
+       TLI = AA->getTargetLibraryInfo();
+ 
+       bool Changed = false;
+-      for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
++      for (BasicBlock &I : F)
+         // Only check non-dead blocks.  Dead blocks may have strange pointer
+         // cycles that will confuse alias analysis.
+-        if (DT->isReachableFromEntry(I))
+-          Changed |= runOnBasicBlock(*I);
++        if (DT->isReachableFromEntry(&I))
++          Changed |= runOnBasicBlock(I);
+ 
+       AA = nullptr; MD = nullptr; DT = nullptr;
+       return Changed;
+@@ -488,7 +488,8 @@
+ 
+   // Do a top-down walk on the BB.
+   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
+-    Instruction *Inst = BBI++;
++    Instruction *Inst = &*BBI;
++    ++BBI;
+ 
+     // Handle 'free' calls specially.
+     if (CallInst *F = isFreeCall(Inst, TLI)) {
+@@ -518,7 +519,7 @@
+ 
+           // DeleteDeadInstruction can delete the current instruction.  Save BBI
+           // in case we need it.
+-          WeakVH NextInst(BBI);
++          WeakVH NextInst(&*BBI);
+ 
+           DeleteDeadInstruction(SI, *MD, TLI);
+ 
+@@ -573,7 +574,7 @@
+ 
+           // DeleteDeadInstruction can delete the current instruction in loop
+           // cases, reset BBI.
+-          BBI = Inst;
++          BBI = Inst->getIterator();
+           if (BBI != BB.begin())
+             --BBI;
+           break;
+@@ -619,7 +620,8 @@
+       if (AA->getModRefInfo(DepWrite, Loc) & AliasAnalysis::Ref)
+         break;
+ 
+-      InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
++      InstDep = MD->getPointerDependencyFrom(Loc, false,
++                                             DepWrite->getIterator(), &BB);
+     }
+   }
+ 
+@@ -661,7 +663,8 @@
+     Instruction *InstPt = BB->getTerminator();
+     if (BB == F->getParent()) InstPt = F;
+ 
+-    MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
++    MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false,
++                                                    InstPt->getIterator(), BB);
+     while (Dep.isDef() || Dep.isClobber()) {
+       Instruction *Dependency = Dep.getInst();
+       if (!hasMemoryWrite(Dependency, TLI) || !isRemovable(Dependency))
+@@ -674,7 +677,7 @@
+       if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
+         break;
+ 
+-      Instruction *Next = std::next(BasicBlock::iterator(Dependency));
++      Instruction *Next = &*std::next(BasicBlock::iterator(Dependency));
+ 
+       // DCE instructions only used to calculate that store
+       DeleteDeadInstruction(Dependency, *MD, TLI);
+@@ -686,7 +689,7 @@
+       //    s[0] = 0;
+       //    s[1] = 0; // This has just been deleted.
+       //    free(s);
+-      Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
++      Dep = MD->getPointerDependencyFrom(Loc, false, Next->getIterator(), BB);
+     }
+ 
+     if (Dep.isNonLocal())
+@@ -710,33 +713,32 @@
+   SmallSetVector<Value*, 16> DeadStackObjects;
+ 
+   // Find all of the alloca'd pointers in the entry block.
+-  BasicBlock *Entry = BB.getParent()->begin();
+-  for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
+-    if (isa<AllocaInst>(I))
+-      DeadStackObjects.insert(I);
++  BasicBlock &Entry = BB.getParent()->front();
++  for (Instruction &I : Entry) {
++    if (isa<AllocaInst>(&I))
++      DeadStackObjects.insert(&I);
+ 
+     // Okay, so these are dead heap objects, but if the pointer never escapes
+     // then it's leaked by this function anyways.
+-    else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
+-      DeadStackObjects.insert(I);
++    else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
++      DeadStackObjects.insert(&I);
+   }
+ 
+   // Treat byval or inalloca arguments the same, stores to them are dead at the
+   // end of the function.
+-  for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
+-       AE = BB.getParent()->arg_end(); AI != AE; ++AI)
+-    if (AI->hasByValOrInAllocaAttr())
+-      DeadStackObjects.insert(AI);
++  for (Argument &AI : BB.getParent()->args())
++    if (AI.hasByValOrInAllocaAttr())
++      DeadStackObjects.insert(&AI);
+ 
+   // Scan the basic block backwards
+   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
+     --BBI;
+ 
+     // If we find a store, check to see if it points into a dead stack value.
+-    if (hasMemoryWrite(BBI, TLI) && isRemovable(BBI)) {
++    if (hasMemoryWrite(&*BBI, TLI) && isRemovable(&*BBI)) {
+       // See through pointer-to-pointer bitcasts
+       SmallVector<Value *, 4> Pointers;
+-      GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers);
++      GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers);
+ 
+       // Stores to stack values are valid candidates for removal.
+       bool AllDead = true;
+@@ -748,7 +750,8 @@
+         }
+ 
+       if (AllDead) {
+-        Instruction *Dead = BBI++;
++        Instruction *Dead = &*BBI;
++        ++BBI;
+ 
+         DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n  DEAD: "
+                      << *Dead << "\n  Objects: ";
+@@ -769,8 +772,9 @@
+     }
+ 
+     // Remove any dead non-memory-mutating instructions.
+-    if (isInstructionTriviallyDead(BBI, TLI)) {
+-      Instruction *Inst = BBI++;
++    if (isInstructionTriviallyDead(&*BBI, TLI)) {
++      Instruction *Inst = &*BBI;
++      ++BBI;
+       DeleteDeadInstruction(Inst, *MD, TLI, &DeadStackObjects);
+       ++NumFastOther;
+       MadeChange = true;
+@@ -780,15 +784,15 @@
+     if (isa<AllocaInst>(BBI)) {
+       // Remove allocas from the list of dead stack objects; there can't be
+       // any references before the definition.
+-      DeadStackObjects.remove(BBI);
++      DeadStackObjects.remove(&*BBI);
+       continue;
+     }
+ 
+     if (CallSite CS = cast<Value>(BBI)) {
+       // Remove allocation function calls from the list of dead stack objects; 
+       // there can't be any references before the definition.
+-      if (isAllocLikeFn(BBI, TLI))
+-        DeadStackObjects.remove(BBI);
++      if (isAllocLikeFn(&*BBI, TLI))
++        DeadStackObjects.remove(&*BBI);
+ 
+       // If this call does not access memory, it can't be loading any of our
+       // pointers.
+--- lib/Transforms/Scalar/EarlyCSE.cpp	2015-02-10 18:23:00.000000000 -0800
++++ lib/Transforms/Scalar/EarlyCSE.cpp	2015-11-28 20:08:04.692689072 -0800
+@@ -427,7 +427,8 @@
+   // See if any instructions in the block can be eliminated.  If so, do it.  If
+   // not, add them to AvailableValues.
+   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
+-    Instruction *Inst = I++;
++    Instruction *Inst = &*I;
++    ++I;
+ 
+     // Dead instructions should just be removed.
+     if (isInstructionTriviallyDead(Inst, TLI)) {
+--- lib/Transforms/Scalar/FlattenCFGPass.cpp	2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/Scalar/FlattenCFGPass.cpp	2015-11-28 20:09:20.884486852 -0800
+@@ -59,7 +59,7 @@
+     // Loop over all of the basic blocks and remove them if they are unneeded...
+     //
+     for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
+-      if (FlattenCFG(BBIt++, AA)) {
++      if (FlattenCFG(&*BBIt++, AA)) {
+         LocalChange = true;
+       }
+     }
+--- lib/Transforms/Scalar/GVN.cpp	2015-05-05 07:43:00.000000000 -0700
++++ lib/Transforms/Scalar/GVN.cpp	2015-11-28 20:13:21.312881435 -0800
+@@ -1123,7 +1123,7 @@
+   uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
+   uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
+ 
+-  IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
++  IRBuilder<> Builder(InsertPt);
+ 
+   // Compute which bits of the stored value are being used by the load.  Convert
+   // to an integer type to start with.
+@@ -1220,7 +1220,7 @@
+   LLVMContext &Ctx = LoadTy->getContext();
+   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
+ 
+-  IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
++  IRBuilder<> Builder(InsertPt);
+ 
+   // We know that this method is only called when the mem transfer fully
+   // provides the bits for the load.
+@@ -2372,7 +2372,8 @@
+   // Merge unconditional branches, allowing PRE to catch more
+   // optimization opportunities.
+   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
+-    BasicBlock *BB = FI++;
++    BasicBlock *BB = &*FI;
++    ++FI;
+ 
+     bool removedBlock = MergeBlockIntoPredecessor(BB, this);
+     if (removedBlock) ++NumGVNBlocks;
+@@ -2425,7 +2426,7 @@
+ 
+   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
+        BI != BE;) {
+-    ChangedFunction |= processInstruction(BI);
++    ChangedFunction |= processInstruction(&*BI);
+     if (InstrsToErase.empty()) {
+       ++BI;
+       continue;
+@@ -2580,7 +2581,8 @@
+   // Create a PHI to make the value available in this block.
+   PHINode *Phi =
+       PHINode::Create(CurInst->getType(), predMap.size(),
+-                      CurInst->getName() + ".pre-phi", CurrentBlock->begin());
++                      CurInst->getName() + ".pre-phi",
++                      &CurrentBlock->front());
+   for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
+     if (Value *V = predMap[i].first)
+       Phi->addIncoming(V, predMap[i].second);
+@@ -2631,7 +2633,8 @@
+     for (BasicBlock::iterator BI = CurrentBlock->begin(),
+                               BE = CurrentBlock->end();
+          BI != BE;) {
+-      Instruction *CurInst = BI++;
++      Instruction *CurInst = &*BI;
++      ++BI;
+       Changed = performScalarPRE(CurInst);
+     }
+   }
+--- lib/Transforms/Scalar/IndVarSimplify.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/IndVarSimplify.cpp	2015-11-29 07:09:51.854588965 -0800
+@@ -435,7 +435,7 @@
+   // platforms.
+   if (WeakPH) {
+     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
+-                                 PN->getParent()->getFirstInsertionPt());
++                                 &*PN->getParent()->getFirstInsertionPt());
+     PN->replaceAllUsesWith(Conv);
+     RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
+   }
+@@ -998,7 +998,7 @@
+           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
+                           UsePhi);
+         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
+-        IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt());
++        IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
+         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
+         UsePhi->replaceAllUsesWith(Trunc);
+         DeadInsts.push_back(UsePhi);
+@@ -1149,7 +1149,7 @@
+   // either find an existing phi or materialize a new one. Either way, we
+   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
+   // of the phi-SCC dominates the loop entry.
+-  Instruction *InsertPt = L->getHeader()->begin();
++  Instruction *InsertPt = &L->getHeader()->front();
+   WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
+ 
+   // Remembering the WideIV increment generated by SCEVExpander allows
+@@ -1835,8 +1835,8 @@
+   BasicBlock *Preheader = L->getLoopPreheader();
+   if (!Preheader) return;
+ 
+-  Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
+-  BasicBlock::iterator I = Preheader->getTerminator();
++  Instruction *InsertPt = &*ExitBlock->getFirstInsertionPt();
++  BasicBlock::iterator I(Preheader->getTerminator());
+   while (I != Preheader->begin()) {
+     --I;
+     // New instructions were inserted at the end of the preheader.
+@@ -1889,7 +1889,7 @@
+       continue;
+ 
+     // Otherwise, sink it to the exit block.
+-    Instruction *ToMove = I;
++    Instruction *ToMove = &*I;
+     bool Done = false;
+ 
+     if (I != Preheader->begin()) {
+--- lib/Transforms/Scalar/JumpThreading.cpp	2015-01-12 19:46:47.000000000 -0800
++++ lib/Transforms/Scalar/JumpThreading.cpp	2015-11-29 07:18:33.215512385 -0800
+@@ -179,7 +179,7 @@
+   do {
+     Changed = false;
+     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
+-      BasicBlock *BB = I;
++      BasicBlock *BB = &*I;
+       // Thread all of the branches we can over this block.
+       while (ProcessBlock(BB))
+         Changed = true;
+@@ -242,7 +242,7 @@
+ static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
+                                              unsigned Threshold) {
+   /// Ignore PHI nodes, these will be flattened when duplication happens.
+-  BasicBlock::const_iterator I = BB->getFirstNonPHI();
++  BasicBlock::const_iterator I(BB->getFirstNonPHI());
+ 
+   // FIXME: THREADING will delete values that are just used to compute the
+   // branch, so they shouldn't count against the duplication cost.
+@@ -890,7 +890,7 @@
+ 
+   // Scan a few instructions up from the load, to see if it is obviously live at
+   // the entry to its block.
+-  BasicBlock::iterator BBIt = LI;
++  BasicBlock::iterator BBIt(LI);
+ 
+   if (Value *AvailableVal =
+         FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
+@@ -1019,7 +1019,7 @@
+   // Create a PHI node at the start of the block for the PRE'd load value.
+   pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
+   PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
+-                                LoadBB->begin());
++                                &LoadBB->front());
+   PN->takeName(LI);
+   PN->setDebugLoc(LI->getDebugLoc());
+ 
+@@ -1449,7 +1449,7 @@
+     Instruction *New = BI->clone();
+     New->setName(BI->getName());
+     NewBB->getInstList().push_back(New);
+-    ValueMapping[BI] = New;
++    ValueMapping[&*BI] = New;
+ 
+     // Remap operands to patch up intra-block references.
+     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
+@@ -1499,8 +1499,8 @@
+     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
+     // with the two values we know.
+     SSAUpdate.Initialize(I->getType(), I->getName());
+-    SSAUpdate.AddAvailableValue(BB, I);
+-    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
++    SSAUpdate.AddAvailableValue(BB, &*I);
++    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&*I]);
+ 
+     while (!UsesToRename.empty())
+       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
+@@ -1605,12 +1605,12 @@
+     // phi translation.
+     if (Value *IV = SimplifyInstruction(New, DL)) {
+       delete New;
+-      ValueMapping[BI] = IV;
++      ValueMapping[&*BI] = IV;
+     } else {
+       // Otherwise, insert the new instruction into the block.
+       New->setName(BI->getName());
+-      PredBB->getInstList().insert(OldPredBranch, New);
+-      ValueMapping[BI] = New;
++      PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
++      ValueMapping[&*BI] = New;
+     }
+   }
+ 
+@@ -1652,8 +1652,8 @@
+     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
+     // with the two values we know.
+     SSAUpdate.Initialize(I->getType(), I->getName());
+-    SSAUpdate.AddAvailableValue(BB, I);
+-    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
++    SSAUpdate.AddAvailableValue(BB, &*I);
++    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&*I]);
+ 
+     while (!UsesToRename.empty())
+       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
+--- lib/Transforms/Scalar/LICM.cpp	2014-12-29 15:00:57.000000000 -0800
++++ lib/Transforms/Scalar/LICM.cpp	2015-11-27 19:41:29.442793583 -0800
+@@ -573,7 +573,7 @@
+         if (!OLoop->contains(&PN)) {
+           PHINode *OpPN =
+               PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
+-                              OInst->getName() + ".lcssa", ExitBlock.begin());
++                              OInst->getName() + ".lcssa", &ExitBlock.front());
+           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
+             OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
+           *OI = OpPN;
+@@ -720,7 +720,7 @@
+             // store that.
+             PHINode *PN = PHINode::Create(
+                 I->getType(), PredCache.GetNumPreds(BB),
+-                I->getName() + ".lcssa", BB->begin());
++                I->getName() + ".lcssa", &BB->front());
+             for (BasicBlock **PI = PredCache.GetPreds(BB); *PI; ++PI)
+               PN->addIncoming(I, *PI);
+             return PN;
+@@ -916,7 +916,7 @@
+     CurLoop->getUniqueExitBlocks(ExitBlocks);
+     InsertPts.resize(ExitBlocks.size());
+     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
+-      InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
++      InsertPts[i] = &*ExitBlocks[i]->getFirstInsertionPt();
+   }
+ 
+   // We use the SSAUpdater interface to insert phi nodes as required.
+--- lib/Transforms/Scalar/LoopIdiomRecognize.cpp	2014-06-13 20:48:29.000000000 -0700
++++ lib/Transforms/Scalar/LoopIdiomRecognize.cpp	2015-11-29 07:21:21.325412485 -0800
+@@ -441,9 +441,9 @@
+   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
+   {
+     CountInst = nullptr;
+-    for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
++    for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
+            IterE = LoopEntry->end(); Iter != IterE; Iter++) {
+-      Instruction *Inst = Iter;
++      Instruction *Inst = &*Iter;
+       if (Inst->getOpcode() != Instruction::Add)
+         continue;
+ 
+@@ -571,7 +571,7 @@
+     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
+     Type *Ty = TripCnt->getType();
+ 
+-    PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
++    PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &(Body->front()));
+ 
+     Builder.SetInsertPoint(LbCond);
+     Value *Opnd1 = cast<Value>(TcPhi);
+@@ -736,10 +736,12 @@
+ 
+   bool MadeChange = false;
+   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
+-    Instruction *Inst = I++;
++    Instruction *Inst = &*I;
++    ++I;
++
+     // Look for store instructions, which may be optimized to memset/memcpy.
+     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))  {
+-      WeakVH InstPtr(I);
++      WeakVH InstPtr(&*I);
+       if (!processLoopStore(SI, BECount)) continue;
+       MadeChange = true;
+ 
+@@ -752,7 +754,7 @@
+ 
+     // Look for memset instructions, which may be optimized to a larger memset.
+     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst))  {
+-      WeakVH InstPtr(I);
++      WeakVH InstPtr(&*I);
+       if (!processLoopMemSet(MSI, BECount)) continue;
+       MadeChange = true;
+ 
+@@ -891,8 +893,7 @@
+   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
+        ++BI)
+     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
+-      if (&*I != IgnoredStore &&
+-          (AA.getModRefInfo(I, StoreLoc) & Access))
++      if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access))
+         return true;
+ 
+   return false;
+--- lib/Transforms/Scalar/LoopInstSimplify.cpp	2015-01-28 09:35:18.000000000 -0800
++++ lib/Transforms/Scalar/LoopInstSimplify.cpp	2015-11-28 15:26:59.128054267 -0800
+@@ -112,7 +112,8 @@
+ 
+       // Simplify instructions in the current basic block.
+       for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
+-        Instruction *I = BI++;
++        Instruction *I = &*BI;
++        BI++;
+ 
+         // The first time through the loop ToSimplify is empty and we try to
+         // simplify all instructions. On later iterations ToSimplify is not
+--- lib/Transforms/Scalar/LoopRerollPass.cpp	2014-10-28 04:54:52.000000000 -0700
++++ lib/Transforms/Scalar/LoopRerollPass.cpp	2015-11-29 07:34:50.826695128 -0800
+@@ -373,7 +373,7 @@
+       continue;
+ 
+     if (const SCEVAddRecExpr *PHISCEV =
+-        dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
++        dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
+       if (PHISCEV->getLoop() != L)
+         continue;
+       if (!PHISCEV->isAffine())
+@@ -387,7 +387,7 @@
+ 
+         DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
+               *PHISCEV << "\n");
+-        PossibleIVs.push_back(I);
++        PossibleIVs.push_back(&*I);
+       }
+     }
+   }
+@@ -445,7 +445,7 @@
+     if (!I->getType()->isSingleValueType())
+       continue;
+ 
+-    SimpleLoopReduction SLR(I, L);
++    SimpleLoopReduction SLR(&*I, L);
+     if (!SLR.valid())
+       continue;
+ 
+@@ -856,35 +856,36 @@
+         continue;
+       if (cast<Instruction>(J1) == IV)
+         continue;
+-      if (!BaseUseSet.count(J1))
++      if (!BaseUseSet.count(&*J1))
+         continue;
+-      if (PossibleRedPHISet.count(J1)) // Skip reduction PHIs.
++      if (PossibleRedPHISet.count(&*J1)) // Skip reduction PHIs.
+         continue;
+ 
+-      while (J2 != JE && (!RootUseSet.count(J2) ||
++      while (J2 != JE && (!RootUseSet.count(&*J2) ||
+              std::find(Roots[i].begin(), Roots[i].end(), J2) !=
+                Roots[i].end())) {
+         // As we iterate through the instructions, instructions that don't
+         // belong to previous iterations (or the base case), must belong to
+         // future iterations. We want to track the alias set of writes from
+         // previous iterations.
+-        if (!isa<PHINode>(J2) && !BaseUseSet.count(J2) &&
+-            !AllRootUses.count(J2)) {
++        if (!isa<PHINode>(J2) && !BaseUseSet.count(&*J2) &&
++            !AllRootUses.count(&*J2)) {
+           if (J2->mayWriteToMemory())
+-            AST.add(J2);
++            AST.add(&*J2);
+ 
+           // Note: This is specifically guarded by a check on isa<PHINode>,
+           // which while a valid (somewhat arbitrary) micro-optimization, is
+           // needed because otherwise isSafeToSpeculativelyExecute returns
+           // false on PHI nodes.
+-          if (!isSimpleLoadStore(J2) && !isSafeToSpeculativelyExecute(J2, DL))
++          if (!isSimpleLoadStore(&*J2) &&
++              !isSafeToSpeculativelyExecute(&*J2, DL))
+             FutureSideEffects = true;
+         }
+ 
+         ++J2;
+       }
+ 
+-      if (!J1->isSameOperationAs(J2)) {
++      if (!J1->isSameOperationAs(&*J2)) {
+         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+                         " vs. " << *J2 << "\n");
+         MatchFailed = true;
+@@ -894,7 +895,7 @@
+       // Make sure that this instruction, which is in the use set of this
+       // root instruction, does not also belong to the base set or the set of
+       // some previous root instruction.
+-      if (BaseUseSet.count(J2) || AllRootUses.count(J2)) {
++      if (BaseUseSet.count(&*J2) || AllRootUses.count(&*J2)) {
+         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+                         " vs. " << *J2 << " (prev. case overlap)\n");
+         MatchFailed = true;
+@@ -907,7 +908,7 @@
+       if (J2->mayReadFromMemory()) {
+         for (AliasSetTracker::iterator K = AST.begin(), KE = AST.end();
+              K != KE && !MatchFailed; ++K) {
+-          if (K->aliasesUnknownInst(J2, *AA)) {
++          if (K->aliasesUnknownInst(&*J2, *AA)) {
+             DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+                             " vs. " << *J2 << " (depends on future store)\n");
+             MatchFailed = true;
+@@ -921,10 +922,10 @@
+       // them, and this matching fails. As an exception, we allow the alias
+       // set tracker to handle regular (simple) load/store dependencies.
+       if (FutureSideEffects &&
+-            ((!isSimpleLoadStore(J1) &&
+-              !isSafeToSpeculativelyExecute(J1, DL)) ||
+-             (!isSimpleLoadStore(J2) &&
+-              !isSafeToSpeculativelyExecute(J2, DL)))) {
++            ((!isSimpleLoadStore(&*J1) &&
++              !isSafeToSpeculativelyExecute(&*J1, &*DL)) ||
++             (!isSimpleLoadStore(&*J2) &&
++              !isSafeToSpeculativelyExecute(&*J2, &*DL)))) {
+         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+                         " vs. " << *J2 <<
+                         " (side effects prevent reordering)\n");
+@@ -942,7 +943,7 @@
+       //   x += a[i]; x += b[i];
+       //   x += a[i+1]; x += b[i+1];
+       //   x += b[i+2]; x += a[i+2];
+-      bool InReduction = Reductions.isPairInSame(J1, J2);
++      bool InReduction = Reductions.isPairInSame(&*J1, &*J2);
+ 
+       if (!(InReduction && J1->isAssociative())) {
+         bool Swapped = false, SomeOpMatched = false;
+@@ -954,7 +955,7 @@
+           // part of the reduction.
+           if (InReduction)
+             if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
+-              if (Reductions.isPairInSame(J2, Op2I))
++              if (Reductions.isPairInSame(&*J2, Op2I))
+                 continue;
+ 
+           DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
+@@ -985,8 +986,8 @@
+         }
+       }
+ 
+-      if ((!PossibleRedLastSet.count(J1) && hasUsesOutsideLoop(J1, L)) ||
+-          (!PossibleRedLastSet.count(J2) && hasUsesOutsideLoop(J2, L))) {
++      if ((!PossibleRedLastSet.count(&*J1) && hasUsesOutsideLoop(&*J1, L)) ||
++          (!PossibleRedLastSet.count(&*J2) && hasUsesOutsideLoop(&*J2, L))) {
+         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+                         " vs. " << *J2 << " (uses outside loop)\n");
+         MatchFailed = true;
+@@ -994,10 +995,10 @@
+       }
+ 
+       if (!MatchFailed)
+-        BaseMap.insert(std::pair<Value *, Value *>(J2, J1));
++        BaseMap.insert(std::pair<Value *, Value *>(&*J2, &*J1));
+ 
+-      AllRootUses.insert(J2);
+-      Reductions.recordPair(J1, J2, i+1);
++      AllRootUses.insert(&*J2);
++      Reductions.recordPair(&*J1, &*J2, i+1);
+ 
+       ++J2;
+     }
+@@ -1025,15 +1026,15 @@
+       continue;
+     if (cast<Instruction>(J) == IV)
+       continue;
+-    if (BaseUseSet.count(J) || AllRootUses.count(J) ||
+-        (LoopIncUseSet.count(J) && (J->isTerminator() ||
+-                                    isSafeToSpeculativelyExecute(J, DL))))
++    if (BaseUseSet.count(&*J) || AllRootUses.count(&*J) ||
++        (LoopIncUseSet.count(&*J) && (J->isTerminator() ||
++                                    isSafeToSpeculativelyExecute(&*J, &*DL))))
+       continue;
+ 
+-    if (AllRoots.count(J))
++    if (AllRoots.count(&*J))
+       continue;
+ 
+-    if (Reductions.isSelectedPHI(J))
++    if (Reductions.isSelectedPHI(&*J))
+       continue;
+ 
+     DEBUG(dbgs() << "LRR: aborting reroll based on " << *RealIV <<
+@@ -1080,7 +1081,7 @@
+                            L, SCEV::FlagAnyWrap));
+   { // Limit the lifetime of SCEVExpander.
+     SCEVExpander Expander(*SE, "reroll");
+-    Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
++    Value *NewIV = Expander.expandCodeFor(H, IV->getType(), &(Header->front()));
+ 
+     for (DenseSet<Instruction *>::iterator J = BaseUseSet.begin(),
+          JE = BaseUseSet.end(); J != JE; ++J)
+--- lib/Transforms/Scalar/LoopRotation.cpp	2015-03-09 13:26:36.000000000 -0700
++++ lib/Transforms/Scalar/LoopRotation.cpp	2015-11-29 08:53:24.120179108 -0800
+@@ -141,7 +141,7 @@
+   // as necessary.
+   SSAUpdater SSA;
+   for (I = OrigHeader->begin(); I != E; ++I) {
+-    Value *OrigHeaderVal = I;
++    Value *OrigHeaderVal = &*I;
+ 
+     // If there are no uses of the value (e.g. because it returns void), there
+     // is nothing to rewrite.
+@@ -203,8 +203,7 @@
+     MultiExitLoop = true;
+ 
+   for (BasicBlock::iterator I = Begin; I != End; ++I) {
+-
+-    if (!isSafeToSpeculativelyExecute(I))
++    if (!isSafeToSpeculativelyExecute(&*I))
+       return false;
+ 
+     if (isa<DbgInfoIntrinsic>(I))
+@@ -287,14 +286,15 @@
+   if (!BI)
+     return false;
+ 
+-  if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
++  if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
+     return false;
+ 
+   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
+         << LastExit->getName() << "\n");
+ 
+   // Hoist the instructions from Latch into LastExit.
+-  LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
++  LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
++                                 Latch->begin(), Jmp->getIterator());
+ 
+   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
+   BasicBlock *Header = Jmp->getSuccessor(0);
+@@ -416,7 +416,8 @@
+   // possible or create a clone in the OldPreHeader if not.
+   TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
+   while (I != E) {
+-    Instruction *Inst = I++;
++    Instruction *Inst = &*I;
++    ++I;
+ 
+     // If the instruction's operands are invariant and it doesn't read or write
+     // memory, then it is safe to hoist.  Doing this doesn't change the order of
+--- lib/Transforms/Scalar/LoopStrengthReduce.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/LoopStrengthReduce.cpp	2015-11-29 08:54:51.641136545 -0800
+@@ -1933,9 +1933,10 @@
+       // NOTE: we could handle setcc instructions with multiple uses here, but
+       // InstCombine does it as well for simple uses, it's not clear that it
+       // occurs enough in real life to handle.
+-      CondUse = UI;
++      CondUse = &*UI;
+       return true;
+     }
++
+   return false;
+ }
+ 
+@@ -2203,7 +2204,7 @@
+         ICmpInst *OldCond = Cond;
+         Cond = cast<ICmpInst>(Cond->clone());
+         Cond->setName(L->getHeader()->getName() + ".termcond");
+-        ExitingBlock->getInstList().insert(TermBr, Cond);
++        ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond);
+ 
+         // Clone the IVUse, as the old use still exists!
+         CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
+@@ -2782,20 +2783,21 @@
+     for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
+          I != E; ++I) {
+       // Skip instructions that weren't seen by IVUsers analysis.
+-      if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
++      if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&*I))
+         continue;
+ 
+       // Ignore users that are part of a SCEV expression. This way we only
+       // consider leaf IV Users. This effectively rediscovers a portion of
+       // IVUsers analysis but in program order this time.
+-      if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
++      if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(&*I)))
+         continue;
+ 
+       // Remove this instruction from any NearUsers set it may be in.
+       for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
+            ChainIdx < NChains; ++ChainIdx) {
+-        ChainUsersVec[ChainIdx].NearUsers.erase(I);
++        ChainUsersVec[ChainIdx].NearUsers.erase(&*I);
+       }
++
+       // Search for operands that can be chained.
+       SmallPtrSet<Instruction*, 4> UniqueOperands;
+       User::op_iterator IVOpEnd = I->op_end();
+@@ -2803,7 +2805,7 @@
+       while (IVOpIter != IVOpEnd) {
+         Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
+         if (UniqueOperands.insert(IVOpInst).second)
+-          ChainInstruction(I, IVOpInst, ChainUsersVec);
++          ChainInstruction(&*I, IVOpInst, ChainUsersVec);
+         IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
+       }
+     } // Continue walking down the instructions.
+@@ -4437,14 +4439,14 @@
+       // instead of at the end, so that it can be used for other expansions.
+       if (IDom == Inst->getParent() &&
+           (!BetterPos || !DT.dominates(Inst, BetterPos)))
+-        BetterPos = std::next(BasicBlock::iterator(Inst));
++        BetterPos = &(*std::next(BasicBlock::iterator(Inst)));
+     }
+     if (!AllDominate)
+       break;
+     if (BetterPos)
+-      IP = BetterPos;
++      IP = BetterPos->getIterator();
+     else
+-      IP = Tentative;
++      IP = Tentative->getIterator();
+   }
+ 
+   return IP;
+@@ -4511,7 +4513,8 @@
+   // Set IP below instructions recently inserted by SCEVExpander. This keeps the
+   // IP consistent across expansions and allows the previously inserted
+   // instructions to be reused by subsequent expansion.
+-  while (Rewriter.isInsertedInstruction(IP) && IP != LowestIP) ++IP;
++  while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)
++    ++IP;
+ 
+   return IP;
+ }
+@@ -4563,7 +4566,7 @@
+                                  LF.UserInst, LF.OperandValToReplace,
+                                  Loops, SE, DT);
+ 
+-    Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, IP)));
++    Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, &*IP)));
+   }
+ 
+   // Expand the ScaledReg portion.
+@@ -4581,14 +4584,14 @@
+       // Expand ScaleReg as if it was part of the base regs.
+       if (F.Scale == 1)
+         Ops.push_back(
+-            SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP)));
++            SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, &*IP)));
+       else {
+         // An interesting way of "folding" with an icmp is to use a negated
+         // scale, which we'll implement by inserting it into the other operand
+         // of the icmp.
+         assert(F.Scale == -1 &&
+                "The only scale supported by ICmpZero uses is -1!");
+-        ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, IP);
++        ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, &*IP);
+       }
+     } else {
+       // Otherwise just expand the scaled register and an explicit scale,
+@@ -4598,11 +4601,11 @@
+       // Unless the addressing mode will not be folded.
+       if (!Ops.empty() && LU.Kind == LSRUse::Address &&
+           isAMCompletelyFolded(TTI, LU, F)) {
+-        Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
++        Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, &*IP);
+         Ops.clear();
+         Ops.push_back(SE.getUnknown(FullV));
+       }
+-      ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP));
++      ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, &*IP));
+       if (F.Scale != 1)
+         ScaledS =
+             SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
+@@ -4614,7 +4617,7 @@
+   if (F.BaseGV) {
+     // Flush the operand list to suppress SCEVExpander hoisting.
+     if (!Ops.empty()) {
+-      Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
++      Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, &*IP);
+       Ops.clear();
+       Ops.push_back(SE.getUnknown(FullV));
+     }
+@@ -4624,7 +4627,7 @@
+   // Flush the operand list to suppress SCEVExpander hoisting of both folded and
+   // unfolded offsets. LSR assumes they both live next to their uses.
+   if (!Ops.empty()) {
+-    Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
++    Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, &*IP);
+     Ops.clear();
+     Ops.push_back(SE.getUnknown(FullV));
+   }
+@@ -4636,7 +4639,7 @@
+       // The other interesting way of "folding" with an ICmpZero is to use a
+       // negated immediate.
+       if (!ICmpScaledV)
+-        ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
++        ICmpScaledV = ConstantInt::get(IntTy, -((uint64_t) Offset));
+       else {
+         Ops.push_back(SE.getUnknown(ICmpScaledV));
+         ICmpScaledV = ConstantInt::get(IntTy, Offset);
+@@ -4660,7 +4663,7 @@
+   const SCEV *FullS = Ops.empty() ?
+                       SE.getConstant(IntTy, 0) :
+                       SE.getAddExpr(Ops);
+-  Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
++  Value *FullV = Rewriter.expandCodeFor(FullS, Ty, &*IP);
+ 
+   // We're done expanding now, so reset the rewriter.
+   Rewriter.clearPostInc();
+@@ -4759,7 +4762,8 @@
+       if (!Pair.second)
+         PN->setIncomingValue(i, Pair.first->second);
+       else {
+-        Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
++        Value *FullV = Expand(LF, F, BB->getTerminator()->getIterator(),
++                              Rewriter, DeadInsts);
+ 
+         // If this is reuse-by-noop-cast, insert the noop cast.
+         Type *OpTy = LF.OperandValToReplace->getType();
+@@ -4789,7 +4793,8 @@
+   if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
+     RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
+   } else {
+-    Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
++    Value *FullV =
++      Expand(LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts);
+ 
+     // If this is reuse-by-noop-cast, insert the noop cast.
+     Type *OpTy = LF.OperandValToReplace->getType();
+--- lib/Transforms/Scalar/LoopUnswitch.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Scalar/LoopUnswitch.cpp	2015-11-28 17:55:30.857922905 -0800
+@@ -737,7 +737,7 @@
+   // without actually branching to it (the exit block should be dominated by the
+   // loop header, not the preheader).
+   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
+-  BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
++  BasicBlock *NewExit = SplitBlock(ExitBlock, &(ExitBlock->front()), this);
+ 
+   // Okay, now we have a position to branch from and a position to branch to,
+   // insert the new conditional branch.
+@@ -832,8 +832,9 @@
+ 
+   // Splice the newly inserted blocks into the function right before the
+   // original preheader.
+-  F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
+-                                NewBlocks[0], F->end());
++  F->getBasicBlockList().splice(NewPreheader->getIterator(),
++                                F->getBasicBlockList(),
++                                NewBlocks[0]->getIterator(), F->end());
+ 
+   // FIXME: We could register any cloned assumptions instead of clearing the
+   // whole function's cache.
+@@ -875,7 +876,7 @@
+ 
+     if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
+       PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
+-                                    ExitSucc->getFirstInsertionPt());
++                                    &*ExitSucc->getFirstInsertionPt());
+ 
+       for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
+            I != E; ++I) {
+@@ -891,7 +892,8 @@
+   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
+     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
+            E = NewBlocks[i]->end(); I != E; ++I)
+-      RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
++      RemapInstruction(&*I, VMap,
++                       RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
+ 
+   // Rewrite the original preheader to select between versions of the loop.
+   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
+@@ -1136,8 +1138,9 @@
+         Succ->replaceAllUsesWith(Pred);
+ 
+         // Move all of the successor contents from Succ to Pred.
+-        Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
+-                                   Succ->end());
++        Pred->getInstList().splice(BI->getIterator(),
++                                   Succ->getInstList(),
++                                   Succ->begin(), Succ->end());
+         LPM->deleteSimpleAnalysisValue(BI, L);
+         BI->eraseFromParent();
+         RemoveFromWorklist(BI, Worklist);
+--- lib/Transforms/Scalar/LowerAtomic.cpp	2014-06-13 07:24:07.000000000 -0700
++++ lib/Transforms/Scalar/LowerAtomic.cpp	2015-11-28 17:57:32.665949990 -0800
+@@ -22,7 +22,7 @@
+ #define DEBUG_TYPE "loweratomic"
+ 
+ static bool LowerAtomicCmpXchgInst(AtomicCmpXchgInst *CXI) {
+-  IRBuilder<> Builder(CXI->getParent(), CXI);
++  IRBuilder<> Builder(CXI);
+   Value *Ptr = CXI->getPointerOperand();
+   Value *Cmp = CXI->getCompareOperand();
+   Value *Val = CXI->getNewValOperand();
+@@ -41,7 +41,7 @@
+ }
+ 
+ static bool LowerAtomicRMWInst(AtomicRMWInst *RMWI) {
+-  IRBuilder<> Builder(RMWI->getParent(), RMWI);
++  IRBuilder<> Builder(RMWI);
+   Value *Ptr = RMWI->getPointerOperand();
+   Value *Val = RMWI->getValOperand();
+ 
+@@ -120,7 +120,8 @@
+         return false;
+       bool Changed = false;
+       for (BasicBlock::iterator DI = BB.begin(), DE = BB.end(); DI != DE; ) {
+-        Instruction *Inst = DI++;
++        Instruction *Inst = &*DI;
++        ++DI;
+         if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
+           Changed |= LowerFenceInst(FI);
+         else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(Inst))
+--- lib/Transforms/Scalar/MemCpyOptimizer.cpp	2015-02-07 11:39:14.000000000 -0800
++++ lib/Transforms/Scalar/MemCpyOptimizer.cpp	2015-11-28 18:08:18.813257513 -0800
+@@ -385,7 +385,7 @@
+   // are stored.
+   MemsetRanges Ranges(*DL);
+ 
+-  BasicBlock::iterator BI = StartInst;
++  BasicBlock::iterator BI(StartInst);
+   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
+     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
+       // If the instruction is readnone, ignore it, otherwise bail out.  We
+@@ -440,7 +440,7 @@
+   // If we create any memsets, we put it right before the first instruction that
+   // isn't part of the memset block.  This ensure that the memset is dominated
+   // by any addressing instruction needed by the start of the block.
+-  IRBuilder<> Builder(BI);
++  IRBuilder<> Builder(&*BI);
+ 
+   // Now that we have full information about ranges, loop over the ranges and
+   // emit memset's for anything big enough to be worthwhile.
+@@ -513,8 +513,8 @@
+         // the call and the store.
+         AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
+         AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
+-        for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
+-                                  E = C; I != E; --I) {
++        for (BasicBlock::iterator I = --SI->getIterator(),
++                                  E = C->getIterator(); I != E; --I) {
+           if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
+             C = nullptr;
+             break;
+@@ -556,7 +556,7 @@
+   if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
+     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
+                                               ByteVal)) {
+-      BBI = I;  // Don't invalidate iterator.
++      BBI = I->getIterator();  // Don't invalidate iterator.
+       return true;
+     }
+ 
+@@ -569,7 +569,7 @@
+   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
+     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
+                                               MSI->getValue())) {
+-      BBI = I;  // Don't invalidate iterator.
++      BBI = I->getIterator();  // Don't invalidate iterator.
+       return true;
+     }
+   return false;
+@@ -808,8 +808,8 @@
+   // NOTE: This is conservative, it will stop on any read from the source loc,
+   // not just the defining memcpy.
+   MemDepResult SourceDep =
+-    MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
+-                                 false, M, M->getParent());
++    MD->getPointerDependencyFrom(AA.getLocationForSource(MDep), false,
++                                 M->getIterator(), M->getParent());
+   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
+     return false;
+ 
+@@ -898,8 +898,9 @@
+   }
+ 
+   AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
+-  MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
+-                                                         M, M->getParent());
++  MemDepResult SrcDepInfo =
++    MD->getPointerDependencyFrom(SrcLoc, true,
++                                 M->getIterator(), M->getParent());
+   if (SrcDepInfo.isClobber()) {
+     if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
+       return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
+@@ -967,7 +968,8 @@
+   uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
+   MemDepResult DepInfo =
+     MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
+-                                 true, CS.getInstruction(),
++                                 true,
++                                 CS.getInstruction()->getIterator(),
+                                  CS.getInstruction()->getParent());
+   if (!DepInfo.isClobber())
+     return false;
+@@ -1012,7 +1014,9 @@
+   // not just the defining memcpy.
+   MemDepResult SourceDep =
+     MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
+-                                 false, CS.getInstruction(), MDep->getParent());
++                                 false,
++                                 CS.getInstruction()->getIterator(),
++                                 MDep->getParent());
+   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
+     return false;
+ 
+@@ -1039,7 +1043,8 @@
+   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
+     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
+       // Avoid invalidating the iterator.
+-      Instruction *I = BI++;
++      Instruction *I = &*BI;
++      ++BI;
+ 
+       bool RepeatInstruction = false;
+ 
+--- lib/Transforms/Scalar/MergedLoadStoreMotion.cpp	2015-02-17 14:03:58.000000000 -0800
++++ lib/Transforms/Scalar/MergedLoadStoreMotion.cpp	2015-11-28 18:11:58.690419443 -0800
+@@ -256,7 +256,7 @@
+ 
+   for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
+        ++BBI) {
+-    Instruction *Inst = BBI;
++    Instruction *Inst = &*BBI;
+ 
+     // Only merge and hoist loads when their result in used only in BB
+     if (!isa<LoadInst>(Inst) || Inst->isUsedOutsideOfBlock(BB1))
+@@ -367,8 +367,7 @@
+   int NLoads = 0;
+   for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
+        BBI != BBE;) {
+-
+-    Instruction *I = BBI;
++    Instruction *I = &*BBI;
+     ++BBI;
+ 
+     // Only move non-simple (atomic, volatile) loads.
+@@ -448,7 +447,7 @@
+   Value *Opd2 = S1->getValueOperand();
+   if (Opd1 != Opd2) {
+     NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
+-                            BB->begin());
++                            &BB->front());
+     NewPN->addIncoming(Opd1, S0->getParent());
+     NewPN->addIncoming(Opd2, S1->getParent());
+     if (NewPN->getType()->getScalarType()->isPointerTy()) {
+@@ -493,7 +492,7 @@
+     StoreInst *SNew = (StoreInst *)(S0->clone());
+     Instruction *ANew = A0->clone();
+     AA->copyValue(S0, SNew);
+-    SNew->insertBefore(InsertPt);
++    SNew->insertBefore(&*InsertPt);
+     ANew->insertBefore(SNew);
+ 
+     assert(S0->getParent() == A0->getParent());
+@@ -588,7 +587,8 @@
+   // Merge unconditional branches, allowing PRE to catch more
+   // optimization opportunities.
+   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
+-    BasicBlock *BB = FI++;
++    BasicBlock *BB = &*FI;
++    ++FI;
+ 
+     // Hoist equivalent loads and sink stores
+     // outside diamonds when possible
+--- lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp	2014-08-01 16:21:21.000000000 -0700
++++ lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp	2015-11-28 18:13:26.025414765 -0800
+@@ -152,7 +152,7 @@
+   Phi->addIncoming(Call, &CurrBB);
+   Phi->addIncoming(LibCall, LibCallBB);
+ 
+-  BB = JoinBB;
++  BB = JoinBB->getIterator();
+   return true;
+ }
+ 
+--- lib/Transforms/Scalar/Reassociate.cpp	2014-12-12 06:44:12.000000000 -0800
++++ lib/Transforms/Scalar/Reassociate.cpp	2015-11-29 08:56:09.229859750 -0800
+@@ -295,7 +295,7 @@
+     // we cannot move.  This ensures that the ranks for these instructions are
+     // all different in the block.
+     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
+-      if (isUnmovableInstruction(I))
++      if (isUnmovableInstruction(&*I))
+         ValueRankMap[&*I] = ++BBRank;
+   }
+ }
+@@ -968,14 +968,14 @@
+       if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
+         InsertPt = II->getNormalDest()->begin();
+       } else {
+-        InsertPt = InstInput;
+-        ++InsertPt;
++        InsertPt = ++InstInput->getIterator();
+       }
+       while (isa<PHINode>(InsertPt)) ++InsertPt;
+     } else {
+       InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
+     }
+-    TheNeg->moveBefore(InsertPt);
++
++    TheNeg->moveBefore(&*InsertPt);
+     return TheNeg;
+   }
+ 
+@@ -1160,7 +1160,7 @@
+     return nullptr;
+   }
+ 
+-  BasicBlock::iterator InsertPt = BO; ++InsertPt;
++  BasicBlock::iterator InsertPt = ++BO->getIterator();
+ 
+   // If this was just a single multiply, remove the multiply and return the only
+   // remaining operand.
+@@ -1173,7 +1173,7 @@
+   }
+ 
+   if (NeedsNegate)
+-    V = CreateNeg(V, "neg", InsertPt, BO);
++    V = CreateNeg(V, "neg", &*InsertPt, BO);
+ 
+   return V;
+ }
+@@ -2262,10 +2262,10 @@
+   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
+     // Optimize every instruction in the basic block.
+     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; )
+-      if (isInstructionTriviallyDead(II)) {
+-        EraseInst(II++);
++      if (isInstructionTriviallyDead(&*II)) {
++        EraseInst(&*II++);
+       } else {
+-        OptimizeInst(II);
++        OptimizeInst(&*II);
+         assert(II->getParent() == BI && "Moved to a different block!");
+         ++II;
+       }
+--- lib/Transforms/Scalar/Reg2Mem.cpp	2015-01-12 19:46:47.000000000 -0800
++++ lib/Transforms/Scalar/Reg2Mem.cpp	2015-11-28 18:22:35.790368260 -0800
+@@ -85,7 +85,7 @@
+   CastInst *AllocaInsertionPoint =
+     new BitCastInst(Constant::getNullValue(Type::getInt32Ty(F.getContext())),
+                     Type::getInt32Ty(F.getContext()),
+-                    "reg2mem alloca point", I);
++                    "reg2mem alloca point", &*I);
+ 
+   // Find the escaped instructions. But don't create stack slots for
+   // allocas in entry block.
+@@ -95,7 +95,7 @@
+     for (BasicBlock::iterator iib = ibb->begin(), iie = ibb->end();
+          iib != iie; ++iib) {
+       if (!(isa<AllocaInst>(iib) && iib->getParent() == BBEntry) &&
+-          valueEscapes(iib)) {
++          valueEscapes(&*iib)) {
+         WorkList.push_front(&*iib);
+       }
+     }
+--- lib/Transforms/Scalar/SCCP.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/SCCP.cpp	2015-11-28 19:12:24.103813993 -0800
+@@ -1125,7 +1125,7 @@
+   // entry block executable and merge in the actual arguments to the call into
+   // the formal arguments of the function.
+   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
+-    MarkBlockExecutable(F->begin());
++    MarkBlockExecutable(&F->front());
+ 
+     // Propagate information from this call site into the callee.
+     CallSite::arg_iterator CAI = CS.arg_begin();
+@@ -1134,17 +1134,17 @@
+       // If this argument is byval, and if the function is not readonly, there
+       // will be an implicit copy formed of the input aggregate.
+       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
+-        markOverdefined(AI);
++        markOverdefined(&*AI);
+         continue;
+       }
+ 
+       if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
+         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
+           LatticeVal CallArg = getStructValueState(*CAI, i);
+-          mergeInValue(getStructValueState(AI, i), AI, CallArg);
++          mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
+         }
+       } else {
+-        mergeInValue(AI, getValueState(*CAI));
++        mergeInValue(&*AI, getValueState(*CAI));
+       }
+     }
+   }
+@@ -1245,18 +1245,18 @@
+ /// even if X isn't defined.
+ bool SCCPSolver::ResolvedUndefsIn(Function &F) {
+   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
+-    if (!BBExecutable.count(BB))
++    if (!BBExecutable.count(&*BB))
+       continue;
+ 
+-    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
++    for (Instruction &I : *BB) {
+       // Look for instructions which produce undef values.
+-      if (I->getType()->isVoidTy()) continue;
++      if (I.getType()->isVoidTy()) continue;
+ 
+-      if (StructType *STy = dyn_cast<StructType>(I->getType())) {
++      if (StructType *STy = dyn_cast<StructType>(I.getType())) {
+         // Only a few things that can be structs matter for undef.
+ 
+         // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
+-        if (CallSite CS = CallSite(I))
++        if (CallSite CS = CallSite(&I))
+           if (Function *F = CS.getCalledFunction())
+             if (MRVFunctionsTracked.count(F))
+               continue;
+@@ -1269,14 +1269,14 @@
+         // Send the results of everything else to overdefined.  We could be
+         // more precise than this but it isn't worth bothering.
+         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
+-          LatticeVal &LV = getStructValueState(I, i);
++          LatticeVal &LV = getStructValueState(&I, i);
+           if (LV.isUndefined())
+-            markOverdefined(LV, I);
++            markOverdefined(LV, &I);
+         }
+         continue;
+       }
+ 
+-      LatticeVal &LV = getValueState(I);
++      LatticeVal &LV = getValueState(&I);
+       if (!LV.isUndefined()) continue;
+ 
+       // extractvalue is safe; check here because the argument is a struct.
+@@ -1286,24 +1286,24 @@
+       // Compute the operand LatticeVals, for convenience below.
+       // Anything taking a struct is conservatively assumed to require
+       // overdefined markings.
+-      if (I->getOperand(0)->getType()->isStructTy()) {
+-        markOverdefined(I);
++      if (I.getOperand(0)->getType()->isStructTy()) {
++        markOverdefined(&I);
+         return true;
+       }
+-      LatticeVal Op0LV = getValueState(I->getOperand(0));
++      LatticeVal Op0LV = getValueState(I.getOperand(0));
+       LatticeVal Op1LV;
+-      if (I->getNumOperands() == 2) {
+-        if (I->getOperand(1)->getType()->isStructTy()) {
+-          markOverdefined(I);
++      if (I.getNumOperands() == 2) {
++        if (I.getOperand(1)->getType()->isStructTy()) {
++          markOverdefined(&I);
+           return true;
+         }
+ 
+-        Op1LV = getValueState(I->getOperand(1));
++        Op1LV = getValueState(I.getOperand(1));
+       }
+       // If this is an instructions whose result is defined even if the input is
+       // not fully defined, propagate the information.
+-      Type *ITy = I->getType();
+-      switch (I->getOpcode()) {
++      Type *ITy = I.getType();
++      switch (I.getOpcode()) {
+       case Instruction::Add:
+       case Instruction::Sub:
+       case Instruction::Trunc:
+@@ -1317,9 +1317,9 @@
+       case Instruction::FRem:
+         // Floating-point binary operation: be conservative.
+         if (Op0LV.isUndefined() && Op1LV.isUndefined())
+-          markForcedConstant(I, Constant::getNullValue(ITy));
++          markForcedConstant(&I, Constant::getNullValue(ITy));
+         else
+-          markOverdefined(I);
++          markOverdefined(&I);
+         return true;
+       case Instruction::ZExt:
+       case Instruction::SExt:
+@@ -1331,7 +1331,7 @@
+       case Instruction::SIToFP:
+       case Instruction::UIToFP:
+         // undef -> 0; some outputs are impossible
+-        markForcedConstant(I, Constant::getNullValue(ITy));
++        markForcedConstant(&I, Constant::getNullValue(ITy));
+         return true;
+       case Instruction::Mul:
+       case Instruction::And:
+@@ -1340,7 +1340,7 @@
+           break;
+         // undef * X -> 0.   X could be zero.
+         // undef & X -> 0.   X could be zero.
+-        markForcedConstant(I, Constant::getNullValue(ITy));
++        markForcedConstant(&I, Constant::getNullValue(ITy));
+         return true;
+ 
+       case Instruction::Or:
+@@ -1348,7 +1348,7 @@
+         if (Op0LV.isUndefined() && Op1LV.isUndefined())
+           break;
+         // undef | X -> -1.   X could be -1.
+-        markForcedConstant(I, Constant::getAllOnesValue(ITy));
++        markForcedConstant(&I, Constant::getAllOnesValue(ITy));
+         return true;
+ 
+       case Instruction::Xor:
+@@ -1356,7 +1356,7 @@
+         // necessary, but we try to be nice to people who expect this
+         // behavior in simple cases
+         if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
+-          markForcedConstant(I, Constant::getNullValue(ITy));
++          markForcedConstant(&I, Constant::getNullValue(ITy));
+           return true;
+         }
+         // undef ^ X -> undef
+@@ -1372,7 +1372,7 @@
+ 
+         // undef / X -> 0.   X could be maxint.
+         // undef % X -> 0.   X could be 1.
+-        markForcedConstant(I, Constant::getNullValue(ITy));
++        markForcedConstant(&I, Constant::getNullValue(ITy));
+         return true;
+ 
+       case Instruction::AShr:
+@@ -1380,7 +1380,7 @@
+         if (Op1LV.isUndefined()) break;
+ 
+         // undef >>a X -> all ones
+-        markForcedConstant(I, Constant::getAllOnesValue(ITy));
++        markForcedConstant(&I, Constant::getAllOnesValue(ITy));
+         return true;
+       case Instruction::LShr:
+       case Instruction::Shl:
+@@ -1390,17 +1390,17 @@
+ 
+         // undef << X -> 0
+         // undef >> X -> 0
+-        markForcedConstant(I, Constant::getNullValue(ITy));
++        markForcedConstant(&I, Constant::getNullValue(ITy));
+         return true;
+       case Instruction::Select:
+-        Op1LV = getValueState(I->getOperand(1));
++        Op1LV = getValueState(I.getOperand(1));
+         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
+         if (Op0LV.isUndefined()) {
+           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
+-            Op1LV = getValueState(I->getOperand(2));
++            Op1LV = getValueState(I.getOperand(2));
+         } else if (Op1LV.isUndefined()) {
+           // c ? undef : undef -> undef.  No change.
+-          Op1LV = getValueState(I->getOperand(2));
++          Op1LV = getValueState(I.getOperand(2));
+           if (Op1LV.isUndefined())
+             break;
+           // Otherwise, c ? undef : x -> x.
+@@ -1409,9 +1409,9 @@
+         }
+ 
+         if (Op1LV.isConstant())
+-          markForcedConstant(I, Op1LV.getConstant());
++          markForcedConstant(&I, Op1LV.getConstant());
+         else
+-          markOverdefined(I);
++          markOverdefined(&I);
+         return true;
+       case Instruction::Load:
+         // A load here means one of two things: a load of undef from a global,
+@@ -1420,9 +1420,9 @@
+         break;
+       case Instruction::ICmp:
+         // X == undef -> undef.  Other comparisons get more complicated.
+-        if (cast<ICmpInst>(I)->isEquality())
++        if (cast<ICmpInst>(&I)->isEquality())
+           break;
+-        markOverdefined(I);
++        markOverdefined(&I);
+         return true;
+       case Instruction::Call:
+       case Instruction::Invoke: {
+@@ -1431,19 +1431,19 @@
+         // 2. It could be constant-foldable.
+         // Because of the way we solve return values, tracked calls must
+         // never be marked overdefined in ResolvedUndefsIn.
+-        if (Function *F = CallSite(I).getCalledFunction())
++        if (Function *F = CallSite(&I).getCalledFunction())
+           if (TrackedRetVals.count(F))
+             break;
+ 
+         // If the call is constant-foldable, we mark it overdefined because
+         // we do not know what return values are valid.
+-        markOverdefined(I);
++        markOverdefined(&I);
+         return true;
+       }
+       default:
+         // If we don't know what should happen here, conservatively mark it
+         // overdefined.
+-        markOverdefined(I);
++        markOverdefined(&I);
+         return true;
+       }
+     }
+@@ -1461,7 +1461,7 @@
+       // false.
+       if (isa<UndefValue>(BI->getCondition())) {
+         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
+-        markEdgeExecutable(BB, TI->getSuccessor(1));
++        markEdgeExecutable(&*BB, TI->getSuccessor(1));
+         return true;
+       }
+ 
+@@ -1483,7 +1483,7 @@
+       // the first constant.
+       if (isa<UndefValue>(SI->getCondition())) {
+         SI->setCondition(SI->case_begin().getCaseValue());
+-        markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
++        markEdgeExecutable(&*BB, SI->case_begin().getCaseSuccessor());
+         return true;
+       }
+ 
+@@ -1540,8 +1540,7 @@
+   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
+   while (EndInst != BB->begin()) {
+     // Delete the next to last instruction.
+-    BasicBlock::iterator I = EndInst;
+-    Instruction *Inst = --I;
++    Instruction *Inst = &*--EndInst->getIterator();
+     if (!Inst->use_empty())
+       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
+     if (isa<LandingPadInst>(Inst)) {
+@@ -1567,11 +1566,11 @@
+   SCCPSolver Solver(DL, TLI);
+ 
+   // Mark the first block of the function as being executable.
+-  Solver.MarkBlockExecutable(F.begin());
++  Solver.MarkBlockExecutable(&F.front());
+ 
+   // Mark all arguments to the function as being overdefined.
+-  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
+-    Solver.markAnythingOverdefined(AI);
++  for (Argument &AI : F.args())
++    Solver.markAnythingOverdefined(&AI);
+ 
+   // Solve for constants.
+   bool ResolvedUndefs = true;
+@@ -1588,8 +1587,8 @@
+   // as we cannot modify the CFG of the function.
+ 
+   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
+-    if (!Solver.isBlockExecutable(BB)) {
+-      DeleteInstructionInBlock(BB);
++    if (!Solver.isBlockExecutable(&*BB)) {
++      DeleteInstructionInBlock(&*BB);
+       MadeChanges = true;
+       continue;
+     }
+@@ -1598,7 +1597,7 @@
+     // constants if we have found them to be of constant values.
+     //
+     for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
+-      Instruction *Inst = BI++;
++      Instruction *Inst = &*BI++;
+       if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
+         continue;
+ 
+@@ -1712,36 +1711,34 @@
+     // If this is a strong or ODR definition of this function, then we can
+     // propagate information about its result into callsites of it.
+     if (!F->mayBeOverridden())
+-      Solver.AddTrackedFunction(F);
++      Solver.AddTrackedFunction(&*F);
+ 
+     // If this function only has direct calls that we can see, we can track its
+     // arguments and return value aggressively, and can assume it is not called
+     // unless we see evidence to the contrary.
+     if (F->hasLocalLinkage()) {
+-      if (AddressIsTaken(F))
+-        AddressTakenFunctions.insert(F);
++      if (AddressIsTaken(&*F))
++        AddressTakenFunctions.insert(&*F);
+       else {
+-        Solver.AddArgumentTrackedFunction(F);
++        Solver.AddArgumentTrackedFunction(&*F);
+         continue;
+       }
+     }
+ 
+     // Assume the function is called.
+-    Solver.MarkBlockExecutable(F->begin());
++    Solver.MarkBlockExecutable(&F->front());
+ 
+     // Assume nothing about the incoming arguments.
+-    for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
+-         AI != E; ++AI)
+-      Solver.markAnythingOverdefined(AI);
++    for (Argument &AI : F->args())
++      Solver.markAnythingOverdefined(&AI);
+   }
+ 
+   // Loop over global variables.  We inform the solver about any internal global
+   // variables that do not have their 'addresses taken'.  If they don't have
+   // their addresses taken, we can propagate constants through them.
+-  for (Module::global_iterator G = M.global_begin(), E = M.global_end();
+-       G != E; ++G)
+-    if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
+-      Solver.TrackValueOfGlobalVariable(G);
++  for (GlobalVariable &G : M.globals())
++    if (!G.isConstant() && G.hasLocalLinkage() && !AddressIsTaken(&G))
++      Solver.TrackValueOfGlobalVariable(&G);
+ 
+   // Solve for constants.
+   bool ResolvedUndefs = true;
+@@ -1762,7 +1759,10 @@
+   SmallVector<BasicBlock*, 512> BlocksToErase;
+ 
+   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
+-    if (Solver.isBlockExecutable(F->begin())) {
++    if (F->isDeclaration())
++      continue;
++
++    if (Solver.isBlockExecutable(&F->front())) {
+       for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
+            AI != E; ++AI) {
+         if (AI->use_empty() || AI->getType()->isStructTy()) continue;
+@@ -1770,7 +1770,7 @@
+         // TODO: Could use getStructLatticeValueFor to find out if the entire
+         // result is a constant and replace it entirely if so.
+ 
+-        LatticeVal IV = Solver.getLatticeValueFor(AI);
++        LatticeVal IV = Solver.getLatticeValueFor(&*AI);
+         if (IV.isOverdefined()) continue;
+ 
+         Constant *CST = IV.isConstant() ?
+@@ -1785,29 +1785,29 @@
+     }
+ 
+     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
+-      if (!Solver.isBlockExecutable(BB)) {
+-        DeleteInstructionInBlock(BB);
++      if (!Solver.isBlockExecutable(&*BB)) {
++        DeleteInstructionInBlock(&*BB);
+         MadeChanges = true;
+ 
+         TerminatorInst *TI = BB->getTerminator();
+         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
+           BasicBlock *Succ = TI->getSuccessor(i);
+           if (!Succ->empty() && isa<PHINode>(Succ->begin()))
+-            TI->getSuccessor(i)->removePredecessor(BB);
++            TI->getSuccessor(i)->removePredecessor(&*BB);
+         }
++
+         if (!TI->use_empty())
+           TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
+         TI->eraseFromParent();
++        new UnreachableInst(M.getContext(), &*BB);
+ 
+         if (&*BB != &F->front())
+-          BlocksToErase.push_back(BB);
+-        else
+-          new UnreachableInst(M.getContext(), BB);
++          BlocksToErase.push_back(&*BB);
+         continue;
+       }
+ 
+       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
+-        Instruction *Inst = BI++;
++        Instruction *Inst = &*BI++;
+         if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
+           continue;
+ 
+--- lib/Transforms/Scalar/SROA.cpp	2015-01-07 18:02:00.000000000 -0800
++++ lib/Transforms/Scalar/SROA.cpp	2015-11-28 19:22:34.615193007 -0800
+@@ -1370,7 +1370,7 @@
+ 
+     // Ensure that there are no instructions between the PHI and the load that
+     // could store.
+-    for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
++    for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
+       if (BBI->mayWriteToMemory())
+         return false;
+ 
+@@ -2607,7 +2607,8 @@
+                  DL.getTypeStoreSizeInBits(LI.getType()) &&
+              "Non-byte-multiple bit width");
+       // Move the insertion point just past the load so that we can refer to it.
+-      IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
++      IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
++
+       // Create a placeholder value with the same type as LI to use as the
+       // basis for the new value. This allows us to replace the uses of LI with
+       // the computed value, and then replace the placeholder with LI, leaving
+@@ -3069,7 +3070,7 @@
+     // dominate the PHI.
+     IRBuilderTy PtrBuilder(IRB);
+     if (isa<PHINode>(OldPtr))
+-      PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
++      PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
+     else
+       PtrBuilder.SetInsertPoint(OldPtr);
+     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
+@@ -3714,7 +3715,7 @@
+            "Cannot represent alloca access size using 64-bit integers!");
+ 
+     Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
+-    IRB.SetInsertPoint(BasicBlock::iterator(LI));
++    IRB.SetInsertPoint(LI);
+ 
+     DEBUG(dbgs() << "  Splitting load: " << *LI << "\n");
+ 
+@@ -3766,7 +3767,7 @@
+       }
+ 
+       Value *StoreBasePtr = SI->getPointerOperand();
+-      IRB.SetInsertPoint(BasicBlock::iterator(SI));
++      IRB.SetInsertPoint(SI);
+ 
+       DEBUG(dbgs() << "    Splitting store of load: " << *SI << "\n");
+ 
+@@ -3855,7 +3856,7 @@
+       if (SplitLoads) {
+         PLoad = (*SplitLoads)[Idx];
+       } else {
+-        IRB.SetInsertPoint(BasicBlock::iterator(LI));
++        IRB.SetInsertPoint(LI);
+         PLoad = IRB.CreateAlignedLoad(
+             getAdjustedPtr(IRB, *DL, LoadBasePtr,
+                            APInt(DL->getPointerSizeInBits(), PartOffset),
+@@ -3865,7 +3866,7 @@
+       }
+ 
+       // And store this partition.
+-      IRB.SetInsertPoint(BasicBlock::iterator(SI));
++      IRB.SetInsertPoint(SI);
+       StoreInst *PStore = IRB.CreateAlignedStore(
+           PLoad, getAdjustedPtr(IRB, *DL, StoreBasePtr,
+                                 APInt(DL->getPointerSizeInBits(), PartOffset),
+--- lib/Transforms/Scalar/SampleProfile.cpp	2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/SampleProfile.cpp	2016-01-23 20:40:41.000000000 -0800
+@@ -54,8 +54,10 @@
+ 
+ // Command line option to specify the file to read samples from. This is
+ // mainly used for debugging.
+-static cl::opt<std::string> SampleProfileFile(
+-    "sample-profile-file", cl::init(""), cl::value_desc("filename"),
++static std::string EmptyInitString("");
++static cl::opt<std::string>
++SampleProfileFile("sample-profile-file", cl::init(EmptyInitString),
++    cl::value_desc("filename"),
+     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
+ static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
+     "sample-profile-max-propagate-iterations", cl::init(100),
+--- lib/Transforms/Scalar/ScalarReplAggregates.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Scalar/ScalarReplAggregates.cpp	2015-11-28 18:31:24.445308022 -0800
+@@ -382,8 +382,9 @@
+     // Create and insert the integer alloca.
+     NewTy = IntegerType::get(AI->getContext(), BitWidth);
+   }
++
+   AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
+-                                     AI->getParent()->begin());
++                                     &AI->getParent()->front());
+   ConvertUsesToScalar(AI, NewAI, 0, nullptr);
+   return NewAI;
+ }
+@@ -1202,7 +1203,7 @@
+ 
+     // Ensure that there are no instructions between the PHI and the load that
+     // could store.
+-    for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
++    for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
+       if (BBI->mayWriteToMemory())
+         return false;
+ 
+--- lib/Transforms/Scalar/Scalarizer.cpp	2014-11-11 13:30:22.000000000 -0800
++++ lib/Transforms/Scalar/Scalarizer.cpp	2015-11-29 08:58:18.947961675 -0800
+@@ -250,10 +250,9 @@
+ bool Scalarizer::runOnFunction(Function &F) {
+   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
+   DL = DLP ? &DLP->getDataLayout() : nullptr;
+-  for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
+-    BasicBlock *BB = BBI;
+-    for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
+-      Instruction *I = II;
++  for (BasicBlock &BB : F) {
++    for (BasicBlock::iterator II = BB.begin(), IE = BB.end(); II != IE;) {
++      Instruction *I = &*II;
+       bool Done = visit(I);
+       ++II;
+       if (Done && I->getType()->isVoidTy())
+@@ -282,7 +281,7 @@
+   }
+   // In the fallback case, just put the scattered before Point and
+   // keep the result local to Point.
+-  return Scatterer(Point->getParent(), Point, V);
++  return Scatterer(Point->getParent(), Point->getIterator(), V);
+ }
+ 
+ // Replace Op with the gathered form of the components in CV.  Defer the
+@@ -377,7 +376,7 @@
+     return false;
+ 
+   unsigned NumElems = VT->getNumElements();
+-  IRBuilder<> Builder(I.getParent(), &I);
++  IRBuilder<> Builder(&I);
+   Scatterer Op0 = scatter(&I, I.getOperand(0));
+   Scatterer Op1 = scatter(&I, I.getOperand(1));
+   assert(Op0.size() == NumElems && "Mismatched binary operation");
+@@ -397,7 +396,7 @@
+     return false;
+ 
+   unsigned NumElems = VT->getNumElements();
+-  IRBuilder<> Builder(SI.getParent(), &SI);
++  IRBuilder<> Builder(&SI);
+   Scatterer Op1 = scatter(&SI, SI.getOperand(1));
+   Scatterer Op2 = scatter(&SI, SI.getOperand(2));
+   assert(Op1.size() == NumElems && "Mismatched select");
+@@ -438,7 +437,7 @@
+   if (!VT)
+     return false;
+ 
+-  IRBuilder<> Builder(GEPI.getParent(), &GEPI);
++  IRBuilder<> Builder(&GEPI);
+   unsigned NumElems = VT->getNumElements();
+   unsigned NumIndices = GEPI.getNumIndices();
+ 
+@@ -472,7 +471,7 @@
+     return false;
+ 
+   unsigned NumElems = VT->getNumElements();
+-  IRBuilder<> Builder(CI.getParent(), &CI);
++  IRBuilder<> Builder(&CI);
+   Scatterer Op0 = scatter(&CI, CI.getOperand(0));
+   assert(Op0.size() == NumElems && "Mismatched cast");
+   ValueVector Res;
+@@ -492,7 +491,7 @@
+ 
+   unsigned DstNumElems = DstVT->getNumElements();
+   unsigned SrcNumElems = SrcVT->getNumElements();
+-  IRBuilder<> Builder(BCI.getParent(), &BCI);
++  IRBuilder<> Builder(&BCI);
+   Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
+   ValueVector Res;
+   Res.resize(DstNumElems);
+@@ -569,7 +568,7 @@
+     return false;
+ 
+   unsigned NumElems = VT->getNumElements();
+-  IRBuilder<> Builder(PHI.getParent(), &PHI);
++  IRBuilder<> Builder(&PHI);
+   ValueVector Res;
+   Res.resize(NumElems);
+ 
+@@ -599,7 +598,7 @@
+     return false;
+ 
+   unsigned NumElems = Layout.VecTy->getNumElements();
+-  IRBuilder<> Builder(LI.getParent(), &LI);
++  IRBuilder<> Builder(&LI);
+   Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
+   ValueVector Res;
+   Res.resize(NumElems);
+@@ -623,7 +622,7 @@
+     return false;
+ 
+   unsigned NumElems = Layout.VecTy->getNumElements();
+-  IRBuilder<> Builder(SI.getParent(), &SI);
++  IRBuilder<> Builder(&SI);
+   Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
+   Scatterer Val = scatter(&SI, FullValue);
+ 
+@@ -653,7 +652,7 @@
+       Value *Res = UndefValue::get(Ty);
+       BasicBlock *BB = Op->getParent();
+       unsigned Count = Ty->getVectorNumElements();
+-      IRBuilder<> Builder(BB, Op);
++      IRBuilder<> Builder(Op);
+       if (isa<PHINode>(Op))
+         Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
+       for (unsigned I = 0; I < Count; ++I)
+--- lib/Transforms/Scalar/SimplifyCFGPass.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Scalar/SimplifyCFGPass.cpp	2015-11-28 19:16:00.355459043 -0800
+@@ -96,7 +96,7 @@
+     // single PHI node that is the operand to the return.
+     if (Ret != &BB.front()) {
+       // Check for something else in the block.
+-      BasicBlock::iterator I = Ret;
++      BasicBlock::iterator I(Ret);
+       --I;
+       // Skip over debug info.
+       while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
+@@ -104,7 +104,7 @@
+       if (!isa<DbgInfoIntrinsic>(I) &&
+           (!isa<PHINode>(I) || I != BB.begin() ||
+            Ret->getNumOperands() == 0 ||
+-           Ret->getOperand(0) != I))
++           Ret->getOperand(0) != &*I))
+         continue;
+     }
+ 
+@@ -166,7 +166,7 @@
+     // Loop over all of the basic blocks and remove them if they are unneeded...
+     //
+     for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
+-      if (SimplifyCFG(BBIt++, TTI, BonusInstThreshold, DL, AC)) {
++      if (SimplifyCFG(&*BBIt++, TTI, BonusInstThreshold, DL, AC)) {
+         LocalChange = true;
+         ++NumSimpl;
+       }
+--- lib/Transforms/Scalar/Sink.cpp	2014-08-24 16:23:06.000000000 -0700
++++ lib/Transforms/Scalar/Sink.cpp	2015-11-28 19:17:12.178518993 -0800
+@@ -136,7 +136,7 @@
+   bool ProcessedBegin = false;
+   SmallPtrSet<Instruction *, 8> Stores;
+   do {
+-    Instruction *Inst = I;  // The instruction to sink.
++    Instruction *Inst = &*I;  // The instruction to sink.
+ 
+     // Predecrement I (if it's not begin) so that it isn't invalidated by
+     // sinking.
+@@ -274,6 +274,6 @@
+         dbgs() << ")\n");
+ 
+   // Move the instruction.
+-  Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
++  Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
+   return true;
+ }
+--- lib/Transforms/Scalar/StructurizeCFG.cpp	2014-12-02 20:28:32.000000000 -0800
++++ lib/Transforms/Scalar/StructurizeCFG.cpp	2015-11-28 19:23:41.808228788 -0800
+@@ -842,14 +842,14 @@
+             continue;
+         }
+ 
+-        if (DT->dominates(II, User))
++        if (DT->dominates(&*II, User))
+           continue;
+ 
+         if (!Initialized) {
+           Value *Undef = UndefValue::get(II->getType());
+           Updater.Initialize(II->getType(), "");
+           Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
+-          Updater.AddAvailableValue(BB, II);
++          Updater.AddAvailableValue(BB, &*II);
+           Initialized = true;
+         }
+         Updater.RewriteUseAfterInsertions(U);
+--- lib/Transforms/Scalar/TailRecursionElimination.cpp	2014-11-19 05:32:51.000000000 -0800
++++ lib/Transforms/Scalar/TailRecursionElimination.cpp	2015-11-28 19:32:29.223858053 -0800
+@@ -404,28 +404,22 @@
+   // alloca' is changed from being a static alloca to being a dynamic alloca.
+   // Until this is resolved, disable this transformation if that would ever
+   // happen.  This bug is PR962.
+-  SmallVector<BasicBlock*, 8> BBToErase;
+-  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
++  for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E;
++       /* inside loop */) {
++    BasicBlock *BB = &*BBI;
++    ++BBI;
++
+     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
+       bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
+                                           ArgumentPHIs, !CanTRETailMarkedCall);
+-      if (!Change && BB->getFirstNonPHIOrDbg() == Ret) {
++      if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
+         Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
+                                           TailCallsAreMarkedTail, ArgumentPHIs,
+                                           !CanTRETailMarkedCall);
+-        // FoldReturnAndProcessPred may have emptied some BB. Remember to
+-        // erase them.
+-        if (Change && BB->empty())
+-          BBToErase.push_back(BB);
+-
+-      }
+       MadeChange |= Change;
+     }
+   }
+ 
+-  for (auto BB: BBToErase)
+-    BB->eraseFromParent();
+-
+   // If we eliminated any tail recursions, it's possible that we inserted some
+   // silly PHI nodes which just merge an initial value (the incoming operand)
+   // with themselves.  Check to see if we did and clean up our mess if so.  This
+@@ -588,7 +582,7 @@
+   // Scan backwards from the return, checking to see if there is a tail call in
+   // this block.  If so, set CI to it.
+   CallInst *CI = nullptr;
+-  BasicBlock::iterator BBI = TI;
++  BasicBlock::iterator BBI(TI);
+   while (true) {
+     CI = dyn_cast<CallInst>(BBI);
+     if (CI && CI->getCalledFunction() == F)
+@@ -609,9 +603,8 @@
+   // and disable this xform in this case, because the code generator will
+   // lower the call to fabs into inline code.
+   if (BB == &F->getEntryBlock() &&
+-      FirstNonDbg(BB->front()) == CI &&
+-      FirstNonDbg(std::next(BB->begin())) == TI &&
+-      CI->getCalledFunction() &&
++      FirstNonDbg(BB->front().getIterator()) == CI &&
++      FirstNonDbg(std::next(BB->begin())) == TI && CI->getCalledFunction() &&
+       !TTI->isLoweredToCall(CI->getCalledFunction())) {
+     // A single-block function with just a call and a return. Check that
+     // the arguments match.
+@@ -650,19 +643,19 @@
+   // tail call if all of the instructions between the call and the return are
+   // movable to above the call itself, leaving the call next to the return.
+   // Check that this is the case now.
+-  BasicBlock::iterator BBI = CI;
++  BasicBlock::iterator BBI(CI);
+   for (++BBI; &*BBI != Ret; ++BBI) {
+-    if (CanMoveAboveCall(BBI, CI)) continue;
++    if (CanMoveAboveCall(&*BBI, CI)) continue;
+ 
+     // If we can't move the instruction above the call, it might be because it
+     // is an associative and commutative operation that could be transformed
+     // using accumulator recursion elimination.  Check to see if this is the
+     // case, and if so, remember the initial accumulator value for later.
+     if ((AccumulatorRecursionEliminationInitVal =
+-                           CanTransformAccumulatorRecursion(BBI, CI))) {
++             CanTransformAccumulatorRecursion(&*BBI, CI))) {
+       // Yes, this is accumulator recursion.  Remember which instruction
+       // accumulates.
+-      AccumulatorRecursionInstr = BBI;
++      AccumulatorRecursionInstr = &*BBI;
+     } else {
+       return false;   // Otherwise, we cannot eliminate the tail recursion!
+     }
+@@ -712,19 +705,19 @@
+              NEBI = NewEntry->begin(); OEBI != E; )
+         if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
+           if (isa<ConstantInt>(AI->getArraySize()))
+-            AI->moveBefore(NEBI);
++            AI->moveBefore(&*NEBI);
+ 
+     // Now that we have created a new block, which jumps to the entry
+     // block, insert a PHI node for each argument of the function.
+     // For now, we initialize each PHI to only have the real arguments
+     // which are passed in.
+-    Instruction *InsertPos = OldEntry->begin();
++    Instruction *InsertPos = &OldEntry->front();
+     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
+          I != E; ++I) {
+       PHINode *PN = PHINode::Create(I->getType(), 2,
+                                     I->getName() + ".tr", InsertPos);
+       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
+-      PN->addIncoming(I, NewEntry);
++      PN->addIncoming(&*I, NewEntry);
+       ArgumentPHIs.push_back(PN);
+     }
+   }
+@@ -753,10 +746,9 @@
+     Instruction *AccRecInstr = AccumulatorRecursionInstr;
+     // Start by inserting a new PHI node for the accumulator.
+     pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
+-    PHINode *AccPN =
+-      PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
+-                      std::distance(PB, PE) + 1,
+-                      "accumulator.tr", OldEntry->begin());
++    PHINode *AccPN = PHINode::Create(
++        AccumulatorRecursionEliminationInitVal->getType(),
++        std::distance(PB, PE) + 1, "accumulator.tr", &OldEntry->front());
+ 
+     // Loop over all of the predecessors of the tail recursion block.  For the
+     // real entry into the function we seed the PHI with the initial value,
+--- lib/Transforms/Utils/AddDiscriminators.cpp	2014-12-09 10:38:53.000000000 -0800
++++ lib/Transforms/Utils/AddDiscriminators.cpp	2015-11-29 09:01:43.033905645 -0800
+@@ -172,7 +172,7 @@
+   // Traverse all the blocks looking for instructions in different
+   // blocks that are at the same file:line location.
+   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+-    BasicBlock *B = I;
++    BasicBlock *B = &*I;
+     TerminatorInst *Last = B->getTerminator();
+     DebugLoc LastLoc = Last->getDebugLoc();
+     if (LastLoc.isUnknown()) continue;
+--- lib/Transforms/Utils/BasicBlockUtils.cpp	2014-11-18 16:17:31.000000000 -0800
++++ lib/Transforms/Utils/BasicBlockUtils.cpp	2015-11-29 09:05:35.763274502 -0800
+@@ -255,7 +255,7 @@
+     // block.
+     assert(SP == BB && "CFG broken");
+     SP = nullptr;
+-    return SplitBlock(Succ, Succ->begin(), P);
++    return SplitBlock(Succ, &Succ->front(), P);
+   }
+ 
+   // Otherwise, if BB has a single successor, split it at the bottom of the
+@@ -283,7 +283,7 @@
+ /// the loop info is updated.
+ ///
+ BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
+-  BasicBlock::iterator SplitIt = SplitPt;
++  BasicBlock::iterator SplitIt = SplitPt->getIterator();
+   while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
+     ++SplitIt;
+   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
+@@ -642,7 +642,7 @@
+       // return instruction.
+       V = BCI->getOperand(0);
+       NewBC = BCI->clone();
+-      Pred->getInstList().insert(NewRet, NewBC);
++      Pred->getInstList().insert(NewRet->getIterator(), NewBC);
+       *i = NewBC;
+     }
+     if (PHINode *PN = dyn_cast<PHINode>(V)) {
+@@ -688,7 +688,7 @@
+                                                 MDNode *BranchWeights,
+                                                 DominatorTree *DT) {
+   BasicBlock *Head = SplitBefore->getParent();
+-  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
++  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
+   TerminatorInst *HeadOldTerm = Head->getTerminator();
+   LLVMContext &C = Head->getContext();
+   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
+@@ -739,7 +739,7 @@
+                                          TerminatorInst **ElseTerm,
+                                          MDNode *BranchWeights) {
+   BasicBlock *Head = SplitBefore->getParent();
+-  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
++  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
+   TerminatorInst *HeadOldTerm = Head->getTerminator();
+   LLVMContext &C = Head->getContext();
+   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
+--- lib/Transforms/Utils/BreakCriticalEdges.cpp	2014-11-18 16:17:31.000000000 -0800
++++ lib/Transforms/Utils/BreakCriticalEdges.cpp	2015-11-29 09:07:57.703524612 -0800
+@@ -98,7 +98,7 @@
+     PHINode *NewPN =
+       PHINode::Create(PN->getType(), Preds.size(), "split",
+                       SplitBB->isLandingPad() ?
+-                      SplitBB->begin() : SplitBB->getTerminator());
++                      &SplitBB->front() : SplitBB->getTerminator());
+     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
+       NewPN->addIncoming(V, Preds[i]);
+ 
+@@ -152,7 +152,7 @@
+ 
+   // Insert the block into the function... right after the block TI lives in.
+   Function &F = *TIBB->getParent();
+-  Function::iterator FBBI = TIBB;
++  Function::iterator FBBI = TIBB->getIterator();
+   F.getBasicBlockList().insert(++FBBI, NewBB);
+ 
+   // If there are any PHI nodes in DestBB, we need to update them so that they
+--- lib/Transforms/Utils/BypassSlowDivision.cpp	2014-04-24 22:29:35.000000000 -0700
++++ lib/Transforms/Utils/BypassSlowDivision.cpp	2015-11-29 09:10:30.545799550 -0800
+@@ -82,7 +82,7 @@
+                           bool UseSignedOp,
+                           DivCacheTy &PerBBDivCache) {
+   // Get instruction operands
+-  Instruction *Instr = J;
++  Instruction *Instr = &*J;
+   Value *Dividend = Instr->getOperand(0);
+   Value *Divisor = Instr->getOperand(1);
+ 
+@@ -94,7 +94,7 @@
+   }
+ 
+   // Basic Block is split before divide
+-  BasicBlock *MainBB = I;
++  BasicBlock *MainBB = &*I;
+   BasicBlock *SuccessorBB = I->splitBasicBlock(J);
+   ++I; //advance iterator I to successorBB
+ 
+@@ -190,7 +190,7 @@
+                                  bool UseSignedOp,
+                                  DivCacheTy &PerBBDivCache) {
+   // Get instruction operands
+-  Instruction *Instr = J;
++  Instruction *Instr = &*J;
+   DivOpInfo Key(UseSignedOp, Instr->getOperand(0), Instr->getOperand(1));
+   DivCacheTy::iterator CacheI = PerBBDivCache.find(Key);
+ 
+--- lib/Transforms/Utils/CloneFunction.cpp	2014-12-18 22:06:18.000000000 -0800
++++ lib/Transforms/Utils/CloneFunction.cpp	2015-11-29 09:27:19.893077178 -0800
+@@ -51,7 +51,7 @@
+     if (II->hasName())
+       NewInst->setName(II->getName()+NameSuffix);
+     NewBB->getInstList().push_back(NewInst);
+-    VMap[II] = NewInst;                // Add instruction map to value.
++    VMap[&*II] = NewInst;                // Add instruction map to value.
+     
+     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
+     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
+@@ -86,7 +86,7 @@
+ #ifndef NDEBUG
+   for (Function::const_arg_iterator I = OldFunc->arg_begin(), 
+        E = OldFunc->arg_end(); I != E; ++I)
+-    assert(VMap.count(I) && "No mapping from source argument specified!");
++    assert(VMap.count(&*I) && "No mapping from source argument specified!");
+ #endif
+ 
+   // Copy all attributes other than those stored in the AttributeSet.  We need
+@@ -145,11 +145,12 @@
+ 
+   // Loop over all of the instructions in the function, fixing up operand
+   // references as we go.  This uses VMap to do all the hard work.
+-  for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
+-         BE = NewFunc->end(); BB != BE; ++BB)
++  for (Function::iterator BB =
++       cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
++       BE = NewFunc->end(); BB != BE; ++BB)
+     // Loop over all instructions, fixing each one as we find it...
+-    for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
+-      RemapInstruction(II, VMap,
++    for (Instruction &II : *BB)
++      RemapInstruction(&II, VMap,
+                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
+                        TypeMapper, Materializer);
+ }
+@@ -220,7 +221,7 @@
+   //
+   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
+        I != E; ++I)
+-    if (VMap.count(I) == 0)  // Haven't mapped the argument to anything yet?
++    if (VMap.count(&*I) == 0)  // Haven't mapped the argument to anything yet?
+       ArgTypes.push_back(I->getType());
+ 
+   // Create a new function type...
+@@ -234,9 +235,9 @@
+   Function::arg_iterator DestI = NewF->arg_begin();
+   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
+        I != E; ++I)
+-    if (VMap.count(I) == 0) {   // Is this argument preserved?
+-      DestI->setName(I->getName()); // Copy the name over...
+-      VMap[I] = DestI++;        // Add mapping to VMap
++    if (VMap.count(&*I) == 0) {       // Is this argument preserved?
++      DestI->setName(I->getName());   // Copy the name over...
++      VMap[&*I] = &*DestI++;          // Add mapping to VMap
+     }
+ 
+   if (ModuleLevelChanges)
+@@ -332,7 +333,7 @@
+         if (Value *MappedV = VMap.lookup(V))
+           V = MappedV;
+ 
+-        VMap[II] = V;
++        VMap[&*II] = V;
+         delete NewInst;
+         continue;
+       }
+@@ -340,9 +341,10 @@
+ 
+     if (II->hasName())
+       NewInst->setName(II->getName()+NameSuffix);
+-    VMap[II] = NewInst;                // Add instruction map to value.
++    VMap[&*II] = NewInst;                // Add instruction map to value.
+     NewBB->getInstList().push_back(NewInst);
+     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
++
+     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
+       if (isa<ConstantInt>(AI->getArraySize()))
+         hasStaticAllocas = true;
+@@ -429,7 +431,7 @@
+ #ifndef NDEBUG
+   for (Function::const_arg_iterator II = OldFunc->arg_begin(), 
+        E = OldFunc->arg_end(); II != E; ++II)
+-    assert(VMap.count(II) && "No mapping from source argument specified!");
++    assert(VMap.count(&*II) && "No mapping from source argument specified!");
+ #endif
+ 
+   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
+@@ -452,7 +454,7 @@
+   SmallVector<const PHINode*, 16> PHIToResolve;
+   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
+        BI != BE; ++BI) {
+-    Value *V = VMap[BI];
++    Value *V = VMap[&*BI];
+     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
+     if (!NewBB) continue;  // Dead block.
+ 
+@@ -546,8 +548,8 @@
+       while ((PN = dyn_cast<PHINode>(I++))) {
+         Value *NV = UndefValue::get(PN->getType());
+         PN->replaceAllUsesWith(NV);
+-        assert(VMap[OldI] == PN && "VMap mismatch");
+-        VMap[OldI] = NV;
++        assert(VMap[&*OldI] == PN && "VMap mismatch");
++        VMap[&*OldI] = NV;
+         PN->eraseFromParent();
+         ++OldI;
+       }
+@@ -569,15 +571,16 @@
+   // and zap unconditional fall-through branches.  This happen all the time when
+   // specializing code: code specialization turns conditional branches into
+   // uncond branches, and this code folds them.
+-  Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
++  Function::iterator Begin =
++    cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()])->getIterator();
+   Function::iterator I = Begin;
+   while (I != NewFunc->end()) {
+     // Check if this block has become dead during inlining or other
+     // simplifications. Note that the first block will appear dead, as it has
+     // not yet been wired up properly.
+-    if (I != Begin && (pred_begin(I) == pred_end(I) ||
+-                       I->getSinglePredecessor() == I)) {
+-      BasicBlock *DeadBB = I++;
++    if ((I != Begin) && (pred_begin(&*I) == pred_end(&*I) ||
++                         I->getSinglePredecessor() == &*I)) {
++      BasicBlock *DeadBB = &*I++;
+       DeleteDeadBlock(DeadBB);
+       continue;
+     }
+@@ -587,7 +590,7 @@
+     // simplification required looking through PHI nodes, those are only
+     // available after forming the full basic block. That may leave some here,
+     // and we still want to prune the dead code as early as possible.
+-    ConstantFoldTerminator(I);
++    ConstantFoldTerminator(&*I);
+ 
+     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
+     if (!BI || BI->isConditional()) { ++I; continue; }
+@@ -606,7 +609,7 @@
+     BI->eraseFromParent();
+     
+     // Make all PHI nodes that referred to Dest now refer to I as their source.
+-    Dest->replaceAllUsesWith(I);
++    Dest->replaceAllUsesWith(&*I);
+ 
+     // Move all the instructions in the succ to the pred.
+     I->getInstList().splice(I->end(), Dest->getInstList());
+@@ -620,9 +623,9 @@
+   // Make a final pass over the basic blocks from theh old function to gather
+   // any return instructions which survived folding. We have to do this here
+   // because we can iteratively remove and merge returns above.
+-  for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
+-                          E = NewFunc->end();
+-       I != E; ++I)
++  for (Function::iterator I =
++       cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()])->getIterator(),
++       E = NewFunc->end(); I != E; ++I)
+     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
+       Returns.push_back(RI);
+ }
+--- lib/Transforms/Utils/CloneModule.cpp	2014-12-23 00:23:45.000000000 -0800
++++ lib/Transforms/Utils/CloneModule.cpp	2015-11-29 10:05:42.438731638 -0800
+@@ -45,15 +45,15 @@
+   //
+   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
+        I != E; ++I) {
+-    GlobalVariable *GV = new GlobalVariable(*New, 
++    GlobalVariable *GV = new GlobalVariable(*New,
+                                             I->getType()->getElementType(),
+                                             I->isConstant(), I->getLinkage(),
+                                             (Constant*) nullptr, I->getName(),
+                                             (GlobalVariable*) nullptr,
+                                             I->getThreadLocalMode(),
+                                             I->getType()->getAddressSpace());
+-    GV->copyAttributesFrom(I);
+-    VMap[I] = GV;
++    GV->copyAttributesFrom(&*I);
++    VMap[&*I] = GV;
+   }
+ 
+   // Loop over the functions in the module, making external functions as before
+@@ -61,8 +61,8 @@
+     Function *NF =
+       Function::Create(cast<FunctionType>(I->getType()->getElementType()),
+                        I->getLinkage(), I->getName(), New);
+-    NF->copyAttributesFrom(I);
+-    VMap[I] = NF;
++    NF->copyAttributesFrom(&*I);
++    VMap[&*I] = NF;
+   }
+ 
+   // Loop over the aliases in the module
+@@ -72,8 +72,8 @@
+     auto *GA =
+         GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
+                             I->getLinkage(), I->getName(), New);
+-    GA->copyAttributesFrom(I);
+-    VMap[I] = GA;
++    GA->copyAttributesFrom(&*I);
++    VMap[&*I] = GA;
+   }
+   
+   // Now that all of the things that global variable initializer can refer to
+@@ -82,7 +82,7 @@
+   //
+   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
+        I != E; ++I) {
+-    GlobalVariable *GV = cast<GlobalVariable>(VMap[I]);
++    GlobalVariable *GV = cast<GlobalVariable>(VMap[&*I]);
+     if (I->hasInitializer())
+       GV->setInitializer(MapValue(I->getInitializer(), VMap));
+   }
+@@ -90,24 +90,24 @@
+   // Similarly, copy over function bodies now...
+   //
+   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
+-    Function *F = cast<Function>(VMap[I]);
++    Function *F = cast<Function>(VMap[&*I]);
+     if (!I->isDeclaration()) {
+       Function::arg_iterator DestI = F->arg_begin();
+       for (Function::const_arg_iterator J = I->arg_begin(); J != I->arg_end();
+            ++J) {
+         DestI->setName(J->getName());
+-        VMap[J] = DestI++;
++        VMap[&*J] = &*DestI++;
+       }
+ 
+       SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
+-      CloneFunctionInto(F, I, VMap, /*ModuleLevelChanges=*/true, Returns);
++      CloneFunctionInto(F, &*I, VMap, /*ModuleLevelChanges=*/true, Returns);
+     }
+   }
+ 
+   // And aliases
+   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
+        I != E; ++I) {
+-    GlobalAlias *GA = cast<GlobalAlias>(VMap[I]);
++    GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]);
+     if (const Constant *C = I->getAliasee())
+       GA->setAliasee(MapValue(C, VMap));
+   }
+--- lib/Transforms/Utils/CodeExtractor.cpp	2014-07-21 10:06:51.000000000 -0700
++++ lib/Transforms/Utils/CodeExtractor.cpp	2015-11-29 10:25:40.506775548 -0800
+@@ -175,7 +175,7 @@
+ 
+       for (User *U : II->users())
+         if (!definedInRegion(Blocks, U)) {
+-          Outputs.insert(II);
++          Outputs.insert(&*II);
+           break;
+         }
+     }
+@@ -211,7 +211,7 @@
+   // containing PHI nodes merging values from outside of the region, and a
+   // second that contains all of the code for the block and merges back any
+   // incoming values from inside of the region.
+-  BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
++  BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI()->getIterator();
+   BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
+                                               Header->getName()+".ce");
+ 
+@@ -246,7 +246,7 @@
+       // Create a new PHI node in the new region, which has an incoming value
+       // from OldPred of PN.
+       PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
+-                                       PN->getName()+".ce", NewBB->begin());
++                                       PN->getName()+".ce", &NewBB->front());
+       NewPN->addIncoming(PN, OldPred);
+ 
+       // Loop over all of the incoming value in PN, moving them to NewPN if they
+@@ -266,14 +266,15 @@
+   for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
+        I != E; ++I)
+     if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
+-      BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
++      BasicBlock *New =
++        (*I)->splitBasicBlock(RI->getIterator(), (*I)->getName() + ".ret");
+       if (DT) {
+         // Old dominates New. New node dominates all other nodes dominated
+         // by Old.
+         DomTreeNode *OldNode = DT->getNode(*I);
+         SmallVector<DomTreeNode*, 8> Children;
+         for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
+-             DI != DE; ++DI) 
++             DI != DE; ++DI)
+           Children.push_back(*DI);
+ 
+         DomTreeNode *NewNode = DT->addNewBlock(New, *I);
+@@ -364,11 +365,11 @@
+       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
+       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
+       TerminatorInst *TI = newFunction->begin()->getTerminator();
+-      GetElementPtrInst *GEP = 
+-        GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI);
++      GetElementPtrInst *GEP =
++        GetElementPtrInst::Create(&*AI, Idx, "gep_" + inputs[i]->getName(), TI);
+       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
+     } else
+-      RewriteVal = AI++;
++      RewriteVal = &*AI++;
+ 
+     std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
+     for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
+@@ -441,7 +442,7 @@
+     } else {
+       AllocaInst *alloca =
+         new AllocaInst((*i)->getType(), nullptr, (*i)->getName()+".loc",
+-                       codeReplacer->getParent()->begin()->begin());
++                       &codeReplacer->getParent()->front().front());
+       ReloadOutputs.push_back(alloca);
+       params.push_back(alloca);
+     }
+@@ -458,7 +459,7 @@
+     Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
+     Struct =
+       new AllocaInst(StructArgTy, nullptr, "structArg",
+-                     codeReplacer->getParent()->begin()->begin());
++                     &codeReplacer->getParent()->front().front());
+     params.push_back(Struct);
+ 
+     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
+@@ -607,12 +608,12 @@
+                 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
+                                           FirstOut+out);
+                 GetElementPtrInst *GEP =
+-                  GetElementPtrInst::Create(OAI, Idx,
++                  GetElementPtrInst::Create(&*OAI, Idx,
+                                             "gep_" + outputs[out]->getName(),
+                                             NTRet);
+                 new StoreInst(outputs[out], GEP, NTRet);
+               } else {
+-                new StoreInst(outputs[out], OAI, NTRet);
++                new StoreInst(outputs[out], &*OAI, NTRet);
+               }
+             }
+             // Advance output iterator even if we don't emit a store
+--- lib/Transforms/Utils/CtorUtils.cpp	2014-09-23 15:33:01.000000000 -0700
++++ lib/Transforms/Utils/CtorUtils.cpp	2015-11-29 10:27:14.531198062 -0800
+@@ -49,7 +49,7 @@
+   GlobalVariable *NGV =
+       new GlobalVariable(CA->getType(), GCL->isConstant(), GCL->getLinkage(),
+                          CA, "", GCL->getThreadLocalMode());
+-  GCL->getParent()->getGlobalList().insert(GCL, NGV);
++  GCL->getParent()->getGlobalList().insert(GCL->getIterator(), NGV);
+   NGV->takeName(GCL);
+ 
+   // Nuke the old list, replacing any uses with the new one.
+--- lib/Transforms/Utils/DemoteRegToStack.cpp	2014-04-24 22:29:35.000000000 -0700
++++ lib/Transforms/Utils/DemoteRegToStack.cpp	2015-11-29 10:33:53.846940110 -0800
+@@ -36,7 +36,7 @@
+   } else {
+     Function *F = I.getParent()->getParent();
+     Slot = new AllocaInst(I.getType(), nullptr, I.getName()+".reg2mem",
+-                          F->getEntryBlock().begin());
++                          &F->getEntryBlock().front());
+   }
+ 
+   // Change all of the users of the instruction to read from the stack slot.
+@@ -77,30 +77,15 @@
+   // AFTER the terminator instruction.
+   BasicBlock::iterator InsertPt;
+   if (!isa<TerminatorInst>(I)) {
+-    InsertPt = &I;
+-    ++InsertPt;
++    InsertPt = ++I.getIterator();
++    for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt);
++         ++InsertPt);
+   } else {
+     InvokeInst &II = cast<InvokeInst>(I);
+-    if (II.getNormalDest()->getSinglePredecessor())
+-      InsertPt = II.getNormalDest()->getFirstInsertionPt();
+-    else {
+-      // We cannot demote invoke instructions to the stack if their normal edge
+-      // is critical.  Therefore, split the critical edge and insert the store
+-      // in the newly created basic block.
+-      unsigned SuccNum = GetSuccessorNumber(I.getParent(), II.getNormalDest());
+-      TerminatorInst *TI = &cast<TerminatorInst>(I);
+-      assert (isCriticalEdge(TI, SuccNum) &&
+-              "Expected a critical edge!");
+-      BasicBlock *BB = SplitCriticalEdge(TI, SuccNum);
+-      assert (BB && "Unable to split critical edge.");
+-      InsertPt = BB->getFirstInsertionPt();
+-    }
++    InsertPt = II.getNormalDest()->getFirstInsertionPt();
+   }
+ 
+-  for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt); ++InsertPt)
+-    /* empty */;   // Don't insert before PHI nodes or landingpad instrs.
+-
+-  new StoreInst(&I, Slot, InsertPt);
++  new StoreInst(&I, Slot, &*InsertPt);
+   return Slot;
+ }
+ 
+@@ -121,7 +106,7 @@
+   } else {
+     Function *F = P->getParent()->getParent();
+     Slot = new AllocaInst(P->getType(), nullptr, P->getName()+".reg2mem",
+-                          F->getEntryBlock().begin());
++                          &F->getEntryBlock().front());
+   }
+ 
+   // Iterate over each operand inserting a store in each predecessor.
+@@ -135,12 +120,12 @@
+   }
+ 
+   // Insert a load in place of the PHI and replace all uses.
+-  BasicBlock::iterator InsertPt = P;
++  BasicBlock::iterator InsertPt = P->getIterator();
+ 
+   for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt); ++InsertPt)
+     /* empty */;   // Don't insert before PHI nodes or landingpad instrs.
+ 
+-  Value *V = new LoadInst(Slot, P->getName()+".reload", InsertPt);
++  Value *V = new LoadInst(Slot, P->getName()+".reload", &*InsertPt);
+   P->replaceAllUsesWith(V);
+ 
+   // Delete PHI.
+--- lib/Transforms/Utils/FlattenCFG.cpp	2014-08-13 13:31:53.000000000 -0700
++++ lib/Transforms/Utils/FlattenCFG.cpp	2015-11-29 10:42:20.827355223 -0800
+@@ -177,8 +177,9 @@
+ 
+       // Instructions in the internal condition blocks should be safe
+       // to hoist up.
+-      for (BasicBlock::iterator BI = Pred->begin(), BE = PBI; BI != BE;) {
+-        Instruction *CI = BI++;
++      for (BasicBlock::iterator BI = Pred->begin(), BE = PBI->getIterator();
++           BI != BE;) {
++        Instruction *CI = &*BI++;
+         if (isa<PHINode>(CI) || !isSafeToSpeculativelyExecute(CI))
+           return false;
+       }
+@@ -315,7 +316,7 @@
+                                          BasicBlock *Block1,
+                                          BasicBlock *Block2) {
+   TerminatorInst *PTI2 = Head2->getTerminator();
+-  Instruction *PBI2 = Head2->begin();
++  Instruction *PBI2 = &Head2->front();
+ 
+   bool eq1 = (Block1 == Head1);
+   bool eq2 = (Block2 == Head2);
+@@ -327,9 +328,9 @@
+   // Check whether instructions in Block1 and Block2 are identical
+   // and do not alias with instructions in Head2.
+   BasicBlock::iterator iter1 = Block1->begin();
+-  BasicBlock::iterator end1 = Block1->getTerminator();
++  BasicBlock::iterator end1 = Block1->getTerminator()->getIterator();
+   BasicBlock::iterator iter2 = Block2->begin();
+-  BasicBlock::iterator end2 = Block2->getTerminator();
++  BasicBlock::iterator end2 = Block2->getTerminator()->getIterator();
+ 
+   while (1) {
+     if (iter1 == end1) {
+@@ -338,7 +339,7 @@
+       break;
+     }
+ 
+-    if (!iter1->isIdenticalTo(iter2))
++    if (!iter1->isIdenticalTo(&*iter2))
+       return false;
+ 
+     // Illegal to remove instructions with side effects except
+@@ -356,10 +357,10 @@
+       return false;
+ 
+     if (iter1->mayWriteToMemory()) {
+-      for (BasicBlock::iterator BI = PBI2, BE = PTI2; BI != BE; ++BI) {
++      for (BasicBlock::iterator BI(PBI2), BE(PTI2); BI != BE; ++BI) {
+         if (BI->mayReadFromMemory() || BI->mayWriteToMemory()) {
+           // Check alias with Head2.
+-          if (!AA || AA->alias(iter1, BI))
++          if (!AA || AA->alias(&*iter1, &*BI))
+             return false;
+         }
+       }
+@@ -413,7 +414,7 @@
+     return false;
+ 
+   TerminatorInst *PTI2 = SecondEntryBlock->getTerminator();
+-  Instruction *PBI2 = SecondEntryBlock->begin();
++  Instruction *PBI2 = &SecondEntryBlock->front();
+ 
+   if (!CompareIfRegionBlock(FirstEntryBlock, SecondEntryBlock, IfTrue1,
+                             IfTrue2))
+@@ -425,8 +426,8 @@
+ 
+   // Check whether \param SecondEntryBlock has side-effect and is safe to
+   // speculate.
+-  for (BasicBlock::iterator BI = PBI2, BE = PTI2; BI != BE; ++BI) {
+-    Instruction *CI = BI;
++  for (BasicBlock::iterator BI(PBI2), BE(PTI2); BI != BE; ++BI) {
++    Instruction *CI = &*BI;
+     if (isa<PHINode>(CI) || CI->mayHaveSideEffects() ||
+         !isSafeToSpeculativelyExecute(CI))
+       return false;
+--- lib/Transforms/Utils/InlineFunction.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/InlineFunction.cpp	2015-11-29 12:31:32.233733995 -0800
+@@ -128,7 +128,7 @@
+   if (InnerResumeDest) return InnerResumeDest;
+ 
+   // Split the landing pad.
+-  BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
++  BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
+   InnerResumeDest =
+     OuterResumeDest->splitBasicBlock(SplitPoint,
+                                      OuterResumeDest->getName() + ".body");
+@@ -137,7 +137,7 @@
+   const unsigned PHICapacity = 2;
+ 
+   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
+-  BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
++  Instruction *InsertPoint = &InnerResumeDest->front();
+   BasicBlock::iterator I = OuterResumeDest->begin();
+   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
+     PHINode *OuterPHI = cast<PHINode>(I);
+@@ -185,7 +185,8 @@
+ static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
+                                                    InvokeInliningInfo &Invoke) {
+   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
+-    Instruction *I = BBI++;
++    Instruction *I = &*BBI;
++    ++BBI;
+ 
+     // We only need to check for function calls: inlined invoke
+     // instructions require no special handling.
+@@ -198,7 +199,8 @@
+ 
+     // Convert this function call into an invoke instruction.  First, split the
+     // basic block.
+-    BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
++    BasicBlock *Split =
++      BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
+ 
+     // Delete the unconditional branch inserted by splitBasicBlock
+     BB->getInstList().pop_back();
+@@ -246,7 +248,8 @@
+ 
+   // Get all of the inlined landing pad instructions.
+   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
+-  for (Function::iterator I = FirstNewBlock, E = Caller->end(); I != E; ++I)
++  for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
++       I != E; ++I)
+     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
+       InlinedLPads.insert(II->getLandingPadInst());
+ 
+@@ -262,9 +265,10 @@
+       InlinedLPad->setCleanup(true);
+   }
+ 
+-  for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
++  for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
++       BB != E; ++BB){
+     if (InlinedCodeInfo.ContainsCalls)
+-      HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
++      HandleCallsInBlockInlinedThroughInvoke(&*BB, Invoke);
+ 
+     // Forward any resumes that are remaining here.
+     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
+@@ -406,10 +410,9 @@
+   const Function *CalledFunc = CS.getCalledFunction();
+   SmallVector<const Argument *, 4> NoAliasArgs;
+ 
+-  for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
+-       E = CalledFunc->arg_end(); I != E; ++I) {
+-    if (I->hasNoAliasAttr() && !I->hasNUses(0))
+-      NoAliasArgs.push_back(I);
++  for (const Argument &A : CalledFunc->args()) {
++    if (A.hasNoAliasAttr() && !A.hasNUses(0))
++      NoAliasArgs.push_back(&A);
+   }
+ 
+   if (NoAliasArgs.empty())
+@@ -727,7 +730,7 @@
+                                     BasicBlock *InsertBlock,
+                                     InlineFunctionInfo &IFI) {
+   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
+-  IRBuilder<> Builder(InsertBlock->begin());
++  IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
+ 
+   Value *Size;
+   if (IFI.DL == nullptr)
+@@ -962,7 +965,7 @@
+ 
+   // Get an iterator to the last basic block in the function, which will have
+   // the new function inlined after it.
+-  Function::iterator LastBlock = &Caller->back();
++  Function::iterator LastBlock = --Caller->end();
+ 
+   // Make sure to capture all of the return instructions from the cloned
+   // function.
+@@ -997,7 +1000,7 @@
+           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
+       }
+ 
+-      VMap[I] = ActualArg;
++      VMap[&*I] = ActualArg;
+     }
+ 
+     // Add alignment assumptions if necessary. We do this before the inlined
+@@ -1014,12 +1017,13 @@
+                               &InlinedFunctionInfo, IFI.DL, TheCall);
+ 
+     // Remember the first block that is newly cloned over.
+-    FirstNewBlock = LastBlock; ++FirstNewBlock;
++    FirstNewBlock = LastBlock;
++    ++FirstNewBlock;
+ 
+     // Inject byval arguments initialization.
+     for (std::pair<Value*, Value*> &Init : ByValInit)
+       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
+-                              FirstNewBlock, IFI);
++                              &*FirstNewBlock, IFI);
+ 
+     // Update the callgraph if requested.
+     if (IFI.CG)
+@@ -1077,7 +1081,7 @@
+       // reinserted.
+       Caller->getEntryBlock().getInstList().splice(InsertPoint,
+                                                    FirstNewBlock->getInstList(),
+-                                                   AI, I);
++                                                   AI->getIterator(), I);
+     }
+   }
+ 
+@@ -1123,7 +1127,7 @@
+   // Leave lifetime markers for the static alloca's, scoping them to the
+   // function we just inlined.
+   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
+-    IRBuilder<> builder(FirstNewBlock->begin());
++    IRBuilder<> builder(&FirstNewBlock->front());
+     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
+       AllocaInst *AI = IFI.StaticAllocas[ai];
+ 
+@@ -1172,8 +1176,9 @@
+     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
+ 
+     // Insert the llvm.stacksave.
+-    CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
+-      .CreateCall(StackSave, "savedstack");
++    CallInst *SavedPtr =
++      IRBuilder<>(&*FirstNewBlock,
++                  FirstNewBlock->begin()).CreateCall(StackSave, "savedstack");
+ 
+     // Insert a call to llvm.stackrestore before any return instructions in the
+     // inlined function.
+@@ -1189,7 +1194,7 @@
+   // If we are inlining for an invoke instruction, we must make sure to rewrite
+   // any call instructions into invoke instructions.
+   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
+-    HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
++    HandleInlinedInvoke(II, &*FirstNewBlock, InlinedFunctionInfo);
+ 
+   // Handle any inlined musttail call sites.  In order for a new call site to be
+   // musttail, the source of the clone and the inlined call site must have been
+@@ -1233,8 +1238,10 @@
+   // the calling basic block.
+   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
+     // Move all of the instructions right before the call.
+-    OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
+-                                 FirstNewBlock->begin(), FirstNewBlock->end());
++    OrigBB->getInstList().splice(TheCall->getIterator(),
++                                 FirstNewBlock->getInstList(),
++                                 FirstNewBlock->begin(),
++                                 FirstNewBlock->end());
+     // Remove the cloned basic block.
+     Caller->getBasicBlockList().pop_back();
+ 
+@@ -1280,14 +1287,15 @@
+     // Split the basic block.  This guarantees that no PHI nodes will have to be
+     // updated due to new incoming edges, and make the invoke case more
+     // symmetric to the call case.
+-    AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
+-                                          CalledFunc->getName()+".exit");
++    AfterCallBB =
++      OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
++                              CalledFunc->getName() + ".exit");
+ 
+   } else {  // It's a call
+     // If this is a call instruction, we need to split the basic block that
+     // the call lives in.
+     //
+-    AfterCallBB = OrigBB->splitBasicBlock(TheCall,
++    AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
+                                           CalledFunc->getName()+".exit");
+   }
+ 
+@@ -1297,13 +1305,14 @@
+   TerminatorInst *Br = OrigBB->getTerminator();
+   assert(Br && Br->getOpcode() == Instruction::Br &&
+          "splitBasicBlock broken!");
+-  Br->setOperand(0, FirstNewBlock);
++  Br->setOperand(0, &*FirstNewBlock);
+ 
+ 
+   // Now that the function is correct, make it a little bit nicer.  In
+   // particular, move the basic blocks inserted from the end of the function
+   // into the space made by splitting the source basic block.
+-  Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
++  Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
++                                     Caller->getBasicBlockList(),
+                                      FirstNewBlock, Caller->end());
+ 
+   // Handle all of the return instructions that we just cloned in, and eliminate
+@@ -1316,7 +1325,7 @@
+     // possible incoming values.
+     if (!TheCall->use_empty()) {
+       PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
+-                            AfterCallBB->begin());
++                            &AfterCallBB->front());
+       // Anything that used the result of the function call should now use the
+       // PHI node as their operand.
+       TheCall->replaceAllUsesWith(PHI);
+@@ -1396,7 +1405,7 @@
+   // Splice the code entry block into calling block, right before the
+   // unconditional branch.
+   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
+-  OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
++  OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
+ 
+   // Remove the unconditional branch.
+   OrigBB->getInstList().erase(Br);
+--- lib/Transforms/Utils/IntegerDivision.cpp	2014-11-05 13:28:24.000000000 -0800
++++ lib/Transforms/Utils/IntegerDivision.cpp	2015-11-29 12:34:15.372349168 -0800
+@@ -401,7 +401,7 @@
+     // If we didn't actually generate an urem instruction, we're done
+     // This happens for example if the input were constant. In this case the
+     // Builder insertion point was unchanged
+-    if (Rem == Builder.GetInsertPoint())
++    if (Rem == Builder.GetInsertPoint().getNodePtrUnchecked())
+       return true;
+ 
+     BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
+@@ -461,7 +461,7 @@
+     // If we didn't actually generate an udiv instruction, we're done
+     // This happens for example if the input were constant. In this case the
+     // Builder insertion point was unchanged
+-    if (Div == Builder.GetInsertPoint())
++    if (Div == Builder.GetInsertPoint().getNodePtrUnchecked())
+       return true;
+ 
+     BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
+--- lib/Transforms/Utils/LCSSA.cpp	2014-12-22 14:35:46.000000000 -0800
++++ lib/Transforms/Utils/LCSSA.cpp	2015-11-29 12:35:57.149304063 -0800
+@@ -113,7 +113,8 @@
+       continue;
+ 
+     PHINode *PN = PHINode::Create(Inst.getType(), PredCache.GetNumPreds(ExitBB),
+-                                  Inst.getName() + ".lcssa", ExitBB->begin());
++                                  Inst.getName() + ".lcssa",
++                                  &ExitBB->front());
+ 
+     // Add inputs from inside the loop for this PHI.
+     for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
+@@ -161,8 +162,9 @@
+     if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
+       // Tell the VHs that the uses changed. This updates SCEV's caches.
+       if (UsesToRewrite[i]->get()->hasValueHandle())
+-        ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin());
+-      UsesToRewrite[i]->set(UserBB->begin());
++        ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i],
++                                      &UserBB->front());
++      UsesToRewrite[i]->set(&UserBB->front());
+       continue;
+     }
+ 
+--- lib/Transforms/Utils/Local.cpp	2015-02-08 19:35:35.000000000 -0800
++++ lib/Transforms/Utils/Local.cpp	2015-11-29 12:57:42.322148975 -0800
+@@ -419,23 +419,24 @@
+   // or deleted by these simplifications. The idea of simplification is that it
+   // cannot introduce new instructions, and there is no way to replace the
+   // terminator of a block without introducing a new instruction.
+-  AssertingVH<Instruction> TerminatorVH(--BB->end());
++  AssertingVH<Instruction> TerminatorVH(&BB->back());
+ #endif
+ 
+   for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
+     assert(!BI->isTerminator());
+-    Instruction *Inst = BI++;
++    Instruction *Inst = &*BI;
++    ++BI;
+ 
+-    WeakVH BIHandle(BI);
++    WeakVH BIHandle(&*BI);
+     if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
+       MadeChange = true;
+-      if (BIHandle != BI)
++      if (BIHandle != &*BI)
+         BI = BB->begin();
+       continue;
+     }
+ 
+     MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
+-    if (BIHandle != BI)
++    if (BIHandle != &*BI)
+       BI = BB->begin();
+   }
+   return MadeChange;
+@@ -804,7 +805,8 @@
+ 
+     // Copy over any phi, debug or lifetime instruction.
+     BB->getTerminator()->eraseFromParent();
+-    Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
++    Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
++                               BB->getInstList());
+   } else {
+     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
+       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
+@@ -1054,8 +1056,8 @@
+   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
+   SmallVector<DbgDeclareInst *, 4> Dbgs;
+   for (auto &FI : F)
+-    for (BasicBlock::iterator BI : FI)
+-      if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
++    for (Instruction &BI : FI)
++      if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
+         Dbgs.push_back(DDI);
+ 
+   if (Dbgs.empty())
+@@ -1154,7 +1156,7 @@
+   new UnreachableInst(I->getContext(), I);
+ 
+   // All instructions after this are dead.
+-  BasicBlock::iterator BBI = I, BBE = BB->end();
++  BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
+   while (BBI != BBE) {
+     if (!BBI->use_empty())
+       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
+@@ -1208,7 +1210,7 @@
+ 
+           if (MakeUnreachable) {
+             // Don't insert a call to llvm.trap right before the unreachable.
+-            changeToUnreachable(BBI, false);
++            changeToUnreachable(&*BBI, false);
+             Changed = true;
+             break;
+           }
+@@ -1222,7 +1224,7 @@
+           ++BBI;
+           if (!isa<UnreachableInst>(BBI)) {
+             // Don't insert a call to llvm.trap right before the unreachable.
+-            changeToUnreachable(BBI, false);
++            changeToUnreachable(&*BBI, false);
+             Changed = true;
+           }
+           break;
+@@ -1279,7 +1281,7 @@
+ /// otherwise.
+ bool llvm::removeUnreachableBlocks(Function &F) {
+   SmallPtrSet<BasicBlock*, 128> Reachable;
+-  bool Changed = markAliveBlocks(F.begin(), Reachable);
++  bool Changed = markAliveBlocks(&F.front(), Reachable);
+ 
+   // If there are unreachable blocks in the CFG...
+   if (Reachable.size() == F.size())
+@@ -1291,17 +1293,18 @@
+   // Loop over all of the basic blocks that are not reachable, dropping all of
+   // their internal references...
+   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
+-    if (Reachable.count(BB))
++    if (Reachable.count(&*BB))
+       continue;
+ 
+-    for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
++    for (succ_iterator SI = succ_begin(&*BB), SE = succ_end(&*BB);
++         SI != SE; ++SI)
+       if (Reachable.count(*SI))
+-        (*SI)->removePredecessor(BB);
++        (*SI)->removePredecessor(&*BB);
+     BB->dropAllReferences();
+   }
+ 
+   for (Function::iterator I = ++F.begin(); I != F.end();)
+-    if (!Reachable.count(I))
++    if (!Reachable.count(&*I))
+       I = F.getBasicBlockList().erase(I);
+     else
+       ++I;
+--- lib/Transforms/Utils/LoopSimplify.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/LoopSimplify.cpp	2015-11-29 13:04:06.563171833 -0800
+@@ -76,7 +76,7 @@
+                                      SmallVectorImpl<BasicBlock *> &SplitPreds,
+                                      Loop *L) {
+   // Check to see if NewBB is already well placed.
+-  Function::iterator BBI = NewBB; --BBI;
++  Function::iterator BBI = --NewBB->getIterator();
+   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
+     if (&*BBI == SplitPreds[i])
+       return;
+@@ -90,9 +90,8 @@
+   // block that neighbors a BB actually in the loop.
+   BasicBlock *FoundBB = nullptr;
+   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
+-    Function::iterator BBI = SplitPreds[i];
+-    if (++BBI != NewBB->getParent()->end() &&
+-        L->contains(BBI)) {
++    Function::iterator BBI = SplitPreds[i]->getIterator();
++    if (++BBI != NewBB->getParent()->end() && L->contains(&*BBI)) {
+       FoundBB = SplitPreds[i];
+       break;
+     }
+@@ -392,7 +391,7 @@
+                << BEBlock->getName() << "\n");
+ 
+   // Move the new backedge block to right after the last backedge block.
+-  Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
++  Function::iterator InsertPos = ++BackedgeBlocks.back()->getIterator();
+   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
+ 
+   // Now that the block has been inserted into the function, create PHI nodes in
+@@ -651,7 +650,7 @@
+       bool AllInvariant = true;
+       bool AnyInvariant = false;
+       for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
+-        Instruction *Inst = I++;
++        Instruction *Inst = &*I++;
+         // Skip debug info intrinsics.
+         if (isa<DbgInfoIntrinsic>(Inst))
+           continue;
+--- lib/Transforms/Utils/LoopUnrollRuntime.cpp	2015-02-18 14:51:15.000000000 -0800
++++ lib/Transforms/Utils/LoopUnrollRuntime.cpp	2015-11-29 13:08:21.195493550 -0800
+@@ -207,9 +207,9 @@
+   // Change the incoming values to the ones defined in the preheader or
+   // cloned loop.
+   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
+-    PHINode *NewPHI = cast<PHINode>(VMap[I]);
++    PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
+     if (UnrollProlog) {
+-      VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
++      VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
+       cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
+     } else {
+       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
+@@ -390,8 +390,8 @@
+                   VMap, LI);
+ 
+   // Insert the cloned blocks into function just before the original loop
+-  F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
+-                                F->end());
++  F->getBasicBlockList().splice(PEnd->getIterator(), F->getBasicBlockList(),
++                                NewBlocks[0]->getIterator(), F->end());
+ 
+   // Rewrite the cloned instruction operands to use the values
+   // created when the clone is created.
+@@ -399,7 +399,7 @@
+     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
+                               E = NewBlocks[i]->end();
+          I != E; ++I) {
+-      RemapInstruction(I, VMap,
++      RemapInstruction(&*I, VMap,
+                        RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
+     }
+   }
+--- lib/Transforms/Utils/LoopUnroll.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/LoopUnroll.cpp	2015-11-29 13:06:17.558243110 -0800
+@@ -383,7 +383,7 @@
+     for (unsigned i = 0; i < NewBlocks.size(); ++i)
+       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
+            E = NewBlocks[i]->end(); I != E; ++I)
+-        ::RemapInstruction(I, LastValueMap);
++        ::RemapInstruction(&*I, LastValueMap);
+   }
+ 
+   // Loop over the PHI nodes in theinal block, setting incoming values.
+@@ -504,7 +504,7 @@
+   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
+        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
+     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
+-      Instruction *Inst = I++;
++      Instruction *Inst = &*I++;
+ 
+       if (isInstructionTriviallyDead(Inst))
+         (*BB)->getInstList().erase(Inst);
+--- lib/Transforms/Utils/LowerExpectIntrinsic.cpp	2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/Utils/LowerExpectIntrinsic.cpp	2015-11-29 13:09:35.298686663 -0800
+@@ -148,7 +148,7 @@
+ 
+ bool LowerExpectIntrinsic::runOnFunction(Function &F) {
+   for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
+-    BasicBlock *BB = I++;
++    BasicBlock *BB = &*I++;
+ 
+     // Create "block_weights" metadata.
+     if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
+--- lib/Transforms/Utils/LowerInvoke.cpp	2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/Utils/LowerInvoke.cpp	2015-11-29 13:18:52.019842685 -0800
+@@ -69,7 +69,7 @@
+       BranchInst::Create(II->getNormalDest(), II);
+ 
+       // Remove any PHI node entries from the exception destination.
+-      II->getUnwindDest()->removePredecessor(BB);
++      II->getUnwindDest()->removePredecessor(&*BB);
+ 
+       // Remove the invoke instruction now.
+       BB->getInstList().erase(II);
+--- lib/Transforms/Utils/LowerSwitch.cpp	2015-01-28 09:35:18.000000000 -0800
++++ lib/Transforms/Utils/LowerSwitch.cpp	2015-11-29 13:39:46.489837410 -0800
+@@ -101,7 +101,8 @@
+   bool Changed = false;
+ 
+   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
+-    BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
++    BasicBlock *Cur = &*I; // Advance over block so we don't traverse new blocks
++    ++I;
+ 
+     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
+       Changed = true;
+@@ -142,7 +143,8 @@
+ // number of phi values equal to the number of branches to SuccBB.
+ static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
+                     unsigned NumMergedCases) {
+-  for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
++  for (BasicBlock::iterator I = SuccBB->begin(),
++       IE = SuccBB->getFirstNonPHI()->getIterator();
+        I != IE; ++I) {
+     PHINode *PN = cast<PHINode>(I);
+ 
+@@ -256,8 +258,7 @@
+                                       UpperBound, Val, NewNode, OrigBlock,
+                                       Default);
+ 
+-  Function::iterator FI = OrigBlock;
+-  F->getBasicBlockList().insert(++FI, NewNode);
++  F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
+   NewNode->getInstList().push_back(Comp);
+ 
+   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
+@@ -276,8 +277,7 @@
+ {
+   Function* F = OrigBlock->getParent();
+   BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
+-  Function::iterator FI = OrigBlock;
+-  F->getBasicBlockList().insert(++FI, NewLeaf);
++  F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
+ 
+   // Emit comparison
+   ICmpInst* Comp = nullptr;
+@@ -395,8 +395,7 @@
+   BasicBlock *NewDefault = nullptr;
+   if (!DefaultIsUnreachable) {
+     NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
+-    F->getBasicBlockList().insert(Default, NewDefault);
+-
++    F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
+     BranchInst::Create(Default, NewDefault);
+   }
+   // If there is an entry in any PHI nodes for the default edge, make sure
+--- lib/Transforms/Utils/PromoteMemoryToRegister.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/PromoteMemoryToRegister.cpp	2015-11-29 13:44:30.613019495 -0800
+@@ -214,10 +214,11 @@
+     // avoid gratuitus rescans.
+     const BasicBlock *BB = I->getParent();
+     unsigned InstNo = 0;
+-    for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end(); BBI != E;
+-         ++BBI)
+-      if (isInterestingInstruction(BBI))
+-        InstNumbers[BBI] = InstNo++;
++
++    for (const Instruction &BBI : *BB)
++      if (isInterestingInstruction(&BBI))
++        InstNumbers[&BBI] = InstNo++;
++
+     It = InstNumbers.find(I);
+ 
+     assert(It != InstNumbers.end() && "Didn't insert instruction?");
+@@ -602,7 +603,7 @@
+     if (BBNumbers.empty()) {
+       unsigned ID = 0;
+       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
+-        BBNumbers[I] = ID++;
++        BBNumbers[&*I] = ID++;
+     }
+ 
+     // If we have an AST to keep updated, remember some pointer value that is
+@@ -641,7 +642,7 @@
+   // and inserting the phi nodes we marked as necessary
+   //
+   std::vector<RenamePassData> RenamePassWorkList;
+-  RenamePassWorkList.push_back(RenamePassData(F.begin(), nullptr, Values));
++  RenamePassWorkList.push_back(RenamePassData(&F.front(), nullptr, Values));
+   do {
+     RenamePassData RPD;
+     RPD.swap(RenamePassWorkList.back());
+@@ -946,7 +947,7 @@
+   // BasicBlock.
+   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
+                        Allocas[AllocaNo]->getName() + "." + Twine(Version++),
+-                       BB->begin());
++                       &BB->front());
+   ++NumPHIInsert;
+   PhiToAllocaMap[PN] = AllocaNo;
+ 
+@@ -1011,7 +1012,8 @@
+     return;
+ 
+   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
+-    Instruction *I = II++; // get the instruction, increment iterator
++    Instruction *I = &*II; // get the instruction, increment iterator
++    ++II;
+ 
+     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
+       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
+--- lib/Transforms/Utils/SimplifyCFG.cpp	2015-01-12 20:17:47.000000000 -0800
++++ lib/Transforms/Utils/SimplifyCFG.cpp	2015-11-29 15:07:34.912976680 -0800
+@@ -1091,15 +1091,15 @@
+   BasicBlock::iterator BB1_Itr = BB1->begin();
+   BasicBlock::iterator BB2_Itr = BB2->begin();
+ 
+-  Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
++  Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
+   // Skip debug info if it is not identical.
+   DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
+   DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
+   if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
+     while (isa<DbgInfoIntrinsic>(I1))
+-      I1 = BB1_Itr++;
++      I1 = &*BB1_Itr++;
+     while (isa<DbgInfoIntrinsic>(I2))
+-      I2 = BB2_Itr++;
++      I2 = &*BB2_Itr++;
+   }
+   if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
+       (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
+@@ -1117,7 +1117,7 @@
+     // For a normal instruction, we just move one to right before the branch,
+     // then replace all uses of the other with the first.  Finally, we remove
+     // the now redundant second instruction.
+-    BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
++    BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
+     if (!I2->use_empty())
+       I2->replaceAllUsesWith(I1);
+     I1->intersectOptionalDataWith(I2);
+@@ -1132,16 +1132,16 @@
+     I2->eraseFromParent();
+     Changed = true;
+ 
+-    I1 = BB1_Itr++;
+-    I2 = BB2_Itr++;
++    I1 = &*BB1_Itr++;
++    I2 = &*BB2_Itr++;
+     // Skip debug info if it is not identical.
+     DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
+     DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
+     if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
+       while (isa<DbgInfoIntrinsic>(I1))
+-        I1 = BB1_Itr++;
++        I1 = &*BB1_Itr++;
+       while (isa<DbgInfoIntrinsic>(I2))
+-        I2 = BB2_Itr++;
++        I2 = &*BB2_Itr++;
+     }
+   } while (I1->isIdenticalToWhenDefined(I2));
+ 
+@@ -1176,7 +1176,7 @@
+ 
+   // Okay, it is safe to hoist the terminator.
+   Instruction *NT = I1->clone();
+-  BIParent->getInstList().insert(BI, NT);
++  BIParent->getInstList().insert(BI->getIterator(), NT);
+   if (!NT->getType()->isVoidTy()) {
+     I1->replaceAllUsesWith(NT);
+     I2->replaceAllUsesWith(NT);
+@@ -1353,7 +1353,7 @@
+       if (!NewPN) {
+         NewPN =
+             PHINode::Create(DifferentOp1->getType(), 2,
+-                            DifferentOp1->getName() + ".sink", BBEnd->begin());
++                            DifferentOp1->getName() + ".sink", &BBEnd->front());
+         NewPN->addIncoming(DifferentOp1, BB1);
+         NewPN->addIncoming(DifferentOp2, BB2);
+         DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
+@@ -1368,7 +1368,8 @@
+     // instruction in the basic block down.
+     bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
+     // Sink the instruction.
+-    BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
++    BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
++                                BB1->getInstList(), I1);
+     if (!OldPN->use_empty())
+       OldPN->replaceAllUsesWith(I1);
+     OldPN->eraseFromParent();
+@@ -1520,7 +1521,7 @@
+   for (BasicBlock::iterator BBI = ThenBB->begin(),
+                             BBE = std::prev(ThenBB->end());
+        BBI != BBE; ++BBI) {
+-    Instruction *I = BBI;
++    Instruction *I = &*BBI;
+     // Skip debug info.
+     if (isa<DbgInfoIntrinsic>(I))
+       continue;
+@@ -1632,8 +1633,8 @@
+   }
+ 
+   // Hoist the instructions.
+-  BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
+-                           std::prev(ThenBB->end()));
++  BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
++                           ThenBB->begin(), std::prev(ThenBB->end()));
+ 
+   // Insert selects and rewrite the PHI operands.
+   IRBuilder<true, NoFolder> Builder(BI);
+@@ -1776,13 +1777,13 @@
+ 
+       // Check for trivial simplification.
+       if (Value *V = SimplifyInstruction(N, DL)) {
+-        TranslateMap[BBI] = V;
++        TranslateMap[&*BBI] = V;
+         delete N;   // Instruction folded away, don't need actual inst
+       } else {
+         // Insert the new instruction into its new home.
+         EdgeBB->getInstList().insert(InsertPt, N);
+         if (!BBI->use_empty())
+-          TranslateMap[BBI] = N;
++          TranslateMap[&*BBI] = N;
+       }
+     }
+ 
+@@ -1875,8 +1876,9 @@
+     IfBlock1 = nullptr;
+   } else {
+     DomBlock = *pred_begin(IfBlock1);
+-    for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
+-      if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
++    for (BasicBlock::iterator I = IfBlock1->begin();
++         !isa<TerminatorInst>(I); ++I)
++      if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
+         // This is not an aggressive instruction that we can promote.
+         // Because of this, we won't be able to get rid of the control
+         // flow, so the xform is not worth it.
+@@ -1888,8 +1890,9 @@
+     IfBlock2 = nullptr;
+   } else {
+     DomBlock = *pred_begin(IfBlock2);
+-    for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
+-      if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
++    for (BasicBlock::iterator I = IfBlock2->begin();
++         !isa<TerminatorInst>(I); ++I)
++      if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
+         // This is not an aggressive instruction that we can promote.
+         // Because of this, we won't be able to get rid of the control
+         // flow, so the xform is not worth it.
+@@ -1908,13 +1911,13 @@
+   // Move all 'aggressive' instructions, which are defined in the
+   // conditional parts of the if's up to the dominating block.
+   if (IfBlock1)
+-    DomBlock->getInstList().splice(InsertPt,
++    DomBlock->getInstList().splice(InsertPt->getIterator(),
+                                    IfBlock1->getInstList(), IfBlock1->begin(),
+-                                   IfBlock1->getTerminator());
++                                   IfBlock1->getTerminator()->getIterator());
+   if (IfBlock2)
+-    DomBlock->getInstList().splice(InsertPt,
++    DomBlock->getInstList().splice(InsertPt->getIterator(),
+                                    IfBlock2->getInstList(), IfBlock2->begin(),
+-                                   IfBlock2->getTerminator());
++                                   IfBlock2->getTerminator()->getIterator());
+ 
+   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
+     // Change the PHI node into a select instruction.
+@@ -2086,7 +2089,8 @@
+              BI->getSuccessor(0) == PBI->getSuccessor(1))) {
+           for (BasicBlock::iterator I = BB->begin(), E = BB->end();
+                I != E; ) {
+-            Instruction *Curr = I++;
++            Instruction *Curr = &*I;
++            ++I;
+             if (isa<CmpInst>(Curr)) {
+               Cond = Curr;
+               break;
+@@ -2106,7 +2110,7 @@
+   return false;
+ 
+   // Make sure the instruction after the condition is the cond branch.
+-  BasicBlock::iterator CondIt = Cond; ++CondIt;
++  BasicBlock::iterator CondIt = ++Cond->getIterator();
+ 
+   // Ignore dbg intrinsics.
+   while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
+@@ -2124,7 +2128,7 @@
+     // Ignore dbg intrinsics.
+     if (isa<DbgInfoIntrinsic>(I))
+       continue;
+-    if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
++    if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I, DL))
+       return false;
+     // I has only one use and can be executed unconditionally.
+     Instruction *User = dyn_cast<Instruction>(I->user_back());
+@@ -2221,7 +2225,7 @@
+       Instruction *NewBonusInst = BonusInst->clone();
+       RemapInstruction(NewBonusInst, VMap,
+                        RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
+-      VMap[BonusInst] = NewBonusInst;
++      VMap[&*BonusInst] = NewBonusInst;
+ 
+       // If we moved a load, we cannot any longer claim any knowledge about
+       // its potential value. The previous information might have been valid
+@@ -2230,8 +2234,8 @@
+       // semantics we don't understand.
+       NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
+ 
+-      PredBlock->getInstList().insert(PBI, NewBonusInst);
+-      NewBonusInst->takeName(BonusInst);
++      PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
++      NewBonusInst->takeName(&*BonusInst);
+       BonusInst->setName(BonusInst->getName() + ".old");
+     }
+ 
+@@ -2240,7 +2244,7 @@
+     Instruction *New = Cond->clone();
+     RemapInstruction(New, VMap,
+                      RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
+-    PredBlock->getInstList().insert(PBI, New);
++    PredBlock->getInstList().insert(PBI->getIterator(), New);
+     New->takeName(Cond);
+     Cond->setName(New->getName() + ".old");
+ 
+@@ -2392,7 +2396,7 @@
+       PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
+                                        std::distance(PB, PE),
+                                        BI->getCondition()->getName() + ".pr",
+-                                       BB->begin());
++                                       &BB->front());
+       // Okay, we're going to insert the PHI node.  Since PBI is not the only
+       // predecessor, compute the PHI'd conditional value for all of the preds.
+       // Any predecessor where the condition is not computable we keep symbolic.
+@@ -2877,7 +2881,9 @@
+   // then we evaluate them with an explicit branch first.  Split the block
+   // right before the condbr to handle it.
+   if (ExtraCase) {
+-    BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
++    BasicBlock *NewBB =
++      BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
++
+     // Remove the uncond branch added to the old block.
+     TerminatorInst *OldTI = BB->getTerminator();
+     Builder.SetInsertPoint(OldTI);
+@@ -2943,7 +2949,7 @@
+     return false;
+ 
+   // Check that there are no other instructions except for debug intrinsics.
+-  BasicBlock::iterator I = LPInst, E = RI;
++  BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
+   while (++I != E)
+     if (!isa<DbgInfoIntrinsic>(I))
+       return false;
+@@ -3049,8 +3055,8 @@
+ 
+   // If there are any instructions immediately before the unreachable that can
+   // be removed, do so.
+-  while (UI != BB->begin()) {
+-    BasicBlock::iterator BBI = UI;
++  while (UI->getIterator() != BB->begin()) {
++    BasicBlock::iterator BBI = UI->getIterator();
+     --BBI;
+     // Do not delete instructions that can have side effects which might cause
+     // the unreachable to not be reachable; specifically, calls and volatile
+@@ -3484,7 +3490,7 @@
+     } else if (isa<DbgInfoIntrinsic>(I)) {
+       // Skip debug intrinsic.
+       continue;
+-    } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
++    } else if (Constant *C = ConstantFold(&*I, ConstantPool, DL)) {
+       // Instruction is side-effect free and constant.
+ 
+       // If the instruction has uses outside this block or a phi node slot for
+@@ -3501,7 +3507,7 @@
+         return false;
+       }
+ 
+-      ConstantPool.insert(std::make_pair(I, C));
++      ConstantPool.insert(std::make_pair(&*I, C));
+     } else {
+       break;
+     }
+@@ -4399,7 +4405,7 @@
+     return true;
+ 
+   // If the Terminator is the only non-phi instruction, simplify the block.
+-  BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
++  BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
+   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
+       TryToSimplifyUncondBranchFromEmptyBlock(BB))
+     return true;
+--- lib/Transforms/Utils/SimplifyInstructions.cpp	2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/SimplifyInstructions.cpp	2015-11-29 15:09:24.682261310 -0800
+@@ -63,8 +63,11 @@
+         for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
+           // Here be subtlety: the iterator must be incremented before the loop
+           // body (not sure why), so a range-for loop won't work here.
+-          for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
+-            Instruction *I = BI++;
++          for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
++               BI != BE; /* inside loop */) {
++            Instruction *I = &*BI;
++            ++BI;
++
+             // The first time through the loop ToSimplify is empty and we try to
+             // simplify all instructions.  On later iterations ToSimplify is not
+             // empty and we only bother simplifying instructions that are in it.
+--- lib/Transforms/Utils/SimplifyLibCalls.cpp	2015-01-28 11:15:34.000000000 -0800
++++ lib/Transforms/Utils/SimplifyLibCalls.cpp	2015-11-29 15:11:56.561911410 -0800
+@@ -1338,8 +1338,7 @@
+   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
+     // If the argument is an instruction, it must dominate all uses so put our
+     // sincos call there.
+-    BasicBlock::iterator Loc = ArgInst;
+-    B.SetInsertPoint(ArgInst->getParent(), ++Loc);
++    B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
+   } else {
+     // Otherwise (e.g. for a constant) the beginning of the function is as
+     // good a place as any.
+--- lib/Transforms/Utils/UnifyFunctionExitNodes.cpp	2015-01-28 09:35:18.000000000 -0800
++++ lib/Transforms/Utils/UnifyFunctionExitNodes.cpp	2015-11-29 15:14:01.147224983 -0800
+@@ -50,11 +50,12 @@
+   //
+   std::vector<BasicBlock*> ReturningBlocks;
+   std::vector<BasicBlock*> UnreachableBlocks;
+-  for(Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
+-    if (isa<ReturnInst>(I->getTerminator()))
+-      ReturningBlocks.push_back(I);
+-    else if (isa<UnreachableInst>(I->getTerminator()))
+-      UnreachableBlocks.push_back(I);
++
++  for (BasicBlock &I : F)
++    if (isa<ReturnInst>(I.getTerminator()))
++      ReturningBlocks.push_back(&I);
++    else if (isa<UnreachableInst>(I.getTerminator()))
++      UnreachableBlocks.push_back(&I);
+ 
+   // Then unreachable blocks.
+   if (UnreachableBlocks.empty()) {
+--- lib/Transforms/Vectorize/BBVectorize.cpp	2014-12-19 09:21:38.000000000 -0800
++++ lib/Transforms/Vectorize/BBVectorize.cpp	2015-12-06 09:35:21.191615227 -0800
+@@ -1243,12 +1243,13 @@
+       if (I == Start) IAfterStart = true;
+ 
+       bool IsSimpleLoadStore;
+-      if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
++      if (!isInstVectorizable(&*I, IsSimpleLoadStore)) continue;
+ 
+       // Look for an instruction with which to pair instruction *I...
+       DenseSet<Value *> Users;
+       AliasSetTracker WriteSet(*AA);
+-      if (I->mayWriteToMemory()) WriteSet.add(I);
++      if (I->mayWriteToMemory())
++        WriteSet.add(&*I);
+ 
+       bool JAfterStart = IAfterStart;
+       BasicBlock::iterator J = std::next(I);
+@@ -1256,7 +1257,7 @@
+         if (J == Start) JAfterStart = true;
+ 
+         // Determine if J uses I, if so, exit the loop.
+-        bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
++        bool UsesI = trackUsesOfI(Users, WriteSet, &*I, &*J, !Config.FastDep);
+         if (Config.FastDep) {
+           // Note: For this heuristic to be effective, independent operations
+           // must tend to be intermixed. This is likely to be true from some
+@@ -1273,25 +1274,26 @@
+         // J does not use I, and comes before the first use of I, so it can be
+         // merged with I if the instructions are compatible.
+         int CostSavings, FixedOrder;
+-        if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
+-            CostSavings, FixedOrder)) continue;
++        if (!areInstsCompatible(&*I, &*J, IsSimpleLoadStore, NonPow2Len,
++                                CostSavings, FixedOrder))
++          continue;
+ 
+         // J is a candidate for merging with I.
+         if (!PairableInsts.size() ||
+-             PairableInsts[PairableInsts.size()-1] != I) {
+-          PairableInsts.push_back(I);
++             PairableInsts[PairableInsts.size()-1] != &*I) {
++          PairableInsts.push_back(&*I);
+         }
+ 
+-        CandidatePairs[I].push_back(J);
++        CandidatePairs[&*I].push_back(&*J);
+         ++TotalPairs;
+         if (TTI)
+-          CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
+-                                                            CostSavings));
++          CandidatePairCostSavings.insert(
++            ValuePairWithCost(ValuePair(&*I, &*J), CostSavings));
+ 
+         if (FixedOrder == 1)
+-          FixedOrderPairs.insert(ValuePair(I, J));
++          FixedOrderPairs.insert(ValuePair(&*I, &*J));
+         else if (FixedOrder == -1)
+-          FixedOrderPairs.insert(ValuePair(J, I));
++          FixedOrderPairs.insert(ValuePair(&*J, &*I));
+ 
+         // The next call to this function must start after the last instruction
+         // selected during this invocation.
+@@ -1472,14 +1474,15 @@
+     BasicBlock::iterator E = BB.end(), EL =
+       BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
+     for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
+-      if (IsInPair.find(I) == IsInPair.end()) continue;
++      if (IsInPair.find(&*I) == IsInPair.end())
++        continue;
+ 
+       DenseSet<Value *> Users;
+       AliasSetTracker WriteSet(*AA);
+-      if (I->mayWriteToMemory()) WriteSet.add(I);
++      if (I->mayWriteToMemory()) WriteSet.add(&*I);
+ 
+       for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
+-        (void) trackUsesOfI(Users, WriteSet, I, J);
++        (void) trackUsesOfI(Users, WriteSet, &*I, &*J);
+ 
+         if (J == EL)
+           break;
+@@ -1488,7 +1491,7 @@
+       for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
+            U != E; ++U) {
+         if (IsInPair.find(*U) == IsInPair.end()) continue;
+-        PairableInstUsers.insert(ValuePair(I, *U));
++        PairableInstUsers.insert(ValuePair(&*I, *U));
+       }
+ 
+       if (I == EL)
+@@ -2873,7 +2876,7 @@
+     if (I->mayWriteToMemory()) WriteSet.add(I);
+ 
+     for (; cast<Instruction>(L) != J; ++L)
+-      (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
++      (void) trackUsesOfI(Users, WriteSet, I, &*L, true, &LoadMoveSetPairs);
+ 
+     assert(cast<Instruction>(L) == J &&
+       "Tracking has not proceeded far enough to check for dependencies");
+@@ -2895,9 +2898,10 @@
+     if (I->mayWriteToMemory()) WriteSet.add(I);
+ 
+     for (; cast<Instruction>(L) != J;) {
+-      if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
++      if (trackUsesOfI(Users, WriteSet, I, &*L, true, &LoadMoveSetPairs)) {
+         // Move this instruction
+-        Instruction *InstToMove = L; ++L;
++        Instruction *InstToMove = &*L;
++        ++L;
+ 
+         DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
+                         " to after " << *InsertionPt << "\n");
+@@ -2929,10 +2933,10 @@
+     // farther down the use chain by another instruction pairing. Also, J
+     // could be before I if this is an inverted input.
+     for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
+-      if (trackUsesOfI(Users, WriteSet, I, L)) {
++      if (trackUsesOfI(Users, WriteSet, I, &*L)) {
+         if (L->mayReadFromMemory()) {
+-          LoadMoveSet[L].push_back(I);
+-          LoadMoveSetPairs.insert(ValuePair(L, I));
++          LoadMoveSet[&*L].push_back(I);
++          LoadMoveSetPairs.insert(ValuePair(&*L, I));
+         }
+       }
+     }
+@@ -2995,7 +2999,7 @@
+     DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
+ 
+     for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
+-      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
++      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(&*PI);
+       if (P == ChosenPairs.end()) {
+         ++PI;
+         continue;
+--- lib/Transforms/Vectorize/LoopVectorize.cpp	2015-02-17 13:53:25.000000000 -0800
++++ lib/Transforms/Vectorize/LoopVectorize.cpp	2015-12-06 11:41:36.696287648 -0800
+@@ -462,6 +462,10 @@
+   Value *ExtendedIdx;
+   /// Maps scalars to widened vectors.
+   ValueMap WidenMap;
++  /// Store instructions that should be predicated, as a pair
++  ///    <StoreInst, Predicate>
++  SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
++
+   EdgeMaskCache MaskCache;
+ 
+   LoopVectorizationLegality *Legal;
+@@ -1965,36 +1969,31 @@
+   // Create a new entry in the WidenMap and initialize it to Undef or Null.
+   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
+ 
+-  Instruction *InsertPt = Builder.GetInsertPoint();
+-  BasicBlock *IfBlock = Builder.GetInsertBlock();
+-  BasicBlock *CondBlock = nullptr;
++  // Instruction *InsertPt = Builder.GetInsertPoint();
++  // BasicBlock *IfBlock = Builder.GetInsertBlock();
++  // BasicBlock *CondBlock = nullptr;
+ 
+   VectorParts Cond;
+-  Loop *VectorLp = nullptr;
++  //  Loop *VectorLp = nullptr;
+   if (IfPredicateStore) {
+     assert(Instr->getParent()->getSinglePredecessor() &&
+            "Only support single predecessor blocks");
+     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
+                           Instr->getParent());
+-    VectorLp = LI->getLoopFor(IfBlock);
+-    assert(VectorLp && "Must have a loop for this block");
++    // VectorLp = LI->getLoopFor(IfBlock);
++    // assert(VectorLp && "Must have a loop for this block");
+   }
+ 
+   // For each vector unroll 'part':
+   for (unsigned Part = 0; Part < UF; ++Part) {
+     // For each scalar that we create:
+     for (unsigned Width = 0; Width < VF; ++Width) {
+-
+       // Start if-block.
+       Value *Cmp = nullptr;
+       if (IfPredicateStore) {
+         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
+-        Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
+-        CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
+-        LoopVectorBody.push_back(CondBlock);
+-        VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
+-        // Update Builder with newly created basic block.
+-        Builder.SetInsertPoint(InsertPt);
++        Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp,
++                                 ConstantInt::get(Cmp->getType(), 1));
+       }
+ 
+       Instruction *Cloned = Instr->clone();
+@@ -2019,6 +2018,7 @@
+                                                        Builder.getInt32(Width));
+       // End if-block.
+       if (IfPredicateStore) {
++#if 0
+          BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
+          LoopVectorBody.push_back(NewIfBlock);
+          VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
+@@ -2027,6 +2027,9 @@
+          BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
+          OldBr->eraseFromParent();
+          IfBlock = NewIfBlock;
++#endif
++         PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
++                                                   Cmp));
+       }
+     }
+   }
+@@ -2283,13 +2286,17 @@
+ 
+   // Split the single block loop into the two loop structure described above.
+   BasicBlock *VectorPH =
+-  BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
++  BypassBlock->splitBasicBlock(BypassBlock->getTerminator()->getIterator(),
++                               "vector.ph");
+   BasicBlock *VecBody =
+-  VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
++  VectorPH->splitBasicBlock(VectorPH->getTerminator()->getIterator(),
++                            "vector.body");
+   BasicBlock *MiddleBlock =
+-  VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
++  VecBody->splitBasicBlock(VecBody->getTerminator()->getIterator(),
++                           "middle.block");
+   BasicBlock *ScalarPH =
+-  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
++  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator()->getIterator(),
++                               "scalar.ph");
+ 
+   // Create and register the new vector loop.
+   Loop* Lp = new Loop();
+@@ -2378,7 +2385,8 @@
+   if (StrideCheck) {
+     // Create a new block containing the stride check.
+     BasicBlock *CheckBlock =
+-        LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
++        LastBypassBlock->splitBasicBlock(FirstCheckInst->getIterator(),
++                                         "vector.stridecheck");
+     if (ParentLoop)
+       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
+     LoopBypassBlocks.push_back(CheckBlock);
+@@ -2402,7 +2410,8 @@
+   if (MemRuntimeCheck) {
+     // Create a new block containing the memory check.
+     BasicBlock *CheckBlock =
+-        LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
++        LastBypassBlock->splitBasicBlock(MemRuntimeCheck->getIterator(),
++                                         "vector.memcheck");
+     if (ParentLoop)
+       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
+     LoopBypassBlocks.push_back(CheckBlock);
+@@ -2590,7 +2599,7 @@
+   VecBody->getTerminator()->eraseFromParent();
+ 
+   // Get ready to start creating new instructions into the vectorized body.
+-  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
++  Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
+ 
+   // Save the state.
+   LoopVectorPreHeader = VectorPH;
+@@ -2739,7 +2748,8 @@
+   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
+     BasicBlock *BB = BBs[i];
+     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
+-      Instruction *In = I++;
++      Instruction *In = &*I;
++      ++I;
+ 
+       if (!CSEDenseMapInfo::canHandle(In))
+         continue;
+@@ -2890,7 +2900,7 @@
+     // the PHIs and the values we are going to write.
+     // This allows us to write both PHINodes and the extractelement
+     // instructions.
+-    Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
++    Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
+ 
+     VectorParts RdxParts;
+     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
+@@ -3000,6 +3010,9 @@
+ 
+   fixLCSSAPHIs();
+ 
++  // Make sure DomTree is updated.
++  updateAnalysis();
++
+   // Remove redundant induction instructions.
+   cse(LoopVectorBody);
+ }
+@@ -3084,8 +3097,9 @@
+       // This is phase one of vectorizing PHIs.
+       Type *VecTy = (VF == 1) ? PN->getType() :
+       VectorType::get(PN->getType(), VF);
+-      Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
+-                                    LoopVectorBody.back()-> getFirstInsertionPt());
++      Entry[part] =
++        PHINode::Create(VecTy, 2, "vec.phi",
++                        &*LoopVectorBody.back()->getFirstInsertionPt());
+     }
+     PV->push_back(P);
+     return;
+@@ -3240,7 +3254,7 @@
+ void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
+   // For each instruction in the old loop.
+   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
+-    VectorParts &Entry = WidenMap.get(it);
++    VectorParts &Entry = WidenMap.get(&*it);
+     switch (it->getOpcode()) {
+     case Instruction::Br:
+       // Nothing to do for PHIs and BR, since we already took care of the
+@@ -3248,7 +3262,7 @@
+       continue;
+     case Instruction::PHI:{
+       // Vectorize PHINodes.
+-      widenPHIInstruction(it, Entry, UF, VF, PV);
++      widenPHIInstruction(&*it, Entry, UF, VF, PV);
+       continue;
+     }// End of PHI.
+ 
+@@ -3286,7 +3300,7 @@
+         Entry[Part] = V;
+       }
+ 
+-      propagateMetadata(Entry, it);
++      propagateMetadata(Entry, &*it);
+       break;
+     }
+     case Instruction::Select: {
+@@ -3295,7 +3309,7 @@
+       // instruction with a scalar condition. Otherwise, use vector-select.
+       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
+                                                OrigLoop);
+-      setDebugLocFromInst(Builder, it);
++      setDebugLocFromInst(Builder, &*it);
+ 
+       // The condition can be loop invariant  but still defined inside the
+       // loop. This means that we can't just use theinal 'cond' value.
+@@ -3315,7 +3329,7 @@
+           Op1[Part]);
+       }
+ 
+-      propagateMetadata(Entry, it);
++      propagateMetadata(Entry, &*it);
+       break;
+     }
+ 
+@@ -3324,7 +3338,7 @@
+       // Widen compares. Generate vector compares.
+       bool FCmp = (it->getOpcode() == Instruction::FCmp);
+       CmpInst *Cmp = dyn_cast<CmpInst>(it);
+-      setDebugLocFromInst(Builder, it);
++      setDebugLocFromInst(Builder, &*it);
+       VectorParts &A = getVectorValue(it->getOperand(0));
+       VectorParts &B = getVectorValue(it->getOperand(1));
+       for (unsigned Part = 0; Part < UF; ++Part) {
+@@ -3336,13 +3350,13 @@
+         Entry[Part] = C;
+       }
+ 
+-      propagateMetadata(Entry, it);
++      propagateMetadata(Entry, &*it);
+       break;
+     }
+ 
+     case Instruction::Store:
+     case Instruction::Load:
+-      vectorizeMemoryInstruction(it);
++      vectorizeMemoryInstruction(&*it);
+         break;
+     case Instruction::ZExt:
+     case Instruction::SExt:
+@@ -3357,7 +3371,7 @@
+     case Instruction::FPTrunc:
+     case Instruction::BitCast: {
+       CastInst *CI = dyn_cast<CastInst>(it);
+-      setDebugLocFromInst(Builder, it);
++      setDebugLocFromInst(Builder, &*it);
+       /// Optimize the special case where the source is the induction
+       /// variable. Notice that we can only optimize the 'trunc' case
+       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
+@@ -3369,7 +3383,7 @@
+         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
+         for (unsigned Part = 0; Part < UF; ++Part)
+           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
+-        propagateMetadata(Entry, it);
++        propagateMetadata(Entry, &*it);
+         break;
+       }
+       /// Vectorize casts.
+@@ -3379,7 +3393,7 @@
+       VectorParts &A = getVectorValue(it->getOperand(0));
+       for (unsigned Part = 0; Part < UF; ++Part)
+         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
+-      propagateMetadata(Entry, it);
++      propagateMetadata(Entry, &*it);
+       break;
+     }
+ 
+@@ -3387,7 +3401,7 @@
+       // Ignore dbg intrinsics.
+       if (isa<DbgInfoIntrinsic>(it))
+         break;
+-      setDebugLocFromInst(Builder, it);
++      setDebugLocFromInst(Builder, &*it);
+ 
+       Module *M = BB->getParent()->getParent();
+       CallInst *CI = cast<CallInst>(it);
+@@ -3397,7 +3411,7 @@
+       case Intrinsic::assume:
+       case Intrinsic::lifetime_end:
+       case Intrinsic::lifetime_start:
+-        scalarizeInstruction(it);
++        scalarizeInstruction(&*it);
+         break;
+       default:
+         bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
+@@ -3419,7 +3433,7 @@
+           Entry[Part] = Builder.CreateCall(F, Args);
+         }
+ 
+-        propagateMetadata(Entry, it);
++        propagateMetadata(Entry, &*it);
+         break;
+       }
+       break;
+@@ -3427,7 +3441,7 @@
+ 
+     default:
+       // All other instructions are unsupported. Scalarize them.
+-      scalarizeInstruction(it);
++      scalarizeInstruction(&*it);
+       break;
+     }// end of switch.
+   }// end of for_each instr.
+@@ -3686,7 +3700,7 @@
+         if (!PhiTy->isIntegerTy() &&
+             !PhiTy->isFloatingPointTy() &&
+             !PhiTy->isPointerTy()) {
+-          emitAnalysis(Report(it)
++          emitAnalysis(Report(&*it)
+                        << "loop control flow is not understood by vectorizer");
+           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
+           return false;
+@@ -3698,16 +3712,17 @@
+         if (*bb != Header) {
+           // Check that this instruction has no outside users or is an
+           // identified reduction value with an outside user.
+-          if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
++          if (!hasOutsideLoopUser(TheLoop, &*it, AllowedExit))
+             continue;
+-          emitAnalysis(Report(it) << "value could not be identified as "
+-                                     "an induction or reduction variable");
++          emitAnalysis(Report(&*it)
++                       << "value could not be identified as "
++                       "an induction or reduction variable");
+           return false;
+         }
+ 
+         // We only allow if-converted PHIs with exactly two incoming values.
+         if (Phi->getNumIncomingValues() != 2) {
+-          emitAnalysis(Report(it)
++          emitAnalysis(Report(&*it)
+                        << "control flow not understood by vectorizer");
+           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
+           return false;
+@@ -3739,9 +3754,10 @@
+ 
+           // Until we explicitly handle the case of an induction variable with
+           // an outside loop user we have to give up vectorizing this loop.
+-          if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
+-            emitAnalysis(Report(it) << "use of induction value outside of the "
+-                                       "loop is not handled by vectorizer");
++          if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
++            emitAnalysis(Report(&*it) <<
++                         "use of induction value outside of the "
++                         "loop is not handled by vectorizer");
+             return false;
+           }
+ 
+@@ -3786,8 +3802,8 @@
+           continue;
+         }
+ 
+-        emitAnalysis(Report(it) << "value that could not be identified as "
+-                                   "reduction is used outside the loop");
++        emitAnalysis(Report(&*it) << "value that could not be identified as "
++                     "reduction is used outside the loop");
+         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
+         return false;
+       }// end of PHI handling
+@@ -3796,7 +3812,7 @@
+       // calls and we do handle certain intrinsic and libm functions.
+       CallInst *CI = dyn_cast<CallInst>(it);
+       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
+-        emitAnalysis(Report(it) << "call instruction cannot be vectorized");
++        emitAnalysis(Report(&*it) << "call instruction cannot be vectorized");
+         DEBUG(dbgs() << "LV: Found a call site.\n");
+         return false;
+       }
+@@ -3806,7 +3822,7 @@
+       if (CI &&
+           hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
+         if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
+-          emitAnalysis(Report(it)
++          emitAnalysis(Report(&*it)
+                        << "intrinsic instruction cannot be vectorized");
+           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
+           return false;
+@@ -3817,7 +3833,7 @@
+       // Also, we can't vectorize extractelement instructions.
+       if ((!VectorType::isValidElementType(it->getType()) &&
+            !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
+-        emitAnalysis(Report(it)
++        emitAnalysis(Report(&*it)
+                      << "instruction return type cannot be vectorized");
+         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
+         return false;
+@@ -3840,8 +3856,8 @@
+ 
+       // Reduction instructions are allowed to have exit users.
+       // All other instructions must not have external users.
+-      if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
+-        emitAnalysis(Report(it) << "value cannot be used outside the loop");
++      if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
++        emitAnalysis(Report(&*it) << "value cannot be used outside the loop");
+         return false;
+       }
+ 
+@@ -4009,7 +4025,7 @@
+        BE = TheLoop->block_end(); B != BE; ++B)
+     for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
+          I != IE; ++I)
+-      if (I->getType()->isPointerTy() && isConsecutivePtr(I))
++      if (I->getType()->isPointerTy() && isConsecutivePtr(&*I))
+         Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
+ 
+   while (Worklist.size()) {
+@@ -4800,7 +4816,7 @@
+       if (it->mayWriteToMemory()) {
+         StoreInst *St = dyn_cast<StoreInst>(it);
+         if (!St) {
+-          emitAnalysis(Report(it) << "instruction cannot be vectorized");
++          emitAnalysis(Report(&*it) << "instruction cannot be vectorized");
+           return false;
+         }
+         if (!St->isSimple() && !IsAnnotatedParallel) {
+@@ -5543,7 +5559,7 @@
+       Type *T = it->getType();
+ 
+       // Ignore ephemeral values.
+-      if (EphValues.count(it))
++      if (EphValues.count(&*it))
+         continue;
+ 
+       // Only examine Loads, Stores and PHINodes.
+@@ -5562,7 +5578,7 @@
+       // Ignore loaded pointer types and stored pointer types that are not
+       // consecutive. However, we do want to take consecutive stores/loads of
+       // pointer vectors into account.
+-      if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
++      if (T->isPointerTy() && !isConsecutiveLoadOrStore(&*it))
+         continue;
+ 
+       MaxWidth = std::max(MaxWidth,
+@@ -5765,7 +5781,7 @@
+     R.NumInstructions += (*bb)->size();
+     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
+          ++it) {
+-      Instruction *I = it;
++      Instruction *I = &*it;
+       IdxToInstr[Index++] = I;
+ 
+       // Save the end location of each USE.
+@@ -5853,10 +5869,10 @@
+         continue;
+ 
+       // Ignore ephemeral values.
+-      if (EphValues.count(it))
++      if (EphValues.count(&*it))
+         continue;
+ 
+-      unsigned C = getInstructionCost(it, VF);
++      unsigned C = getInstructionCost(&*it, VF);
+ 
+       // Check if we should override the cost.
+       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
+@@ -6230,19 +6246,12 @@
+   // Create a new entry in the WidenMap and initialize it to Undef or Null.
+   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
+ 
+-  Instruction *InsertPt = Builder.GetInsertPoint();
+-  BasicBlock *IfBlock = Builder.GetInsertBlock();
+-  BasicBlock *CondBlock = nullptr;
+-
+   VectorParts Cond;
+-  Loop *VectorLp = nullptr;
+   if (IfPredicateStore) {
+     assert(Instr->getParent()->getSinglePredecessor() &&
+            "Only support single predecessor blocks");
+     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
+                           Instr->getParent());
+-    VectorLp = LI->getLoopFor(IfBlock);
+-    assert(VectorLp && "Must have a loop for this block");
+   }
+ 
+   // For each vector unroll 'part':
+@@ -6257,11 +6266,6 @@
+             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
+       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
+                                ConstantInt::get(Cond[Part]->getType(), 1));
+-      CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
+-      LoopVectorBody.push_back(CondBlock);
+-      VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
+-      // Update Builder with newly created basic block.
+-      Builder.SetInsertPoint(InsertPt);
+     }
+ 
+     Instruction *Cloned = Instr->clone();
+@@ -6282,16 +6286,9 @@
+         VecResults[Part] = Cloned;
+ 
+     // End if-block.
+-      if (IfPredicateStore) {
+-        BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
+-        LoopVectorBody.push_back(NewIfBlock);
+-        VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
+-        Builder.SetInsertPoint(InsertPt);
+-        Instruction *OldBr = IfBlock->getTerminator();
+-        BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
+-        OldBr->eraseFromParent();
+-        IfBlock = NewIfBlock;
+-      }
++      if (IfPredicateStore)
++        PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
++                                                  Cmp));
+   }
+ }
+ 
+--- lib/Transforms/Vectorize/SLPVectorizer.cpp	2015-02-12 09:51:17.000000000 -0800
++++ lib/Transforms/Vectorize/SLPVectorizer.cpp	2015-12-06 11:52:23.656576722 -0800
+@@ -1742,7 +1742,8 @@
+     }    
+ 
+     // Now find the sequence of instructions between PrevInst and Inst.
+-    BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
++    BasicBlock::reverse_iterator InstIt(Inst->getIterator()),
++      PrevInstIt(PrevInst->getIterator());
+     --PrevInstIt;
+     while (InstIt != PrevInstIt) {
+       if (PrevInstIt == PrevInst->getParent()->rend()) {
+@@ -1890,7 +1891,7 @@
+ 
+ void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
+   Instruction *VL0 = cast<Instruction>(VL[0]);
+-  BasicBlock::iterator NextInst = VL0;
++  BasicBlock::iterator NextInst(VL0);
+   ++NextInst;
+   Builder.SetInsertPoint(VL0->getParent(), NextInst);
+   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
+@@ -2346,7 +2347,7 @@
+     scheduleBlock(BSIter.second.get());
+   }
+ 
+-  Builder.SetInsertPoint(F->getEntryBlock().begin());
++  Builder.SetInsertPoint(&F->getEntryBlock().front());
+   vectorizeTree(&VectorizableTree[0]);
+ 
+   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
+@@ -2391,7 +2392,7 @@
+         User->replaceUsesOfWith(Scalar, Ex);
+      }
+     } else {
+-      Builder.SetInsertPoint(F->getEntryBlock().begin());
++      Builder.SetInsertPoint(&F->getEntryBlock().front());
+       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
+       CSEBlocks.insert(&F->getEntryBlock());
+       User->replaceUsesOfWith(Scalar, Ex);
+@@ -2500,7 +2501,9 @@
+     BasicBlock *BB = (*I)->getBlock();
+     // For all instructions in blocks containing gather sequences:
+     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
+-      Instruction *In = it++;
++      Instruction *In = &*it;
++      ++it;
++
+       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
+         continue;
+ 
+@@ -2648,7 +2651,7 @@
+   }
+   // Search up and down at the same time, because we don't know if the new
+   // instruction is above or below the existing scheduling region.
+-  BasicBlock::reverse_iterator UpIter(ScheduleStart);
++  BasicBlock::reverse_iterator UpIter(ScheduleStart->getIterator());
+   BasicBlock::reverse_iterator UpperEnd = BB->rend();
+   BasicBlock::iterator DownIter(ScheduleEnd);
+   BasicBlock::iterator LowerEnd = BB->end();
+@@ -2860,7 +2863,8 @@
+       Instruction *pickedInst = BundleMember->Inst;
+       if (LastScheduledInst->getNextNode() != pickedInst) {
+         BS->BB->getInstList().remove(pickedInst);
+-        BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
++        BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
++                                     pickedInst);
+       }
+       LastScheduledInst = pickedInst;
+       BundleMember = BundleMember->NextInBundle;
+@@ -3243,8 +3247,8 @@
+         Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
+         unsigned VecIdx = 0;
+         for (auto &V : BuildVectorSlice) {
+-          IRBuilder<true, NoFolder> Builder(
+-              ++BasicBlock::iterator(InsertAfter));
++          IRBuilder<true, NoFolder> Builder(InsertAfter->getParent(),
++                                   ++BasicBlock::iterator(InsertAfter));
+           InsertElementInst *IE = cast<InsertElementInst>(V);
+           Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
+               VectorizedRoot, Builder.getInt32(VecIdx++)));
+@@ -3695,10 +3699,10 @@
+ 
+   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
+     // We may go through BB multiple times so skip the one we have checked.
+-    if (!VisitedInstrs.insert(it).second)
++    if (!VisitedInstrs.insert(&*it).second)
+       continue;
+ 
+-    if (isa<DbgInfoIntrinsic>(it))
++    if (isa<DbgInfoIntrinsic>(&*it))
+       continue;
+ 
+     // Try to vectorize reductions that use PHINodes.
+--- tools/bugpoint/CrashDebugger.cpp	2014-08-26 10:19:03.000000000 -0700
++++ tools/bugpoint/CrashDebugger.cpp	2015-12-08 17:47:24.061167860 -0800
+@@ -148,7 +148,7 @@
+   // playing with...
+   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
+        I != E; ++I)
+-    if (I->hasInitializer() && !GVSet.count(I)) {
++    if (I->hasInitializer() && !GVSet.count(&*I)) {
+       I->setInitializer(nullptr);
+       I->setLinkage(GlobalValue::ExternalLinkage);
+     }
+@@ -222,8 +222,8 @@
+   // Loop over and delete any functions which we aren't supposed to be playing
+   // with...
+   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
+-    if (!I->isDeclaration() && !Functions.count(I))
+-      DeleteFunctionBody(I);
++    if (!I->isDeclaration() && !Functions.count(&*I))
++      DeleteFunctionBody(&*I);
+ 
+   // Try running the hacked up program...
+   if (TestFn(BD, M)) {
+@@ -289,11 +289,12 @@
+   // Loop over and delete any hack up any blocks that are not listed...
+   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
+     for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
+-      if (!Blocks.count(BB) && BB->getTerminator()->getNumSuccessors()) {
++      if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
+         // Loop over all of the successors of this block, deleting any PHI nodes
+         // that might include it.
+-        for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
+-          (*SI)->removePredecessor(BB);
++        for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB);
++             SI != E; ++SI)
++          (*SI)->removePredecessor(&*BB);
+ 
+         TerminatorInst *BBTerm = BB->getTerminator();
+         
+@@ -302,7 +303,7 @@
+ 
+         // Replace the old terminator instruction.
+         BB->getInstList().pop_back();
+-        new UnreachableInst(BB->getContext(), BB);
++        new UnreachableInst(BB->getContext(), &*BB);
+       }
+ 
+   // The CFG Simplifier pass may delete one of the basic blocks we are
+@@ -397,7 +398,8 @@
+   for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
+     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
+       for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
+-        Instruction *Inst = I++;
++        Instruction *Inst = &*I;
++        ++I;
+         if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
+             !isa<LandingPadInst>(Inst)) {
+           if (!Inst->getType()->isVoidTy())
+@@ -468,7 +470,7 @@
+         for (Module::global_iterator I = BD.getProgram()->global_begin(),
+                E = BD.getProgram()->global_end(); I != E; ++I)
+           if (I->hasInitializer())
+-            GVs.push_back(I);
++            GVs.push_back(&*I);
+ 
+         if (GVs.size() > 1 && !BugpointIsInterrupted) {
+           outs() << "\n*** Attempting to reduce the number of global "
+@@ -491,7 +493,7 @@
+   for (Module::iterator I = BD.getProgram()->begin(),
+          E = BD.getProgram()->end(); I != E; ++I)
+     if (!I->isDeclaration())
+-      Functions.push_back(I);
++      Functions.push_back(&*I);
+ 
+   if (Functions.size() > 1 && !BugpointIsInterrupted) {
+     outs() << "\n*** Attempting to reduce the number of functions "
+@@ -511,10 +513,11 @@
+   //
+   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
+     std::vector<const BasicBlock*> Blocks;
+-    for (Module::const_iterator I = BD.getProgram()->begin(),
+-           E = BD.getProgram()->end(); I != E; ++I)
+-      for (Function::const_iterator FI = I->begin(), E = I->end(); FI !=E; ++FI)
+-        Blocks.push_back(FI);
++    for (Function &F : *BD.getProgram()) {
++      for (BasicBlock &BB : F)
++        Blocks.push_back(&BB);
++    }
++
+     unsigned OldSize = Blocks.size();
+     ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks, Error);
+     if (Blocks.size() < OldSize)
+@@ -525,14 +528,11 @@
+   // cases with large basic blocks where the problem is at one end.
+   if (!BugpointIsInterrupted) {
+     std::vector<const Instruction*> Insts;
+-    for (Module::const_iterator MI = BD.getProgram()->begin(),
+-           ME = BD.getProgram()->end(); MI != ME; ++MI)
+-      for (Function::const_iterator FI = MI->begin(), FE = MI->end(); FI != FE;
+-           ++FI)
+-        for (BasicBlock::const_iterator I = FI->begin(), E = FI->end();
+-             I != E; ++I)
+-          if (!isa<TerminatorInst>(I))
+-            Insts.push_back(I);
++    for (const Function &F : *BD.getProgram())
++      for (const BasicBlock &BB : F)
++        for (const Instruction &I : BB)
++          if (!isa<TerminatorInst>(&I))
++            Insts.push_back(&I);
+ 
+     ReduceCrashingInstructions(BD, TestFn).reduceList(Insts, Error);
+   }
+@@ -577,7 +577,7 @@
+ 
+               outs() << "Checking instruction: " << *I;
+               std::unique_ptr<Module> M =
+-                  BD.deleteInstructionFromProgram(I, Simplification);
++                  BD.deleteInstructionFromProgram(&*I, Simplification);
+ 
+               // Find out if the pass still crashes on this pass...
+               if (TestFn(BD, M.get())) {
+--- tools/bugpoint/ExtractFunction.cpp	2014-08-26 10:19:03.000000000 -0700
++++ tools/bugpoint/ExtractFunction.cpp	2015-12-08 17:53:34.720329668 -0800
+@@ -100,7 +100,7 @@
+ 
+   BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
+   std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
+-  Instruction *TheInst = RI;              // Got the corresponding instruction!
++  Instruction *TheInst = &*RI;           // Got the corresponding instruction!
+ 
+   // If this instruction produces a value, replace any users with null values
+   if (!TheInst->getType()->isVoidTy())
+@@ -307,15 +307,15 @@
+   
+   // Remove the Safe functions from the Test module
+   for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
+-    if (!TestFunctions.count(I))
+-      DeleteFunctionBody(I);
++    if (!TestFunctions.count(&*I))
++      DeleteFunctionBody(&*I);
+   
+ 
+   // Try to split the global initializers evenly
+   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
+        I != E; ++I) {
+-    GlobalVariable *GV = cast<GlobalVariable>(NewVMap[I]);
+-    if (Function *TestFn = globalInitUsesExternalBA(I)) {
++    GlobalVariable *GV = cast<GlobalVariable>(NewVMap[&*I]);
++    if (Function *TestFn = globalInitUsesExternalBA(&*I)) {
+       if (Function *SafeFn = globalInitUsesExternalBA(GV)) {
+         errs() << "*** Error: when reducing functions, encountered "
+                   "the global '";
+--- tools/bugpoint/Miscompilation.cpp	2014-10-27 17:24:16.000000000 -0700
++++ tools/bugpoint/Miscompilation.cpp	2015-12-08 17:55:31.425007898 -0800
+@@ -550,7 +550,7 @@
+   for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
+     for (Function::iterator I = MiscompiledFunctions[i]->begin(),
+            E = MiscompiledFunctions[i]->end(); I != E; ++I)
+-      Blocks.push_back(I);
++      Blocks.push_back(&*I);
+ 
+   // Use the list reducer to identify blocks that can be extracted without
+   // obscuring the bug.  The Blocks list will end up containing blocks that must
+@@ -634,7 +634,7 @@
+   Module *Prog = BD.getProgram();
+   for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
+     if (!I->isDeclaration())
+-      MiscompiledFunctions.push_back(I);
++      MiscompiledFunctions.push_back(&*I);
+ 
+   // Do the reduction...
+   if (!BugpointIsInterrupted)
+@@ -806,7 +806,7 @@
+              I = newMain->arg_begin(), E = newMain->arg_end(),
+              OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
+         I->setName(OI->getName());    // Copy argument names from oldMain
+-        args.push_back(I);
++        args.push_back(&*I);
+       }
+ 
+       // Call the old main function and return its result
+@@ -910,7 +910,7 @@
+           std::vector<Value*> Args;
+           for (Function::arg_iterator i = FuncWrapper->arg_begin(),
+                  e = FuncWrapper->arg_end(); i != e; ++i)
+-            Args.push_back(i);
++            Args.push_back(&*i);
+ 
+           // Pass on the arguments to the real function, return its result
+           if (F->getReturnType()->isVoidTy()) {
+--- tools/clang/include/clang/Analysis/CFG.h	2015-10-05 11:01:32.409005315 -0700
++++ tools/clang/include/clang/Analysis/CFG.h	2015-12-08 08:12:46.482439723 -0800
+@@ -322,7 +322,7 @@
+   Stmt &operator*() { return *getStmt(); }
+   const Stmt &operator*() const { return *getStmt(); }
+ 
+-  LLVM_EXPLICIT operator bool() const { return getStmt(); }
++  explicit operator bool() const { return getStmt(); }
+ };
+ 
+ /// CFGBlock - Represents a single basic block in a source-level CFG.
+@@ -432,7 +432,7 @@
+   public:
+     /// Construct an AdjacentBlock with a possibly unreachable block.
+     AdjacentBlock(CFGBlock *B, bool IsReachable);
+-    
++
+     /// Construct an AdjacentBlock with a reachable block and an alternate
+     /// unreachable block.
+     AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock);
+@@ -694,7 +694,7 @@
+   iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
+       BumpVectorContext &C) {
+     return iterator(Elements.insert(I.base(), Cnt,
+-                                    CFGAutomaticObjDtor(nullptr, 0), C));
++                                    CFGAutomaticObjDtor(nullptr, nullptr), C));
+   }
+   iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
+     *I = CFGAutomaticObjDtor(VD, S);
+@@ -767,7 +767,7 @@
+   /// (not a pointer to CFGBlock).
+   class graph_iterator {
+   public:
+-    typedef const CFGBlock                  value_type;
++    typedef CFGBlock                        value_type;
+     typedef value_type&                     reference;
+     typedef value_type*                     pointer;
+     typedef BumpVector<CFGBlock*>::iterator ImplTy;
+--- tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp	2015-10-05 11:01:32.364932580 -0700
++++ tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp	2015-10-12 22:15:59.378584335 -0700
+@@ -285,16 +285,11 @@
+   do {
+     DirectiveLex.LexFromRawLexer(DirectiveToken);
+   } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof));
++
+   if (&FromFile == PredefinesBuffer) {
+     // OutputContentUpTo() would not output anything anyway.
+     return;
+   }
+-  OS << "#if 0 /* expanded by -frewrite-includes */" << MainEOL;
+-  OutputContentUpTo(FromFile, NextToWrite,
+-                    SM.getFileOffset(DirectiveToken.getLocation()) +
+-                        DirectiveToken.getLength(),
+-                    LocalEOL, Line, true);
+-  OS << "#endif /* expanded by -frewrite-includes */" << MainEOL;
+ }
+ 
+ /// Find the next identifier in the pragma directive specified by \p RawToken.
+--- tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp	2015-10-05 11:01:32.334095518 -0700
++++ tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp	2015-12-08 09:02:55.503942822 -0800
+@@ -3295,11 +3295,11 @@
+   // post-dominated by a sink, simply add all the nodes in the equivalence class
+   // to 'Nodes'.  Any of the reports will serve as a "representative" report.
+   if (!BT.isSuppressOnSink()) {
+-    BugReport *R = I;
++    BugReport *R = &*I;
+     for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
+       const ExplodedNode *N = I->getErrorNode();
+       if (N) {
+-        R = I;
++        R = &*I;
+         bugReports.push_back(R);
+       }
+     }
+@@ -3325,35 +3325,35 @@
+     }
+     // No successors?  By definition this nodes isn't post-dominated by a sink.
+     if (errorNode->succ_empty()) {
+-      bugReports.push_back(I);
++      bugReports.push_back(&*I);
+       if (!exampleReport)
+-        exampleReport = I;
++        exampleReport = &*I;
+       continue;
+     }
+ 
+     // At this point we know that 'N' is not a sink and it has at least one
+-    // successor.  Use a DFS worklist to find a non-sink end-of-path node.    
++    // successor.  Use a DFS worklist to find a non-sink end-of-path node.
+     typedef FRIEC_WLItem WLItem;
+     typedef SmallVector<WLItem, 10> DFSWorkList;
+     llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
+-    
++
+     DFSWorkList WL;
+     WL.push_back(errorNode);
+     Visited[errorNode] = 1;
+-    
++
+     while (!WL.empty()) {
+       WLItem &WI = WL.back();
+       assert(!WI.N->succ_empty());
+-            
++
+       for (; WI.I != WI.E; ++WI.I) {
+-        const ExplodedNode *Succ = *WI.I;        
++        const ExplodedNode *Succ = *WI.I;
+         // End-of-path node?
+         if (Succ->succ_empty()) {
+           // If we found an end-of-path node that is not a sink.
+           if (!Succ->isSink()) {
+-            bugReports.push_back(I);
++            bugReports.push_back(&*I);
+             if (!exampleReport)
+-              exampleReport = I;
++              exampleReport = &*I;
+             WL.clear();
+             break;
+           }
+--- tools/llvm-diff/DifferenceEngine.cpp	2014-07-21 10:06:51.000000000 -0700
++++ tools/llvm-diff/DifferenceEngine.cpp	2015-12-08 13:51:00.260552197 -0800
+@@ -599,7 +599,7 @@
+   TerminatorInst *RTerm = RStart->getParent()->getTerminator();
+   if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
+     if (cast<BranchInst>(LTerm)->isConditional()) return;
+-    BasicBlock::iterator I = LTerm;
++    BasicBlock::iterator I = LTerm->getIterator();
+     if (I == LStart->getParent()->begin()) return;
+     --I;
+     if (!isa<CallInst>(*I)) return;
+@@ -612,7 +612,7 @@
+     tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
+   } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
+     if (cast<BranchInst>(RTerm)->isConditional()) return;
+-    BasicBlock::iterator I = RTerm;
++    BasicBlock::iterator I = RTerm->getIterator();
+     if (I == RStart->getParent()->begin()) return;
+     --I;
+     if (!isa<CallInst>(*I)) return;
+--- tools/llvm-stress/llvm-stress.cpp	2014-08-25 11:16:47.000000000 -0700
++++ tools/llvm-stress/llvm-stress.cpp	2015-12-08 17:59:08.743284003 -0800
+@@ -622,7 +622,7 @@
+   // Consider arguments as legal values.
+   for (Function::arg_iterator it = F->arg_begin(), e = F->arg_end();
+        it != e; ++it)
+-    PT.push_back(it);
++    PT.push_back(&*it);
+ 
+   // List of modifiers which add new random instructions.
+   std::vector<Modifier*> Modifiers;
+@@ -663,16 +663,15 @@
+   for (BasicBlock::iterator it = F->begin()->begin(),
+        e = F->begin()->end(); it != e; ++it) {
+     if (it->getType() == IntegerType::getInt1Ty(F->getContext()))
+-      BoolInst.push_back(it);
++      BoolInst.push_back(&*it);
+   }
+ 
+   std::random_shuffle(BoolInst.begin(), BoolInst.end(), R);
+ 
+-  for (std::vector<Instruction*>::iterator it = BoolInst.begin(),
+-       e = BoolInst.end(); it != e; ++it) {
+-    Instruction *Instr = *it;
++
++  for (auto *Instr : BoolInst) {
+     BasicBlock *Curr = Instr->getParent();
+-    BasicBlock::iterator Loc= Instr;
++    BasicBlock::iterator Loc = Instr->getIterator();
+     BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
+     Instr->moveBefore(Curr->getTerminator());
+     if (Curr != &F->getEntryBlock()) {
+--- unittests/ADT/ilistTest.cpp	2014-06-08 15:29:17.000000000 -0700
++++ unittests/ADT/ilistTest.cpp	2016-01-23 11:05:55.000000000 -0800
+@@ -80,7 +80,7 @@
+   // List with contents.
+   List.push_back(1);
+   ASSERT_EQ(1u, List.size());
+-  Node *N = List.begin();
++  Node *N = &*List.begin();
+   EXPECT_EQ(1, N->Value);
+   List.clearAndLeakNodesUnsafely();
+   EXPECT_EQ(0u, List.size());
+--- unittests/Analysis/CFGTest.cpp	2014-08-19 09:58:54.000000000 -0700
++++ unittests/Analysis/CFGTest.cpp	2016-01-23 11:08:10.000000000 -0800
+@@ -378,7 +378,7 @@
+ TEST_F(IsPotentiallyReachableTest, ModifyTest) {
+   ParseAssembly(BranchInsideLoopIR);
+ 
+-  succ_iterator S = succ_begin(++M->getFunction("test")->begin());
++  succ_iterator S = succ_begin(&*++M->getFunction("test")->begin());
+   BasicBlock *OldBB = S[0];
+   S[0] = S[1];
+   ExpectPath(false);
+--- unittests/ExecutionEngine/MCJIT/MCJITTestBase.h	2014-12-02 16:51:19.000000000 -0800
++++ unittests/ExecutionEngine/MCJIT/MCJITTestBase.h	2016-01-23 11:13:10.000000000 -0800
+@@ -71,8 +71,8 @@
+     SmallVector<Value*, 1> CallArgs;
+ 
+     Function::arg_iterator arg_iter = Result->arg_begin();
+-    for(;arg_iter != Result->arg_end(); ++arg_iter)
+-      CallArgs.push_back(arg_iter);
++    for (Argument &A : Result->args())
++      CallArgs.push_back(&A);
+ 
+     Value *ReturnCode = Builder.CreateCall(Callee, CallArgs);
+     Builder.CreateRet(ReturnCode);
+@@ -98,8 +98,8 @@
+     Function *Result = startFunction<int32_t(int32_t, int32_t)>(M, Name);
+ 
+     Function::arg_iterator args = Result->arg_begin();
+-    Value *Arg1 = args;
+-    Value *Arg2 = ++args;
++    Value *Arg1 = &*args;
++    Value *Arg2 = &*++args;
+     Value *AddResult = Builder.CreateAdd(Arg1, Arg2);
+ 
+     endFunctionWithRet(Result, AddResult);
+@@ -170,7 +170,7 @@
+     BasicBlock *RecursiveCase = BasicBlock::Create(Context, "", Result);
+ 
+     // if (num == 0)
+-    Value *Param = Result->arg_begin();
++    Value *Param = &*Result->arg_begin();
+     Value *Zero = ConstantInt::get(Context, APInt(32, 0));
+     Builder.CreateCondBr(Builder.CreateICmpEQ(Param, Zero),
+                          BaseCase, RecursiveCase);
+--- unittests/IR/DominatorTreeTest.cpp	2014-08-19 09:58:54.000000000 -0700
++++ unittests/IR/DominatorTreeTest.cpp	2016-01-23 11:18:36.000000000 -0800
+@@ -31,29 +31,29 @@
+         PostDominatorTree *PDT = &getAnalysis<PostDominatorTree>();
+         Function::iterator FI = F.begin();
+ 
+-        BasicBlock *BB0 = FI++;
++        BasicBlock *BB0 = &*FI++;
+         BasicBlock::iterator BBI = BB0->begin();
+-        Instruction *Y1 = BBI++;
+-        Instruction *Y2 = BBI++;
+-        Instruction *Y3 = BBI++;
++        Instruction *Y1 = &*BBI++;
++        Instruction *Y2 = &*BBI++;
++        Instruction *Y3 = &*BBI++;
+ 
+-        BasicBlock *BB1 = FI++;
++        BasicBlock *BB1 = &*FI++;
+         BBI = BB1->begin();
+-        Instruction *Y4 = BBI++;
++        Instruction *Y4 = &*BBI++;
+ 
+-        BasicBlock *BB2 = FI++;
++        BasicBlock *BB2 = &*FI++;
+         BBI = BB2->begin();
+-        Instruction *Y5 = BBI++;
++        Instruction *Y5 = &*BBI++;
+ 
+-        BasicBlock *BB3 = FI++;
++        BasicBlock *BB3 = &*FI++;
+         BBI = BB3->begin();
+-        Instruction *Y6 = BBI++;
+-        Instruction *Y7 = BBI++;
++        Instruction *Y6 = &*BBI++;
++        Instruction *Y7 = &*BBI++;
+ 
+-        BasicBlock *BB4 = FI++;
++        BasicBlock *BB4 = &*FI++;
+         BBI = BB4->begin();
+-        Instruction *Y8 = BBI++;
+-        Instruction *Y9 = BBI++;
++        Instruction *Y8 = &*BBI++;
++        Instruction *Y9 = &*BBI++;
+ 
+         // Reachability
+         EXPECT_TRUE(DT->isReachableFromEntry(BB0));
+--- unittests/IR/IRBuilderTest.cpp	2014-09-02 13:03:00.000000000 -0700
++++ unittests/IR/IRBuilderTest.cpp	2016-01-23 11:19:43.000000000 -0800
+@@ -280,7 +280,7 @@
+   {
+     IRBuilder<>::InsertPointGuard Guard(Builder);
+     Builder.SetInsertPoint(cast<Instruction>(F));
+-    EXPECT_EQ(F, Builder.GetInsertPoint());
++    EXPECT_EQ(F, &*Builder.GetInsertPoint());
+   }
+ 
+   EXPECT_EQ(BB->end(), Builder.GetInsertPoint());
+--- unittests/IR/LegacyPassManagerTest.cpp	2014-09-10 14:27:43.000000000 -0700
++++ unittests/IR/LegacyPassManagerTest.cpp	2016-01-23 11:21:26.000000000 -0800
+@@ -521,7 +521,7 @@
+       // Function: test4 (func_test4)
+       {
+         Function::arg_iterator args = func_test4->arg_begin();
+-        Value* int1_f = args++;
++        Value* int1_f = &*args++;
+         int1_f->setName("f");
+ 
+         BasicBlock* label_entry_11 = BasicBlock::Create(getGlobalContext(), "entry",func_test4,nullptr);
+--- unittests/IR/ValueTest.cpp	2014-10-23 07:45:19.000000000 -0700
++++ unittests/IR/ValueTest.cpp	2016-01-23 11:23:38.000000000 -0800
+@@ -38,9 +38,9 @@
+ 
+   Function *F = M->getFunction("f");
+ 
+-  EXPECT_FALSE(F->isUsedInBasicBlock(F->begin()));
+-  EXPECT_TRUE((++F->arg_begin())->isUsedInBasicBlock(F->begin()));
+-  EXPECT_TRUE(F->arg_begin()->isUsedInBasicBlock(F->begin()));
++  EXPECT_FALSE(F->isUsedInBasicBlock(&F->front()));
++  EXPECT_TRUE((++F->arg_begin())->isUsedInBasicBlock(&F->front()));
++  EXPECT_TRUE(F->arg_begin()->isUsedInBasicBlock(&F->front()));
+ }
+ 
+ TEST(GlobalTest, CreateAddressSpace) {
+--- unittests/Linker/LinkModulesTest.cpp	2015-01-14 03:23:27.000000000 -0800
++++ unittests/Linker/LinkModulesTest.cpp	2016-01-23 11:25:17.000000000 -0800
+@@ -73,7 +73,7 @@
+ 
+   std::vector<Value *> GEPIndices;
+   GEPIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ctx), 0));
+-  GEPIndices.push_back(F->arg_begin());
++  GEPIndices.push_back(&*F->arg_begin());
+ 
+   Value *GEP = Builder.CreateGEP(GV, GEPIndices, "switch.gep");
+   Value *Load = Builder.CreateLoad(GEP, "switch.load");
+--- unittests/Support/Makefile	2013-08-01 11:42:28.000000000 -0700
++++ unittests/Support/Makefile	2016-01-27 11:20:22.000000000 -0800
+@@ -13,3 +13,7 @@
+ 
+ include $(LEVEL)/Makefile.config
+ include $(LLVM_SRC_ROOT)/unittests/Makefile.unittest
++
++C.Flags += -DALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
++CXX.Flags += -DALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
++
+--- unittests/Transforms/Utils/Cloning.cpp	2015-01-14 03:23:27.000000000 -0800
++++ unittests/Transforms/Utils/Cloning.cpp	2016-01-23 11:29:52.000000000 -0800
+@@ -165,7 +165,7 @@
+ 
+   Attribute::AttrKind AK[] = { Attribute::NoCapture };
+   AttributeSet AS = AttributeSet::get(context, 0, AK);
+-  Argument *A = F1->arg_begin();
++  Argument *A = &*F1->arg_begin();
+   A->addAttr(AS);
+ 
+   SmallVector<ReturnInst*, 4> Returns;
+@@ -193,7 +193,7 @@
+ 
+   SmallVector<ReturnInst*, 4> Returns;
+   ValueToValueMapTy VMap;
+-  VMap[F1->arg_begin()] = F2->arg_begin();
++  VMap[&*F1->arg_begin()] = &*F2->arg_begin();
+ 
+   CloneFunctionInto(F2, F1, VMap, false, Returns);
+   EXPECT_EQ(CallingConv::Cold, F2->getCallingConv());
+--- unittests/Transforms/Utils/IntegerDivision.cpp	2013-11-18 22:54:19.000000000 -0800
++++ unittests/Transforms/Utils/IntegerDivision.cpp	2016-01-23 11:32:46.000000000 -0800
+@@ -35,8 +35,8 @@
+   Builder.SetInsertPoint(BB);
+ 
+   Function::arg_iterator AI = F->arg_begin();
+-  Value *A = AI++;
+-  Value *B = AI++;
++  Value *A = &*AI++;
++  Value *B = &*AI++;
+ 
+   Value *Div = Builder.CreateSDiv(A, B);
+   EXPECT_TRUE(BB->front().getOpcode() == Instruction::SDiv);
+@@ -65,8 +65,8 @@
+   Builder.SetInsertPoint(BB);
+ 
+   Function::arg_iterator AI = F->arg_begin();
+-  Value *A = AI++;
+-  Value *B = AI++;
++  Value *A = &*AI++;
++  Value *B = &*AI++;
+ 
+   Value *Div = Builder.CreateUDiv(A, B);
+   EXPECT_TRUE(BB->front().getOpcode() == Instruction::UDiv);
+@@ -95,8 +95,8 @@
+   Builder.SetInsertPoint(BB);
+ 
+   Function::arg_iterator AI = F->arg_begin();
+-  Value *A = AI++;
+-  Value *B = AI++;
++  Value *A = &*AI++;
++  Value *B = &*AI++;
+ 
+   Value *Rem = Builder.CreateSRem(A, B);
+   EXPECT_TRUE(BB->front().getOpcode() == Instruction::SRem);
+@@ -125,8 +125,8 @@
+   Builder.SetInsertPoint(BB);
+ 
+   Function::arg_iterator AI = F->arg_begin();
+-  Value *A = AI++;
+-  Value *B = AI++;
++  Value *A = &*AI++;
++  Value *B = &*AI++;
+ 
+   Value *Rem = Builder.CreateURem(A, B);
+   EXPECT_TRUE(BB->front().getOpcode() == Instruction::URem);
+@@ -156,8 +156,8 @@
+   Builder.SetInsertPoint(BB);
+ 
+   Function::arg_iterator AI = F->arg_begin();
+-  Value *A = AI++;
+-  Value *B = AI++;
++  Value *A = &*AI++;
++  Value *B = &*AI++;
+ 
+   Value *Div = Builder.CreateSDiv(A, B);
+   EXPECT_TRUE(BB->front().getOpcode() == Instruction::SDiv);
+@@ -186,8 +186,8 @@
+   Builder.SetInsertPoint(BB);
+ 
+   Function::arg_iterator AI = F->arg_begin();
+-  Value *A = AI++;
+-  Value *B = AI++;
++  Value *A = &*AI++;
++  Value *B = &*AI++;
+ 
+   Value *Div = Builder.CreateUDiv(A, B);
+   EXPECT_TRUE(BB->front().getOpcode() == Instruction::UDiv);
+@@ -216,8 +216,8 @@
+   Builder.SetInsertPoint(BB);
+ 
+   Function::arg_iterator AI = F->arg_begin();
+-  Value *A = AI++;
+-  Value *B = AI++;
++  Value *A = &*AI++;
++  Value *B = &*AI++;
+ 
+   Value *Rem = Builder.CreateSRem(A, B);
+   EXPECT_TRUE(BB->front().getOpcode() == Instruction::SRem);
+@@ -246,8 +246,8 @@
+   Builder.SetInsertPoint(BB);
+ 
+   Function::arg_iterator AI = F->arg_begin();
+-  Value *A = AI++;
+-  Value *B = AI++;
++  Value *A = &*AI++;
++  Value *B = &*AI++;
+ 
+   Value *Rem = Builder.CreateURem(A, B);
+   EXPECT_TRUE(BB->front().getOpcode() == Instruction::URem);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/022-google-test-harness-22643565.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,67 @@
+# - 22643565 - llvm's Google test harness needs some attention
+# For upstream - maytbe.
+--- utils/unittest/googletest/src/gtest-port.cc	2013-11-18 16:57:56.000000000 -0800
++++ utils/unittest/googletest/src/gtest-port.cc	2016-02-01 11:34:55.170628325 -0800
+@@ -51,6 +51,13 @@
+ # include <mach/vm_map.h>
+ #endif  // GTEST_OS_MAC
+ 
++#if GTEST_OS_SOLARIS
++# include <strings.h>
++# include <sys/types.h>
++# include <dirent.h>
++# include <unistd.h>
++#endif
++
+ #include "gtest/gtest-spi.h"
+ #include "gtest/gtest-message.h"
+ #include "gtest/internal/gtest-internal.h"
+@@ -101,9 +108,36 @@
+ #else
+ 
+ size_t GetThreadCount() {
++  size_t NumThreads = 1U;
++
++#if GTEST_OS_SOLARIS
++  char lwpdir[PATH_MAX+1];
++  (void) std::memset(lwpdir, 0, sizeof(lwpdir));
++  (void) std::sprintf(lwpdir, "/proc/%i/lwp/", static_cast<int>(getpid()));
++
++  struct dirent *DE;
++  DIR *D = ::opendir(lwpdir);
++  if (!D)
++    return NumThreads;
++
++  while ((DE = ::readdir(D)) != NULL) {
++    if (DE->d_name[0] == '.') {
++      if ((DE->d_name[1] == '\0') ||
++          ((DE->d_name[1] == '.') && (DE->d_name[2] == '\0')))
++        continue;
++    }
++
++    NumThreads =
++      static_cast<size_t>(std::max<int>(NumThreads, std::atoi(DE->d_name)));
++  }
++
++  ::rewinddir(D);
++  ::closedir(D);
++#endif
++
+   // There's no portable way to detect the number of threads, so we just
+   // return 0 to indicate that we cannot detect it.
+-  return 0;
++  return NumThreads;
+ }
+ 
+ #endif  // GTEST_OS_MAC
+--- utils/unittest/googletest/include/gtest/internal/gtest-port.h	2014-02-19 07:18:30.000000000 -0800
++++ utils/unittest/googletest/include/gtest/internal/gtest-port.h	2016-02-01 11:15:20.899289723 -0800
+@@ -238,7 +238,7 @@
+ # endif  // ANDROID
+ #elif defined __MVS__
+ # define GTEST_OS_ZOS 1
+-#elif defined(__sun) && defined(__SVR4)
++#elif (defined(__sun) || defined(__sun__)) && defined(__SVR4)
+ # define GTEST_OS_SOLARIS 1
+ #elif defined(_AIX)
+ # define GTEST_OS_AIX 1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/023-Makefile.config.in.patch	Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,48 @@
+# ${prefix/libdir must be set correctly for 64-bit builds.
+# We can't have $ORIGIN in RPATH/RUNPATH.
+# Not for upstream. The autoconf-based build system is removed in 3.8.X.
+--- Makefile.config.in	2016-02-02 09:12:17.972038970 -0800
++++ Makefile.config.in	2016-02-02 09:46:11.950055804 -0800
+@@ -13,6 +13,10 @@
+ #===------------------------------------------------------------------------===#
+ 
+ MACH = $(shell uname -p)
++MACH64=sparcv9
++ifeq ($(MACH),i386)
++  MACH64=amd64
++endif
+ 
+ # Define LLVM specific info and directories based on the autoconf variables
+ LLVMPackageName   := @PACKAGE_TARNAME@
+@@ -182,6 +186,10 @@
+ # Path to the nm program
+ NM_PATH = @NM@
+ 
++ifeq ($(findstring -m32,$(CXXFLAGS)),)
++  PROJ_libdir = $(PROJ_prefix)/lib/$(MACH64)
++endif
++
+ # The pathnames of the programs we require to build
+ CMP        := @CMP@
+ CP         := @CP@
+--- Makefile.rules	2016-02-02 09:59:19.111715578 -0800
++++ Makefile.rules	2016-02-02 11:51:02.057248471 -0800
+@@ -604,7 +604,7 @@
+ endif
+ 
+ ifdef SHARED_LIBRARY
+-ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
++ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW SunOS))
+ ifneq ($(HOST_OS),Darwin)
+   LD.Flags += $(RPATH) -Wl,'$$ORIGIN'
+ else
+@@ -665,7 +665,9 @@
+   endif
+   ifneq ($(HOST_OS), Darwin)
+     ifdef TOOLNAME
++      ifneq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
+       LD.Flags += $(RPATH) -Wl,'$$ORIGIN/../lib'
++      endif
+       ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
+         LD.Flags += -Wl,-z -Wl,discard-unused=sections
+         LD.Flags += -Wl,-M -Wl,$(PROJ_SRC_ROOT)/mapfiles/map.gnu-sections