about summary refs log tree commit diff
diff options
context:
space:
mode:
authorachernyak <artemchernyak@gmail.com>2017-05-09 14:40:42 -0500
committerachernyak <artemchernyak@gmail.com>2017-05-09 17:23:41 -0500
commit35812d1746b8b98200533bd2bef18649ef5807d1 (patch)
tree7fa9c1b6863a7d995f7058993894b0ccb6012f11
parentdfb740f83ca1d6f2056f5cf8de1adbe81b973438 (diff)
parentf3fc547194d22dc673274ac20e9a7b1e607cb862 (diff)
downloadrust-35812d1746b8b98200533bd2bef18649ef5807d1.tar.gz
rust-35812d1746b8b98200533bd2bef18649ef5807d1.zip
resolved merge conflicts
-rw-r--r--.mailmap1
-rw-r--r--.travis.yml17
-rwxr-xr-xconfigure1
-rw-r--r--src/Cargo.lock18
-rw-r--r--src/bootstrap/check.rs2
-rw-r--r--src/bootstrap/step.rs36
m---------src/doc/nomicon0
-rw-r--r--src/doc/rustc-ux-guidelines.md22
-rw-r--r--src/etc/platform-intrinsics/hexagon/hvx_v60.json1326
-rw-r--r--src/grammar/.gitignore3
-rw-r--r--src/grammar/lexer.l343
-rw-r--r--src/grammar/parser-lalr-main.c203
-rw-r--r--src/grammar/parser-lalr.y1945
-rw-r--r--src/grammar/raw-string-literal-ambiguity.md64
-rwxr-xr-xsrc/grammar/testparser.py76
-rw-r--r--src/grammar/tokens.h91
-rw-r--r--src/liballoc/arc.rs42
-rw-r--r--src/liballoc/boxed.rs2
-rw-r--r--src/liballoc/heap.rs6
-rw-r--r--src/liballoc/raw_vec.rs28
-rw-r--r--src/liballoc/rc.rs50
-rw-r--r--src/libarena/lib.rs4
-rw-r--r--src/libcollections/btree/node.rs18
-rw-r--r--src/libcollections/linked_list.rs72
-rw-r--r--src/libcollections/slice.rs9
-rw-r--r--src/libcollections/vec.rs22
-rw-r--r--src/libcollections/vec_deque.rs2
-rw-r--r--src/libcore/cell.rs4
-rw-r--r--src/libcore/nonzero.rs13
-rw-r--r--src/libcore/option.rs12
-rw-r--r--src/libcore/ptr.rs171
-rw-r--r--src/libcore/tests/nonzero.rs4
-rw-r--r--src/libcore/tests/ptr.rs8
-rw-r--r--src/libflate/lib.rs4
m---------src/liblibc0
-rw-r--r--src/libpanic_unwind/windows.rs4
-rw-r--r--src/librustc/dep_graph/dep_node.rs28
-rw-r--r--src/librustc/dep_graph/mod.rs3
-rw-r--r--src/librustc/dep_graph/visit.rs77
-rw-r--r--src/librustc/hir/check_attr.rs4
-rw-r--r--src/librustc/hir/def_id.rs5
-rw-r--r--src/librustc/hir/intravisit.rs19
-rw-r--r--src/librustc/hir/itemlikevisit.rs5
-rw-r--r--src/librustc/hir/map/mod.rs19
-rw-r--r--src/librustc/hir/svh.rs4
-rw-r--r--src/librustc/ich/caching_codemap_view.rs35
-rw-r--r--src/librustc/ich/impls_cstore.rs40
-rw-r--r--src/librustc/ich/impls_hir.rs8
-rw-r--r--src/librustc/ich/impls_syntax.rs80
-rw-r--r--src/librustc/ich/mod.rs1
-rw-r--r--src/librustc/infer/error_reporting/mod.rs4
-rw-r--r--src/librustc/lint/context.rs4
-rw-r--r--src/librustc/middle/const_val.rs2
-rw-r--r--src/librustc/middle/cstore.rs30
-rw-r--r--src/librustc/middle/effect.rs2
-rw-r--r--src/librustc/middle/entry.rs8
-rw-r--r--src/librustc/middle/intrinsicck.rs4
-rw-r--r--src/librustc/middle/region.rs160
-rw-r--r--src/librustc/middle/resolve_lifetime.rs14
-rw-r--r--src/librustc/session/config.rs84
-rw-r--r--src/librustc/session/mod.rs23
-rw-r--r--src/librustc/traits/error_reporting.rs22
-rw-r--r--src/librustc/ty/context.rs18
-rw-r--r--src/librustc/ty/maps.rs30
-rw-r--r--src/librustc/ty/mod.rs81
-rw-r--r--src/librustc/ty/relate.rs10
-rw-r--r--src/librustc/ty/subst.rs4
-rw-r--r--src/librustc/ty/util.rs50
-rw-r--r--src/librustc_borrowck/borrowck/check_loans.rs50
-rw-r--r--src/librustc_borrowck/borrowck/gather_loans/move_error.rs12
-rw-r--r--src/librustc_borrowck/borrowck/mir/gather_moves.rs2
-rw-r--r--src/librustc_borrowck/borrowck/mod.rs60
-rw-r--r--src/librustc_const_eval/check_match.rs26
-rw-r--r--src/librustc_data_structures/array_vec.rs2
-rw-r--r--src/librustc_data_structures/flock.rs4
-rw-r--r--src/librustc_data_structures/obligation_forest/node_index.rs2
-rw-r--r--src/librustc_data_structures/stable_hasher.rs10
-rw-r--r--src/librustc_data_structures/transitive_relation.rs83
-rw-r--r--src/librustc_driver/driver.rs3
-rw-r--r--src/librustc_driver/target_features.rs3
-rw-r--r--src/librustc_errors/diagnostic.rs5
-rw-r--r--src/librustc_errors/diagnostic_builder.rs6
-rw-r--r--src/librustc_errors/emitter.rs11
-rw-r--r--src/librustc_errors/lib.rs8
-rw-r--r--src/librustc_incremental/assert_dep_graph.rs24
-rw-r--r--src/librustc_incremental/calculate_svh/mod.rs61
-rw-r--r--src/librustc_incremental/persist/data.rs6
-rw-r--r--src/librustc_incremental/persist/dirty_clean.rs2
-rw-r--r--src/librustc_incremental/persist/hash.rs82
-rw-r--r--src/librustc_incremental/persist/load.rs57
-rw-r--r--src/librustc_incremental/persist/save.rs11
-rw-r--r--src/librustc_lint/builtin.rs76
-rw-r--r--src/librustc_lint/lib.rs5
-rw-r--r--src/librustc_lint/unused.rs2
-rw-r--r--src/librustc_metadata/astencode.rs4
-rw-r--r--src/librustc_metadata/creader.rs82
-rw-r--r--src/librustc_metadata/cstore.rs53
-rw-r--r--src/librustc_metadata/cstore_impl.rs55
-rw-r--r--src/librustc_metadata/decoder.rs236
-rw-r--r--src/librustc_metadata/encoder.rs931
-rw-r--r--src/librustc_metadata/index_builder.rs122
-rw-r--r--src/librustc_metadata/isolated_encoder.rs160
-rw-r--r--src/librustc_metadata/lib.rs1
-rw-r--r--src/librustc_metadata/locator.rs2
-rw-r--r--src/librustc_metadata/schema.rs77
-rw-r--r--src/librustc_mir/transform/qualify_consts.rs16
-rw-r--r--src/librustc_mir/util/pretty.rs13
-rw-r--r--src/librustc_passes/ast_validation.rs6
-rw-r--r--src/librustc_passes/consts.rs2
-rw-r--r--src/librustc_passes/loops.rs8
-rw-r--r--src/librustc_passes/static_recursion.rs2
-rw-r--r--src/librustc_platform_intrinsics/hexagon.rs2937
-rw-r--r--src/librustc_platform_intrinsics/lib.rs23
-rw-r--r--src/librustc_privacy/lib.rs6
-rw-r--r--src/librustc_resolve/lib.rs70
-rw-r--r--src/librustc_resolve/macros.rs2
-rw-r--r--src/librustc_resolve/resolve_imports.rs6
-rw-r--r--src/librustc_save_analysis/Cargo.toml5
-rw-r--r--src/librustc_save_analysis/dump_visitor.rs2
-rw-r--r--src/librustc_save_analysis/lib.rs17
-rw-r--r--src/librustc_trans/base.rs5
-rw-r--r--src/librustc_typeck/astconv.rs43
-rw-r--r--src/librustc_typeck/check/_match.rs22
-rw-r--r--src/librustc_typeck/check/autoderef.rs2
-rw-r--r--src/librustc_typeck/check/callee.rs2
-rw-r--r--src/librustc_typeck/check/cast.rs4
-rw-r--r--src/librustc_typeck/check/closure.rs1
-rw-r--r--src/librustc_typeck/check/coercion.rs6
-rw-r--r--src/librustc_typeck/check/compare_method.rs18
-rw-r--r--src/librustc_typeck/check/intrinsic.rs8
-rw-r--r--src/librustc_typeck/check/method/confirm.rs52
-rw-r--r--src/librustc_typeck/check/method/suggest.rs6
-rw-r--r--src/librustc_typeck/check/mod.rs79
-rw-r--r--src/librustc_typeck/check/op.rs6
-rw-r--r--src/librustc_typeck/check/wfcheck.rs6
-rw-r--r--src/librustc_typeck/check/writeback.rs8
-rw-r--r--src/librustc_typeck/coherence/builtin.rs10
-rw-r--r--src/librustc_typeck/coherence/inherent_impls.rs4
-rw-r--r--src/librustc_typeck/coherence/inherent_impls_overlap.rs4
-rw-r--r--src/librustc_typeck/coherence/mod.rs2
-rw-r--r--src/librustc_typeck/coherence/orphan.rs4
-rw-r--r--src/librustc_typeck/coherence/overlap.rs4
-rw-r--r--src/librustc_typeck/collect.rs21
-rw-r--r--src/librustc_typeck/impl_wf_check.rs6
-rw-r--r--src/librustc_typeck/lib.rs37
-rw-r--r--src/librustc_typeck/variance/README.md68
-rw-r--r--src/librustc_typeck/variance/constraints.rs244
-rw-r--r--src/librustc_typeck/variance/mod.rs67
-rw-r--r--src/librustc_typeck/variance/solve.rs34
-rw-r--r--src/librustc_typeck/variance/terms.rs43
-rw-r--r--src/librustc_typeck/variance/test.rs41
-rw-r--r--src/librustdoc/Cargo.toml1
-rw-r--r--src/librustdoc/clean/mod.rs8
-rw-r--r--src/librustdoc/core.rs5
-rw-r--r--src/librustdoc/html/format.rs4
-rw-r--r--src/librustdoc/html/layout.rs1
-rw-r--r--src/librustdoc/html/markdown.rs75
-rw-r--r--src/librustdoc/html/render.rs2
-rw-r--r--src/librustdoc/html/static/COPYRIGHT.txt5
-rw-r--r--src/librustdoc/html/static/jquery-2.1.4.min.js4
-rw-r--r--src/librustdoc/html/static/main.js689
-rw-r--r--src/librustdoc/lib.rs12
-rw-r--r--src/librustdoc/markdown.rs5
-rw-r--r--src/librustdoc/test.rs6
-rw-r--r--src/libstd/build.rs5
-rw-r--r--src/libstd/collections/hash/table.rs24
-rw-r--r--src/libstd/fs.rs2
-rw-r--r--src/libstd/process.rs10
-rw-r--r--src/libstd/sys/unix/thread_local.rs5
-rw-r--r--src/libstd/sys/windows/c.rs8
-rw-r--r--src/libstd/sys/windows/thread_local.rs165
-rw-r--r--src/libstd/sys_common/net.rs19
-rw-r--r--src/libstd/sys_common/thread_local.rs37
-rw-r--r--src/libstd/thread/mod.rs74
-rw-r--r--src/libstd/time/duration.rs29
-rw-r--r--src/libstd_unicode/tables.rs2
-rwxr-xr-xsrc/libstd_unicode/unicode.py (renamed from src/etc/unicode.py)2
-rw-r--r--src/libsyntax/Cargo.toml2
-rw-r--r--src/libsyntax/attr.rs3
-rw-r--r--src/libsyntax/codemap.rs43
-rw-r--r--src/libsyntax/ext/base.rs12
-rw-r--r--src/libsyntax/ext/expand.rs4
-rw-r--r--src/libsyntax/ext/tt/macro_rules.rs10
-rw-r--r--src/libsyntax/lib.rs7
-rw-r--r--src/libsyntax/parse/lexer/mod.rs4
-rw-r--r--src/libsyntax/parse/mod.rs8
-rw-r--r--src/libsyntax/parse/parser.rs67
-rw-r--r--src/libsyntax/print/pprust.rs2
-rw-r--r--src/libsyntax/test.rs4
-rw-r--r--src/libsyntax_pos/lib.rs6
-rw-r--r--src/libtest/lib.rs74
m---------src/llvm0
m---------src/rust-installer0
-rw-r--r--src/rustllvm/llvm-rebuild-trigger2
-rw-r--r--src/test/compile-fail/closure-no-fn-1.rs (renamed from src/test/compile-fail/closure-no-fn.rs)6
-rw-r--r--src/test/compile-fail/closure-no-fn-2.rs18
-rw-r--r--src/test/compile-fail/closure-no-fn-3.rs18
-rw-r--r--src/test/compile-fail/dep-graph-struct-signature.rs6
-rw-r--r--src/test/compile-fail/dep-graph-type-alias.rs12
-rw-r--r--src/test/compile-fail/dep-graph-variance-alias.rs32
-rw-r--r--src/test/compile-fail/issue-3008-1.rs13
-rw-r--r--src/test/compile-fail/issue-3008-2.rs1
-rw-r--r--src/test/compile-fail/issue-32326.rs2
-rw-r--r--src/test/compile-fail/issue-3779.rs6
-rw-r--r--src/test/compile-fail/issue-40000.rs3
-rw-r--r--src/test/compile-fail/issue-41255.rs55
-rw-r--r--src/test/compile-fail/issue-41726.rs17
-rw-r--r--src/test/compile-fail/issue-41742.rs35
-rw-r--r--src/test/compile-fail/non-exhaustive-match.rs1
-rw-r--r--src/test/compile-fail/regions-adjusted-lvalue-op.rs26
-rw-r--r--src/test/compile-fail/type-recursive.rs2
-rw-r--r--src/test/compile-fail/variance-regions-direct.rs1
-rw-r--r--src/test/compile-fail/variance-regions-indirect.rs4
-rw-r--r--src/test/compile-fail/variance-trait-bounds.rs5
-rw-r--r--src/test/incremental/remapped_paths_cc/auxiliary/extern_crate.rs24
-rw-r--r--src/test/incremental/remapped_paths_cc/main.rs42
-rw-r--r--src/test/parse-fail/lex-bare-cr-string-literal-doc-comment.rs6
-rw-r--r--src/test/run-make/tools.mk1
-rw-r--r--src/test/run-make/trace-macros-flag/Makefile9
-rw-r--r--src/test/run-make/trace-macros-flag/hello.trace2
-rw-r--r--src/test/run-pass-fulldeps/auxiliary/issue_24106.rs23
-rw-r--r--src/test/run-pass-fulldeps/issue_24106.rs17
-rw-r--r--src/test/run-pass/associated-const-type-parameters.rs9
-rw-r--r--src/test/run-pass/closure_to_fn_coercion-expected-types.rs17
-rw-r--r--src/test/run-pass/issue-22066.rs21
-rw-r--r--src/test/run-pass/issue-41697.rs50
-rw-r--r--src/test/run-pass/lex-bare-cr-nondoc-comment.rs18
-rw-r--r--src/test/rustdoc/issue-41783.rs25
-rw-r--r--src/test/ui/did_you_mean/issue-41679.rs13
-rw-r--r--src/test/ui/did_you_mean/issue-41679.stderr10
-rw-r--r--src/test/ui/issue-41652/auxiliary/issue_41652_b.rs16
-rw-r--r--src/test/ui/issue-41652/issue_41652.rs26
-rw-r--r--src/test/ui/issue-41652/issue_41652.stderr12
-rw-r--r--src/test/ui/macros/trace-macro.rs (renamed from src/test/run-make/trace-macros-flag/hello.rs)2
-rw-r--r--src/test/ui/macros/trace-macro.stderr9
-rw-r--r--src/test/ui/span/E0072.stderr3
-rw-r--r--src/test/ui/span/multiline-span-E0072.stderr1
-rw-r--r--src/test/ui/span/recursive-type-field.rs28
-rw-r--r--src/test/ui/span/recursive-type-field.stderr31
-rw-r--r--src/tools/build-manifest/src/main.rs50
-rw-r--r--src/tools/compiletest/src/main.rs1
-rw-r--r--src/tools/remote-test-client/src/main.rs16
-rw-r--r--src/tools/remote-test-server/src/main.rs55
-rw-r--r--src/tools/tidy/src/style.rs2
244 files changed, 11452 insertions, 2606 deletions
diff --git a/.mailmap b/.mailmap
index 4b4f343d15a..ee5b6f257b5 100644
--- a/.mailmap
+++ b/.mailmap
@@ -139,6 +139,7 @@ Margaret Meyerhofer <mmeyerho@andrew.cmu.edu> <mmeyerho@andrew>
 Mark Sinclair <mark.edward.x@gmail.com>
 Mark Sinclair <mark.edward.x@gmail.com> =Mark Sinclair <=125axel125@gmail.com>
 Markus Westerlind <marwes91@gmail.com> Markus <marwes91@gmail.com>
+Martin Hafskjold Thoresen <martinhath@gmail.com>
 Matej Lach <matej.lach@gmail.com> Matej Ľach <matej.lach@gmail.com>
 Matt Brubeck <mbrubeck@limpet.net> <mbrubeck@cs.hmc.edu>
 Matthew Auld <matthew.auld@intel.com>
diff --git a/.travis.yml b/.travis.yml
index 9ca8cecd482..4fcf6f02def 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -95,7 +95,10 @@ matrix:
         MACOSX_DEPLOYMENT_TARGET=10.7
       os: osx
       osx_image: xcode7
-      install: *osx_install_sccache
+      install:
+        - travis_retry brew update
+        - travis_retry brew install xz
+        - *osx_install_sccache
     - env: >
         RUST_CHECK_TARGET=dist
         RUST_CONFIGURE_ARGS="--target=aarch64-apple-ios,armv7-apple-ios,armv7s-apple-ios,i386-apple-ios,x86_64-apple-ios --enable-extended --enable-sanitizers"
@@ -106,7 +109,10 @@ matrix:
         MACOSX_DEPLOYMENT_TARGET=10.7
       os: osx
       osx_image: xcode7
-      install: *osx_install_sccache
+      install:
+        - travis_retry brew update
+        - travis_retry brew install xz
+        - *osx_install_sccache
 
     # "alternate" deployments, these are "nightlies" but don't have assertions
     # turned on, they're deployed to a different location primarily for projects
@@ -123,7 +129,10 @@ matrix:
         MACOSX_DEPLOYMENT_TARGET=10.7
       os: osx
       osx_image: xcode7
-      install: *osx_install_sccache
+      install:
+        - travis_retry brew update
+        - travis_retry brew install xz
+        - *osx_install_sccache
 
 env:
   global:
@@ -185,7 +194,7 @@ after_failure:
 
 # Save tagged docker images we created and load them if they're available
 # Travis saves caches whether the build failed or not, nuke rustsrc if
-# the failure was while updating it (as it may be in an bad state)
+# the failure was while updating it (as it may be in a bad state)
 # https://github.com/travis-ci/travis-ci/issues/4472
 before_cache:
   - docker history -q rust-ci |
diff --git a/configure b/configure
index c5ecc223689..db41f0dfb94 100755
--- a/configure
+++ b/configure
@@ -510,7 +510,6 @@ valopt default-ar     "ar" "the default ar"
 opt_nosave manage-submodules 1 "let the build manage the git submodules"
 opt_nosave clang 0 "prefer clang to gcc for building the runtime"
 opt_nosave jemalloc 1 "build liballoc with jemalloc"
-opt elf-tls 1 "elf thread local storage on platforms where supported"
 opt full-bootstrap 0 "build three compilers instead of two"
 opt extended 0 "build an extended rust tool set"
 
diff --git a/src/Cargo.lock b/src/Cargo.lock
index 21b167f6d42..3dd8231a49f 100644
--- a/src/Cargo.lock
+++ b/src/Cargo.lock
@@ -411,16 +411,16 @@ version = "0.1.0"
 
 [[package]]
 name = "rls-data"
-version = "0.1.0"
+version = "0.3.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
- "rls-span 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rls-span 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "rustc-serialize 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "rls-span"
-version = "0.1.0"
+version = "0.4.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
  "rustc-serialize 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -719,10 +719,11 @@ name = "rustc_save_analysis"
 version = "0.0.0"
 dependencies = [
  "log 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
- "rls-data 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "rls-span 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rls-data 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rls-span 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "rustc 0.0.0",
  "rustc-serialize 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rustc_typeck 0.0.0",
  "syntax 0.0.0",
  "syntax_pos 0.0.0",
 ]
@@ -793,6 +794,7 @@ dependencies = [
  "rustc_metadata 0.0.0",
  "rustc_resolve 0.0.0",
  "rustc_trans 0.0.0",
+ "rustc_typeck 0.0.0",
  "serialize 0.0.0",
  "syntax 0.0.0",
  "syntax_pos 0.0.0",
@@ -858,8 +860,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 name = "syntax"
 version = "0.0.0"
 dependencies = [
+ "bitflags 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)",
  "log 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
- "rustc_bitflags 0.0.0",
  "rustc_data_structures 0.0.0",
  "rustc_errors 0.0.0",
  "serialize 0.0.0",
@@ -1019,8 +1021,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 "checksum quick-error 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0aad603e8d7fb67da22dbdf1f4b826ce8829e406124109e73cf1b2454b93a71c"
 "checksum regex 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4278c17d0f6d62dfef0ab00028feb45bd7d2102843f80763474eeb1be8a10c01"
 "checksum regex-syntax 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2f9191b1f57603095f105d317e375d19b1c9c5c3185ea9633a99a6dcbed04457"
-"checksum rls-data 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "af1dfff00189fd7b78edb9af131b0de703676c04fa8126aed77fd2c586775a4d"
-"checksum rls-span 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8656f7b850ac85fb204ef94318c641bbb15a32766e12f9a589a23e4c0fbc38db"
+"checksum rls-data 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fc4277ce3c57f456b11fe3145b181a844a25201bab5cbaa1978457e6e2f27d47"
+"checksum rls-span 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5d7c7046dc6a92f2ae02ed302746db4382e75131b9ce20ce967259f6b5867a6a"
 "checksum rustc-serialize 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)" = "684ce48436d6465300c9ea783b6b14c4361d6b8dcbb1375b486a69cc19e2dfb0"
 "checksum serde 0.9.11 (registry+https://github.com/rust-lang/crates.io-index)" = "a702319c807c016e51f672e5c77d6f0b46afddd744b5e437d6b8436b888b458f"
 "checksum serde_json 0.9.9 (registry+https://github.com/rust-lang/crates.io-index)" = "dbc45439552eb8fb86907a2c41c1fd0ef97458efb87ff7f878db466eb581824e"
diff --git a/src/bootstrap/check.rs b/src/bootstrap/check.rs
index d7457e08869..d24bb074cd3 100644
--- a/src/bootstrap/check.rs
+++ b/src/bootstrap/check.rs
@@ -529,7 +529,7 @@ fn find_tests(dir: &Path,
     }
 }
 
-pub fn emulator_copy_libs(build: &Build, compiler: &Compiler, target: &str) {
+pub fn remote_copy_libs(build: &Build, compiler: &Compiler, target: &str) {
     if !build.remote_tested(target) {
         return
     }
diff --git a/src/bootstrap/step.rs b/src/bootstrap/step.rs
index f69b68a9545..970c0bc565d 100644
--- a/src/bootstrap/step.rs
+++ b/src/bootstrap/step.rs
@@ -307,7 +307,7 @@ pub fn build_rules<'a>(build: &'a Build) -> Rules {
                  .dep(|s| s.name("libtest"))
                  .dep(|s| s.name("tool-compiletest").target(s.host).stage(0))
                  .dep(|s| s.name("test-helpers"))
-                 .dep(|s| s.name("emulator-copy-libs"))
+                 .dep(|s| s.name("remote-copy-libs"))
                  .default(mode != "pretty") // pretty tests don't run everywhere
                  .run(move |s| {
                      check::compiletest(build, &s.compiler(), s.target, mode, dir)
@@ -346,7 +346,7 @@ pub fn build_rules<'a>(build: &'a Build) -> Rules {
              .dep(|s| s.name("tool-compiletest").target(s.host).stage(0))
              .dep(|s| s.name("test-helpers"))
              .dep(|s| s.name("debugger-scripts"))
-             .dep(|s| s.name("emulator-copy-libs"))
+             .dep(|s| s.name("remote-copy-libs"))
              .run(move |s| check::compiletest(build, &s.compiler(), s.target,
                                          "debuginfo-gdb", "debuginfo"));
         let mut rule = rules.test("check-debuginfo", "src/test/debuginfo");
@@ -400,14 +400,14 @@ pub fn build_rules<'a>(build: &'a Build) -> Rules {
     for (krate, path, _default) in krates("std") {
         rules.test(&krate.test_step, path)
              .dep(|s| s.name("libtest"))
-             .dep(|s| s.name("emulator-copy-libs"))
+             .dep(|s| s.name("remote-copy-libs"))
              .run(move |s| check::krate(build, &s.compiler(), s.target,
                                         Mode::Libstd, TestKind::Test,
                                         Some(&krate.name)));
     }
     rules.test("check-std-all", "path/to/nowhere")
          .dep(|s| s.name("libtest"))
-         .dep(|s| s.name("emulator-copy-libs"))
+         .dep(|s| s.name("remote-copy-libs"))
          .default(true)
          .run(move |s| check::krate(build, &s.compiler(), s.target,
                                     Mode::Libstd, TestKind::Test, None));
@@ -416,14 +416,14 @@ pub fn build_rules<'a>(build: &'a Build) -> Rules {
     for (krate, path, _default) in krates("std") {
         rules.bench(&krate.bench_step, path)
              .dep(|s| s.name("libtest"))
-             .dep(|s| s.name("emulator-copy-libs"))
+             .dep(|s| s.name("remote-copy-libs"))
              .run(move |s| check::krate(build, &s.compiler(), s.target,
                                         Mode::Libstd, TestKind::Bench,
                                         Some(&krate.name)));
     }
     rules.bench("bench-std-all", "path/to/nowhere")
          .dep(|s| s.name("libtest"))
-         .dep(|s| s.name("emulator-copy-libs"))
+         .dep(|s| s.name("remote-copy-libs"))
          .default(true)
          .run(move |s| check::krate(build, &s.compiler(), s.target,
                                     Mode::Libstd, TestKind::Bench, None));
@@ -431,21 +431,21 @@ pub fn build_rules<'a>(build: &'a Build) -> Rules {
     for (krate, path, _default) in krates("test") {
         rules.test(&krate.test_step, path)
              .dep(|s| s.name("libtest"))
-             .dep(|s| s.name("emulator-copy-libs"))
+             .dep(|s| s.name("remote-copy-libs"))
              .run(move |s| check::krate(build, &s.compiler(), s.target,
                                         Mode::Libtest, TestKind::Test,
                                         Some(&krate.name)));
     }
     rules.test("check-test-all", "path/to/nowhere")
          .dep(|s| s.name("libtest"))
-         .dep(|s| s.name("emulator-copy-libs"))
+         .dep(|s| s.name("remote-copy-libs"))
          .default(true)
          .run(move |s| check::krate(build, &s.compiler(), s.target,
                                     Mode::Libtest, TestKind::Test, None));
     for (krate, path, _default) in krates("rustc-main") {
         rules.test(&krate.test_step, path)
              .dep(|s| s.name("librustc"))
-             .dep(|s| s.name("emulator-copy-libs"))
+             .dep(|s| s.name("remote-copy-libs"))
              .host(true)
              .run(move |s| check::krate(build, &s.compiler(), s.target,
                                         Mode::Librustc, TestKind::Test,
@@ -453,7 +453,7 @@ pub fn build_rules<'a>(build: &'a Build) -> Rules {
     }
     rules.test("check-rustc-all", "path/to/nowhere")
          .dep(|s| s.name("librustc"))
-         .dep(|s| s.name("emulator-copy-libs"))
+         .dep(|s| s.name("remote-copy-libs"))
          .default(true)
          .host(true)
          .run(move |s| check::krate(build, &s.compiler(), s.target,
@@ -500,17 +500,17 @@ pub fn build_rules<'a>(build: &'a Build) -> Rules {
     rules.build("openssl", "path/to/nowhere")
          .run(move |s| native::openssl(build, s.target));
 
-    // Some test suites are run inside emulators, and most of our test binaries
-    // are linked dynamically which means we need to ship the standard library
-    // and such to the emulator ahead of time. This step represents this and is
-    // a dependency of all test suites.
+    // Some test suites are run inside emulators or on remote devices, and most
+    // of our test binaries are linked dynamically which means we need to ship
+    // the standard library and such to the emulator ahead of time. This step
+    // represents this and is a dependency of all test suites.
     //
     // Most of the time this step is a noop (the `check::emulator_copy_libs`
     // only does work if necessary). For some steps such as shipping data to
     // QEMU we have to build our own tools so we've got conditional dependencies
-    // on those programs as well. Note that the QEMU client is built for the
-    // build target (us) and the server is built for the target.
-    rules.test("emulator-copy-libs", "path/to/nowhere")
+    // on those programs as well. Note that the remote test client is built for
+    // the build target (us) and the server is built for the target.
+    rules.test("remote-copy-libs", "path/to/nowhere")
          .dep(|s| s.name("libtest"))
          .dep(move |s| {
              if build.remote_tested(s.target) {
@@ -526,7 +526,7 @@ pub fn build_rules<'a>(build: &'a Build) -> Rules {
                  Step::noop()
              }
          })
-         .run(move |s| check::emulator_copy_libs(build, &s.compiler(), s.target));
+         .run(move |s| check::remote_copy_libs(build, &s.compiler(), s.target));
 
     rules.test("check-bootstrap", "src/bootstrap")
          .default(true)
diff --git a/src/doc/nomicon b/src/doc/nomicon
-Subproject 616b98444ff4eb5260deee95ee3e090dfd98b94
+Subproject 6fa139b1630a9bb95dcd60cfc90aff9c19e5458
diff --git a/src/doc/rustc-ux-guidelines.md b/src/doc/rustc-ux-guidelines.md
index 15b3bfebfac..323d49e4691 100644
--- a/src/doc/rustc-ux-guidelines.md
+++ b/src/doc/rustc-ux-guidelines.md
@@ -1,14 +1,14 @@
 % Rustc UX guidelines
 
 Don't forget the user. Whether human or another program, such as an IDE, a
-good user experience with the compiler goes a long way into making developer
-lives better. We don't want users to be baffled by compiler output or
+good user experience with the compiler goes a long way toward making developers'
+lives better. We do not want users to be baffled by compiler output or
 learn arcane patterns to compile their program.
 
 ## Error, Warning, Help, Note Messages
 
-When the compiler detects a problem, it can emit either an error, warning,
-note, or help message.
+When the compiler detects a problem, it can emit one of the following: an error, a warning,
+a note, or a help message.
 
 An `error` is emitted when the compiler detects a problem that makes it unable
  to compile the program, either because the program is invalid or the
@@ -17,11 +17,11 @@ An `error` is emitted when the compiler detects a problem that makes it unable
 A `warning` is emitted when the compiler detects something odd about a
 program. For instance, dead code and unused `Result` values.
 
-A `help` is emitted following either an `error` or `warning` giving extra
+A `help` message is emitted following an `error` or `warning` to give additional
 information to the user about how to solve their problem.
 
-A `note` is for identifying additional circumstances and parts of the code
-that lead to a warning or error. For example, the borrow checker will note any
+A `note` is emitted to identify additional circumstances and parts of the code
+that caused the warning or error. For example, the borrow checker will note any
 previous conflicting borrows.
 
 * Write in plain simple English. If your message, when shown on a – possibly
@@ -56,18 +56,22 @@ Error explanations are long form descriptions of error messages provided with
 the compiler. They are accessible via the `--explain` flag. Each explanation
 comes with an example of how to trigger it and advice on how to fix it.
 
+Please read [RFC 1567](https://github.com/rust-lang/rfcs/blob/master/text/1567-long-error-codes-explanation-normalization.md)
+for details on how to format and write long error codes.
+
 * All of them are accessible [online](http://doc.rust-lang.org/error-index.html),
   which are auto-generated from rustc source code in different places:
   [librustc](https://github.com/rust-lang/rust/blob/master/src/librustc/diagnostics.rs),
+  [libsyntax](https://github.com/rust-lang/rust/blob/master/src/libsyntax/diagnostics.rs),
   [librustc_borrowck](https://github.com/rust-lang/rust/blob/master/src/librustc_borrowck/diagnostics.rs),
   [librustc_const_eval](https://github.com/rust-lang/rust/blob/master/src/librustc_const_eval/diagnostics.rs),
-  [librustc_lint](https://github.com/rust-lang/rust/blob/master/src/librustc_lint/types.rs),
   [librustc_metadata](https://github.com/rust-lang/rust/blob/master/src/librustc_metadata/diagnostics.rs),
   [librustc_mir](https://github.com/rust-lang/rust/blob/master/src/librustc_mir/diagnostics.rs),
   [librustc_passes](https://github.com/rust-lang/rust/blob/master/src/librustc_passes/diagnostics.rs),
   [librustc_privacy](https://github.com/rust-lang/rust/blob/master/src/librustc_privacy/diagnostics.rs),
   [librustc_resolve](https://github.com/rust-lang/rust/blob/master/src/librustc_resolve/diagnostics.rs),
   [librustc_trans](https://github.com/rust-lang/rust/blob/master/src/librustc_trans/diagnostics.rs),
+  [librustc_plugin](https://github.com/rust-lang/rust/blob/master/src/librustc_plugin/diagnostics.rs),
   [librustc_typeck](https://github.com/rust-lang/rust/blob/master/src/librustc_typeck/diagnostics.rs).
 * Explanations have full markdown support. Use it, especially to highlight
 code with backticks.
@@ -79,7 +83,7 @@ code with backticks.
 * Flags should be orthogonal to each other. For example, if we'd have a
 json-emitting variant of multiple actions `foo` and `bar`, an additional
 --json flag is better than adding `--foo-json` and `--bar-json`.
-* Always give options a long descriptive name, if only for better
+* Always give options a long descriptive name, if only for more
 understandable compiler scripts.
 * The `--verbose` flag is for adding verbose information to `rustc` output
 when not compiling a program. For example, using it with the `--version` flag
diff --git a/src/etc/platform-intrinsics/hexagon/hvx_v60.json b/src/etc/platform-intrinsics/hexagon/hvx_v60.json
new file mode 100644
index 00000000000..a1897e6bf61
--- /dev/null
+++ b/src/etc/platform-intrinsics/hexagon/hvx_v60.json
@@ -0,0 +1,1326 @@
+{
+    "platform": "Q6_",
+    "intrinsic_prefix": "",
+    "llvm_prefix": "llvm.hexagon.V6.",
+    "number_info": {
+        "signed": {
+            "kind": "s",
+            "data_type": { "8": "b", "16": "h", "32": "w" },
+            "data_type_plain": { "8": "b", "16": "h", "32": "w" }
+        },
+        "unsigned": {
+            "kind": "u",
+            "data_type": { "8": "ub", "16": "uh", "32": "uw" },
+            "data_type_plain": { "8": "b", "16": "h", "32": "w" }
+        },
+        "float": {
+            "kind": "f",
+            "data_type": { "8": "b", "16": "h", "32": "w" },
+            "data_type_plain": { "8": "b", "16": "h", "32": "w" }
+        }
+    },
+    "width_info": {
+        "64": { "width_b": "64", "width_suffix": "" },
+        "128": { "width_b": "128", "width_suffix": ".128B" },
+        "512": { "width_b": "64", "width_suffix": "" },
+        "1024": { "widthd_b": "64", "width_b": "128", "width_suffix": ".128B",  "widthd_suffix": "" },
+        "2048": { "widthd_b": "128", "widthd_suffix": ".128B" }
+    },
+    "intrinsics": [
+        {
+            "intrinsic": "R_vextract{1.width_b}",
+            "width": [512, 1024],
+            "llvm": "extractw{1.width_suffix}",
+            "ret": "U32",
+            "args": ["u32", "U32"]
+        },
+        {
+            "intrinsic": "V_lo{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "lo{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0d"]
+        },
+        {
+            "intrinsic": "V_hi{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "hi{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0d"]
+        },
+        {
+            "intrinsic": "V_vsplat_R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "lvsplat{1.data_type}{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0S"]
+        },
+        {
+            "intrinsic": "Q_and_QQ{0.width_b}",
+            "width": [64, 128],
+            "llvm": "pred.and{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "Q_not_Q{0.width_b}",
+            "width": [64, 128],
+            "llvm": "pred.not{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "Q_or_QQ{0.width_b}",
+            "width": [64, 128],
+            "llvm": "pred.or{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "Q_xor_QQ{0.width_b}",
+            "width": [64, 128],
+            "llvm": "pred.xor{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vabsdiff_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vabsdiff{1.data_type}{0.width_suffix}",
+            "ret": "u(8-16)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vabsdiff_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vabsdiff{1.data_type}{0.width_suffix}",
+            "ret": "u(16-32)",
+            "args": ["0s", "0s"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vabs_V{1.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vabs{1.data_type}{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vabs_V{1.data_type}_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vabs{1.data_type}.sat{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vadd_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vadd{0.data_type}{0.width_suffix}",
+            "ret": "s(8-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vadd_V{1.data_type}V{2.data_type}_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vadd{0.data_type}sat{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vadd_V{1.data_type}V{2.data_type}_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vadd{0.data_type}sat{0.width_suffix}",
+            "ret": "u(8-16)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vadd_W{1.data_type}W{2.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vadd{0.data_type}.dv{0.widthd_suffix}",
+            "ret": "s(8-32)d",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vadd_W{1.data_type}W{2.data_type}_sat{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vadd{0.data_type}sat.dv{0.widthd_suffix}",
+            "ret": "s(16-32)d",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vadd_W{1.data_type}W{2.data_type}_sat{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vadd{0.data_type}sat.dv{0.widthd_suffix}",
+            "ret": "u(8-16)d",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V_valign_VVR{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "valignb{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "V_valign_VVI{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "valignbi{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "V_vlalign_VVR{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vlalignb{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "V_vlalign_VVI{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vlalignbi{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "V_vand_VV{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vand{0.width_suffix}",
+            "ret": "u16",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V_vand_QR{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vandqrt{0.width_suffix}",
+            "ret": "u8",
+            "args": ["u32hhh", "U32"]
+        },
+        {
+            "intrinsic": "V_vandor_VQR{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vandqrt.acc{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0", "u32hhh", "U32"]
+        },
+        {
+            "intrinsic": "Q_vand_VR{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vandvrt{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["u8", "U32"]
+        },
+        {
+            "intrinsic": "Q_vandor_QVR{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vandvrt{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "u8", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vasl_V{1.data_type}R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vasl{0.data_type}{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vasl_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vasl{0.data_type}v{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vaslacc_V{1.data_type}V{2.data_type}R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vasl{0.data_type}.acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vasr_V{1.data_type}R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vasr{0.data_type}{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vasr_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vasr{0.data_type}v{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vasracc_V{1.data_type}V{2.data_type}R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vasr{0.data_type}.acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vasr_V{1.data_type}V{2.data_type}R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vasr{0.data_type}{1.data_type}{0.width_suffix}",
+            "ret": "s16",
+            "args": ["0hw", "0hw", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vasr_V{1.data_type}V{2.data_type}R_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vasr{1.data_type}{0.data_type_plain}sat{0.width_suffix}",
+            "ret": "i(8-16)",
+            "args": ["0hws", "0hws", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vasr_V{1.data_type}V{2.data_type}R_rnd_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vasr{1.data_type}{0.data_type_plain}rndsat{0.width_suffix}",
+            "ret": "i(8-16)",
+            "args": ["0hws", "0hws", "U32"]
+        },
+        {
+            "intrinsic": "V_equals_V{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vassign{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "W_equals_W{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vassignp{0.widthd_suffix}",
+            "ret": "u32d",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vavg_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vavg{0.data_type}{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vavg_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vavg{0.data_type}{0.width_suffix}",
+            "ret": "u(8-16)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vavg_V{1.data_type}V{2.data_type}_rnd{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vavgrnd{0.data_type}{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vavg_V{1.data_type}V{2.data_type}_rnd{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vavgrnd{0.data_type}{0.width_suffix}",
+            "ret": "u(8-16)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vcl0_V{1.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vcl0{0.data_type_plain}{0.width_suffix}",
+            "ret": "u(16-32)",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "W_vcombine_VV{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vcombine{0.widthd_suffix}",
+            "ret": "u8d",
+            "args": ["0h", "0h"]
+        },
+        {
+            "intrinsic": "V_vzero{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vd0{0.width_suffix}",
+            "ret": "u32",
+            "args": []
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdeal_V{1.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdeal{1.data_type}{0.width_suffix}",
+            "ret": "s(8-16)",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdeale_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdeal{1.data_type}4w{0.width_suffix}",
+            "ret": "s8",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W_vdeal_VVR{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vdealvdd{0.widthd_suffix}",
+            "ret": "u8d",
+            "args": ["0h", "0h", "U32"]
+        },
+        {
+            "intrinsic": "V_vdelta_VV{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdelta{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpy_V{1.data_type}Rb{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpybus{0.width_suffix}",
+            "ret": "s16",
+            "args": ["u8", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpyacc_V{1.data_type}V{2.data_type}Rb{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpybus.acc{0.width_suffix}",
+            "ret": "s16",
+            "args": ["s16", "u8", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vdmpy_W{1.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpybus.dv{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["u8d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vdmpyacc_W{1.data_type}W{2.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpybus.dv.acc{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["s16d", "u8d", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpy_V{1.data_type}Rb{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhb{0.width_suffix}",
+            "ret": "s32",
+            "args": ["s16", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpyacc_V{1.data_type}V{2.data_type}Rb{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhb.acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["s32", "s16", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vdmpy_W{1.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhb.dv{0.widthd_suffix}",
+            "ret": "s32d",
+            "args": ["s16d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vdmpyacc_W{1.data_type}W{2.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhb.dv.acc{0.widthd_suffix}",
+            "ret": "s32d",
+            "args": ["s32d", "s16d", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpy_W{1.data_type}Rh_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhisat{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0d", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpy_V{1.data_type}Rh_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhsat{0.width_suffix}",
+            "ret": "s32",
+            "args": ["s16", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpy_W{1.data_type}Ruh_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhsuisat{0.width_suffix}",
+            "ret": "s32",
+            "args": ["s16d", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpy_V{1.data_type}Ruh_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhsusat{0.width_suffix}",
+            "ret": "s32",
+            "args": ["s16", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpy_V{1.data_type}V{2.data_type}_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhvsat{0.width_suffix}",
+            "ret": "s32",
+            "args": ["s16", "s16"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpyacc_V{1.data_type}W{2.data_type}Rh_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhisat_acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vdsad_W{1.data_type}Ruh{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vdsaduh{0.widthd_suffix}",
+            "ret": "u32d",
+            "args": ["u16d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vdsadacc_W{1.data_type}W{2.data_type}Ruh{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vdsaduh.acc{0.widthd_suffix}",
+            "ret": "u32d",
+            "args": ["0", "u16d", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpyacc_V{1.data_type}V{2.data_type}Rh_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhsat_acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "s16", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpyacc_V{1.data_type}W{2.data_type}Ruh_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhsuisat_acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "s16d", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpyacc_V{1.data_type}V{2.data_type}Ruh_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhsusat_acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "s16", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vdmpyacc_V{1.data_type}V{2.data_type}V{3.data_type}_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vdmpyhvsat_acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "s16", "s16"]
+        },
+        {
+            "intrinsic": "Q_vcmp_eq_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "veq{1.data_type}{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["s(8-32)", "1"]
+        },
+        {
+            "intrinsic": "Q_vcmp_eqand_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "veq{2.data_type}.and{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "s(8-32)", "2"]
+        },
+        {
+            "intrinsic": "Q_vcmp_eqor_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "veq{2.data_type}.or{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "s(8-32)", "2"]
+        },
+        {
+            "intrinsic": "Q_vcmp_eqxacc_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "veq{2.data_type}.xor{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "s(8-32)", "2"]
+        },
+        {
+            "intrinsic": "Q_vcmp_gt_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vgt{1.data_type}{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["s(8-32)", "1"]
+        },
+        {
+            "intrinsic": "Q_vcmp_gt_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vgt{1.data_type}{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["u(8-16)", "1"]
+        },
+        {
+            "intrinsic": "Q_vcmp_gtand_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vgt{2.data_type}.and{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "s(8-32)", "2"]
+        },
+        {
+            "intrinsic": "Q_vcmp_gtand_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vgt{2.data_type}.and{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "u(8-16)", "2"]
+        },
+        {
+            "intrinsic": "Q_vcmp_gtor_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vgt{2.data_type}.or{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "s(8-32)", "2"]
+        },
+        {
+            "intrinsic": "Q_vcmp_gtor_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vgt{2.data_type}.or{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "u(8-16)", "2"]
+        },
+        {
+            "intrinsic": "Q_vcmp_gtxacc_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vgt{2.data_type}.xor{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "s(8-32)", "2"]
+        },
+        {
+            "intrinsic": "Q_vcmp_gtxacc_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vgt{2.data_type}.xor{0.width_suffix}",
+            "ret": "u32hhh",
+            "args": ["0", "u(8-16)", "2"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vinsert_V{1.data_type}R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vinsertwr{0.width_suffix}",
+            "ret": "s32",
+            "args": ["S32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vlsr_V{1.data_type}R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vlsr{0.data_type_plain}{0.width_suffix}",
+            "ret": "u(16-32)",
+            "args": ["0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vlsr_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vlsr{0.data_type}v{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vlut32_V{1.data_type}V{2.data_type}R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vlutvv{0.data_type}{0.width_suffix}",
+            "ret": "s8",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vlut16_V{1.data_type}V{2.data_type}R{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vlutvw{0.data_type}{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["s8", "s16", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vlut32or_V{1.data_type}V{2.data_type}V{3.data_type}R{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vlutvv{0.data_type}.oracc{0.width_suffix}",
+            "ret": "s8",
+            "args": ["0", "0", "0", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vlut16or_W{1.data_type}V{2.data_type}V{3.data_type}R{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vlutvw{0.data_type}.oracc{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["0", "s8", "s16", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmax_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmax{0.data_type}{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmax_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmax{0.data_type}{0.width_suffix}",
+            "ret": "u(8-16)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmin_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmin{0.data_type}{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmin_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmin{0.data_type}{0.width_suffix}",
+            "ret": "u(8-16)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpa_W{1.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpabus{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["u8d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpaacc_W{1.data_type}W{2.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpabus.acc{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["0", "u8d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpa_W{1.data_type}W{2.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpab{1.kind}{2.kind}v{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["u8d", "i8d"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpa_W{1.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpahb{0.widthd_suffix}",
+            "ret": "s32d",
+            "args": ["s16d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpaacc_W{1.data_type}W{2.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpahb.acc{0.widthd_suffix}",
+            "ret": "s32d",
+            "args": ["0", "s16d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpy_V{1.data_type}V{2.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{1.data_type}us{0.widthd_suffix}",
+            "ret": "s(16-32)d",
+            "args": ["0n", "0nu"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpyacc_W{1.data_type}V{2.data_type}V{3.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{2.data_type}us.acc{0.widthd_suffix}",
+            "ret": "s(16-32)d",
+            "args": ["0", "0n", "0nu"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpy_V{1.data_type}V{2.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpybusv{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["u8", "s8"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpyacc_W{1.data_type}V{2.data_type}V{3.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpybusv.acc{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["0", "0nu", "0n"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpy_V{1.data_type}V{2.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{1.data_type}v{0.widthd_suffix}",
+            "ret": "i(16-32)d",
+            "args": ["0n", "0n"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpyacc_W{1.data_type}V{2.data_type}V{3.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{2.data_type}v.acc{0.widthd_suffix}",
+            "ret": "i(16-32)d",
+            "args": ["0", "0n", "0n"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpye_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyewuh{0.width_suffix}",
+            "ret": "s32",
+            "args": ["s32", "u16"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpy_V{1.data_type}R{1.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{1.data_type}{0.widthd_suffix}",
+            "ret": "i32d",
+            "args": ["0n", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpyacc_W{1.data_type}V{2.data_type}R{2.data_type}_sat{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{2.data_type}sat.acc{0.widthd_suffix}",
+            "ret": "s32d",
+            "args": ["0", "0n", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpy_V{1.data_type}R{1.data_type}_s1_rnd_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{1.data_type}srs{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0nd", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpy_V{1.data_type}R{1.data_type}_s1_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{1.data_type}ss{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0nd", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpy_V{1.data_type}V{2.data_type}_s1_rnd_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{1.data_type}vsrs{0.width_suffix}",
+            "ret": "s16",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyieo_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyieo{1.data_type}{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0nd", "0nd"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyieacc_V{1.data_type}V{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyie{2.data_type}{3.data_type}.acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0", "i16"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyie_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyie{1.data_type}{2.data_type}{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "u16"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyi_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyi{1.data_type}{0.width_suffix}",
+            "ret": "s16",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyiacc_V{1.data_type}V{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyi{1.data_type}.acc{0.width_suffix}",
+            "ret": "s16",
+            "args": ["0", "0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyi_V{1.data_type}Rb{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyi{1.data_type}b{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyiacc_V{1.data_type}V{2.data_type}Rb{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyi{1.data_type}b.acc{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyi_V{1.data_type}Rh{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyi{1.data_type}h{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyiacc_V{1.data_type}V{2.data_type}Rh{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyi{1.data_type}h.acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyi_V{1.data_type}Rub{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyi{1.data_type}ub{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyiacc_V{1.data_type}V{2.data_type}Rub{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyi{1.data_type}ub.acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyo_V{1.data_type}V{2.data_type}_s1_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyo{1.data_type}{2.data_type}{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0nd"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyo_V{1.data_type}V{2.data_type}_s1_rnd_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyo{1.data_type}{2.data_type}.rnd{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0nd"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyo_V{1.data_type}V{2.data_type}_s1_rnd_sat_shift{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyo{1.data_type}{2.data_type}.rnd.sacc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0nd"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyo_V{1.data_type}V{2.data_type}_s1_sat_shift{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyo{1.data_type}{2.data_type}.sacc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0nd"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmpyio_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmpyio{1.data_type}{2.data_type}{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "0nd"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpy_V{1.data_type}R{1.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{1.data_type}{0.widthd_suffix}",
+            "ret": "u16d",
+            "args": ["0n", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vmpyacc_W{1.data_type}V{2.data_type}R{2.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vmpy{2.data_type}.acc{0.widthd_suffix}",
+            "ret": "u(16-32)d",
+            "args": ["0", "0n", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vmux_QVV{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vmux{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0hhh", "0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vnavg_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vnavg{0.data_type}{0.width_suffix}",
+            "ret": "i(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vnavg_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vnavg{0.data_type}{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vnormamt_V{1.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vnormamt{0.data_type}{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "V_vnot_VV{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vnot{0.width_suffix}",
+            "ret": "u16",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "V_vor_VV{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vor{0.width_suffix}",
+            "ret": "u16",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vpacke_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vpack{1.data_type}e{0.width_suffix}",
+            "ret": "s(8-16)",
+            "args": ["0hw", "0hw"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vpacko_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vpack{1.data_type}o{0.width_suffix}",
+            "ret": "s(8-16)",
+            "args": ["0hw", "0hw"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vpack_V{1.data_type}V{2.data_type}_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vpack{1.data_type}{0.data_type}.sat{0.width_suffix}",
+            "ret": "i(8-16)",
+            "args": ["0hws", "0hws"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vpopcount_V{1.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vpopcount{0.data_type}{0.width_suffix}",
+            "ret": "s16",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "V_vrdelta_VV{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vrdelta{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vrmpy_V{1.data_type}Rb{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpybus{0.width_suffix}",
+            "ret": "s32",
+            "args": ["u8", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vrmpyacc_V{1.data_type}V{2.data_type}Rb{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpybus.acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "u8", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vrmpy_W{1.data_type}RbI{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpybusi{0.widthd_suffix}",
+            "ret": "s32d",
+            "args": ["u8d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vrmpyacc_W{1.data_type}W{2.data_type}RbI{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpybusi.acc{0.widthd_suffix}",
+            "ret": "s32d",
+            "args": ["0", "u8d", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vrmpy_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpybusv{0.width_suffix}",
+            "ret": "s32",
+            "args": ["u8", "s8"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vrmpyacc_V{1.data_type}V{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpybusv.acc{0.width_suffix}",
+            "ret": "s32",
+            "args": ["0", "u8", "s8"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vrmpy_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpy{1.data_type}v{0.width_suffix}",
+            "ret": "i32",
+            "args": ["0nndd", "0nndd"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vrmpyacc_V{1.data_type}V{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpy{1.data_type}v.acc{0.width_suffix}",
+            "ret": "i32",
+            "args": ["0", "0nndd", "0nndd"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vrmpy_V{1.data_type}Rub{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpyub{0.width_suffix}",
+            "ret": "u32",
+            "args": ["u8", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vrmpyacc_V{1.data_type}V{2.data_type}Rub{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpyub.acc{0.width_suffix}",
+            "ret": "u32",
+            "args": ["0", "u8", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vrmpy_W{1.data_type}RubI{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpyubi{0.widthd_suffix}",
+            "ret": "u32d",
+            "args": ["u8d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vrmpyacc_W{1.data_type}W{2.data_type}RubI{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vrmpyubi.acc{0.widthd_suffix}",
+            "ret": "u32d",
+            "args": ["0", "u8d", "U32"]
+        },
+        {
+            "intrinsic": "V_vror_VR{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vror{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vround_V{1.data_type}V{2.data_type}_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vround{1.data_type}{0.data_type}{0.width_suffix}",
+            "ret": "i(8-16)",
+            "args": ["0hws", "0hws"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vrsad_W{1.data_type}RubI{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vrsadubi{0.widthd_suffix}",
+            "ret": "u32d",
+            "args": ["u8d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vrsadacc_W{1.data_type}W{2.data_type}RubI{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vrsadubi.acc{0.widthd_suffix}",
+            "ret": "u32d",
+            "args": ["0", "u8d", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vsat_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vsat{1.data_type}{0.data_type}{0.width_suffix}",
+            "ret": "u8",
+            "args": ["0hws", "0hws"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vsat_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vsat{1.data_type}{0.data_type}{0.width_suffix}",
+            "ret": "s16",
+            "args": ["0hw", "0hw"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vsxt_V{1.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vs{1.data_type}{0.widthd_suffix}",
+            "ret": "s(16-32)d",
+            "args": ["0n"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vzxt_V{1.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vz{1.data_type_plain}{0.widthd_suffix}",
+            "ret": "u(16-32)d",
+            "args": ["0n"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_condacc_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vadd{0.data_type}q{0.width_suffix}",
+            "ret": "s(8-32)",
+            "args": ["u32hhh", "0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_condacc_QnV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vadd{0.data_type}nq{0.width_suffix}",
+            "ret": "s(8-32)",
+            "args": ["u32hhh", "0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_condnac_QV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vsub{0.data_type}q{0.width_suffix}",
+            "ret": "s(8-32)",
+            "args": ["u32hhh", "0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_condnac_QnV{2.data_type}V{3.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vsub{0.data_type}nq{0.width_suffix}",
+            "ret": "s(8-32)",
+            "args": ["u32hhh", "0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vshuffe_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vshufe{1.data_type}{0.width_suffix}",
+            "ret": "s16",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vshuffo_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vshufo{1.data_type}{0.width_suffix}",
+            "ret": "s16",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vshuff_V{1.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vshuff{1.data_type}{0.width_suffix}",
+            "ret": "s(8-16)",
+            "args": ["0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vshuffe_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vshuffe{1.data_type}{0.width_suffix}",
+            "ret": "s8",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vshuffo_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vshuffo{1.data_type}{0.width_suffix}",
+            "ret": "s8",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vshuffoe_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vshuffoe{1.data_type}{0.width_suffix}",
+            "ret": "s(8-16)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W_vshuff_VVR{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vshufvvd{0.widthd_suffix}",
+            "ret": "u8d",
+            "args": ["0h", "0h", "U32"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vsub_V{1.data_type}V{2.data_type}{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vsub{0.data_type}{0.width_suffix}",
+            "ret": "s(8-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vsub_V{1.data_type}V{2.data_type}_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vsub{0.data_type}sat{0.width_suffix}",
+            "ret": "s(16-32)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "V{0.data_type}_vsub_V{1.data_type}V{2.data_type}_sat{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vsub{0.data_type}sat{0.width_suffix}",
+            "ret": "u(8-16)",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vsub_W{1.data_type}W{2.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vsub{0.data_type}.dv{0.widthd_suffix}",
+            "ret": "s(8-32)d",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vsub_W{1.data_type}W{2.data_type}_sat{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vsub{0.data_type}sat.dv{0.widthd_suffix}",
+            "ret": "s(16-32)d",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vsub_W{1.data_type}W{2.data_type}_sat{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vsub{0.data_type}sat.dv{0.widthd_suffix}",
+            "ret": "u(8-16)d",
+            "args": ["0", "0"]
+        },
+        {
+            "intrinsic": "W_vswap_QVV{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vswap{0.widthd_suffix}",
+            "ret": "u8d",
+            "args": ["u32hhh", "0h", "0h"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vtmpy_W{1.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vtmpyb{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["0nd", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vtmpyacc_W{1.data_type}W{2.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vtmpyb.acc{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["0", "0nd", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vtmpy_W{1.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vtmpybus{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["u8d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vtmpyacc_W{1.data_type}W{2.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vtmpybus.acc{0.widthd_suffix}",
+            "ret": "s16d",
+            "args": ["0", "u8d", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vtmpy_W{1.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vtmpyhb{0.widthd_suffix}",
+            "ret": "s32d",
+            "args": ["0nd", "U32"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vunpack_V{1.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vunpack{1.data_type}{0.widthd_suffix}",
+            "ret": "i(16-32)d",
+            "args": ["0n"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vunpackoor_W{1.data_type}V{2.data_type}{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vunpacko{2.data_type}{0.widthd_suffix}",
+            "ret": "s(16-32)d",
+            "args": ["0", "0n"]
+        },
+        {
+            "intrinsic": "W{0.data_type}_vtmpyacc_W{1.data_type}W{2.data_type}Rb{0.widthd_b}",
+            "width": [512, 1024],
+            "llvm": "vtmpyhb.acc{0.widthd_suffix}",
+            "ret": "s32d",
+            "args": ["0", "0nd", "U32"]
+        },
+        {
+            "intrinsic": "V_vxor_VV{0.width_b}",
+            "width": [512, 1024],
+            "llvm": "vxor{0.width_suffix}",
+            "ret": "u16",
+            "args": ["0", "0"]
+        }
+    ]
+}
diff --git a/src/grammar/.gitignore b/src/grammar/.gitignore
new file mode 100644
index 00000000000..3e449875943
--- /dev/null
+++ b/src/grammar/.gitignore
@@ -0,0 +1,3 @@
+*.class
+*.java
+*.tokens
diff --git a/src/grammar/lexer.l b/src/grammar/lexer.l
new file mode 100644
index 00000000000..77737c99496
--- /dev/null
+++ b/src/grammar/lexer.l
@@ -0,0 +1,343 @@
+%{
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#include <stdio.h>
+#include <ctype.h>
+
+static int num_hashes;
+static int end_hashes;
+static int saw_non_hash;
+
+%}
+
+%option stack
+%option yylineno
+
+%x str
+%x rawstr
+%x rawstr_esc_begin
+%x rawstr_esc_body
+%x rawstr_esc_end
+%x byte
+%x bytestr
+%x rawbytestr
+%x rawbytestr_nohash
+%x pound
+%x shebang_or_attr
+%x ltorchar
+%x linecomment
+%x doc_line
+%x blockcomment
+%x doc_block
+%x suffix
+
+ident [a-zA-Z\x80-\xff_][a-zA-Z0-9\x80-\xff_]*
+
+%%
+
+<suffix>{ident}            { BEGIN(INITIAL); }
+<suffix>(.|\n)  { yyless(0); BEGIN(INITIAL); }
+
+[ \n\t\r]             { }
+
+\xef\xbb\xbf {
+  // UTF-8 byte order mark (BOM), ignore if in line 1, error otherwise
+  if (yyget_lineno() != 1) {
+    return -1;
+  }
+}
+
+\/\/(\/|\!)           { BEGIN(doc_line); yymore(); }
+<doc_line>\n          { BEGIN(INITIAL);
+                        yyleng--;
+                        yytext[yyleng] = 0;
+                        return ((yytext[2] == '!') ? INNER_DOC_COMMENT : OUTER_DOC_COMMENT);
+                      }
+<doc_line>[^\n]*      { yymore(); }
+
+\/\/|\/\/\/\/         { BEGIN(linecomment); }
+<linecomment>\n       { BEGIN(INITIAL); }
+<linecomment>[^\n]*   { }
+
+\/\*(\*|\!)[^*]       { yy_push_state(INITIAL); yy_push_state(doc_block); yymore(); }
+<doc_block>\/\*       { yy_push_state(doc_block); yymore(); }
+<doc_block>\*\/       {
+    yy_pop_state();
+    if (yy_top_state() == doc_block) {
+        yymore();
+    } else {
+        return ((yytext[2] == '!') ? INNER_DOC_COMMENT : OUTER_DOC_COMMENT);
+    }
+}
+<doc_block>(.|\n)     { yymore(); }
+
+\/\*                  { yy_push_state(blockcomment); }
+<blockcomment>\/\*    { yy_push_state(blockcomment); }
+<blockcomment>\*\/    { yy_pop_state(); }
+<blockcomment>(.|\n)   { }
+
+_        { return UNDERSCORE; }
+as       { return AS; }
+box      { return BOX; }
+break    { return BREAK; }
+const    { return CONST; }
+continue { return CONTINUE; }
+crate    { return CRATE; }
+else     { return ELSE; }
+enum     { return ENUM; }
+extern   { return EXTERN; }
+false    { return FALSE; }
+fn       { return FN; }
+for      { return FOR; }
+if       { return IF; }
+impl     { return IMPL; }
+in       { return IN; }
+let      { return LET; }
+loop     { return LOOP; }
+match    { return MATCH; }
+mod      { return MOD; }
+move     { return MOVE; }
+mut      { return MUT; }
+priv     { return PRIV; }
+proc     { return PROC; }
+pub      { return PUB; }
+ref      { return REF; }
+return   { return RETURN; }
+self     { return SELF; }
+static   { return STATIC; }
+struct   { return STRUCT; }
+trait    { return TRAIT; }
+true     { return TRUE; }
+type     { return TYPE; }
+typeof   { return TYPEOF; }
+unsafe   { return UNSAFE; }
+use      { return USE; }
+where    { return WHERE; }
+while    { return WHILE; }
+
+{ident}  { return IDENT; }
+
+0x[0-9a-fA-F_]+                                    { BEGIN(suffix); return LIT_INTEGER; }
+0o[0-8_]+                                          { BEGIN(suffix); return LIT_INTEGER; }
+0b[01_]+                                           { BEGIN(suffix); return LIT_INTEGER; }
+[0-9][0-9_]*                                       { BEGIN(suffix); return LIT_INTEGER; }
+[0-9][0-9_]*\.(\.|[a-zA-Z])    { yyless(yyleng - 2); BEGIN(suffix); return LIT_INTEGER; }
+
+[0-9][0-9_]*\.[0-9_]*([eE][-\+]?[0-9_]+)?          { BEGIN(suffix); return LIT_FLOAT; }
+[0-9][0-9_]*(\.[0-9_]*)?[eE][-\+]?[0-9_]+          { BEGIN(suffix); return LIT_FLOAT; }
+
+;      { return ';'; }
+,      { return ','; }
+\.\.\. { return DOTDOTDOT; }
+\.\.   { return DOTDOT; }
+\.     { return '.'; }
+\(     { return '('; }
+\)     { return ')'; }
+\{     { return '{'; }
+\}     { return '}'; }
+\[     { return '['; }
+\]     { return ']'; }
+@      { return '@'; }
+#      { BEGIN(pound); yymore(); }
+<pound>\! { BEGIN(shebang_or_attr); yymore(); }
+<shebang_or_attr>\[ {
+  BEGIN(INITIAL);
+  yyless(2);
+  return SHEBANG;
+}
+<shebang_or_attr>[^\[\n]*\n {
+  // Since the \n was eaten as part of the token, yylineno will have
+  // been incremented to the value 2 if the shebang was on the first
+  // line. This yyless undoes that, setting yylineno back to 1.
+  yyless(yyleng - 1);
+  if (yyget_lineno() == 1) {
+    BEGIN(INITIAL);
+    return SHEBANG_LINE;
+  } else {
+    BEGIN(INITIAL);
+    yyless(2);
+    return SHEBANG;
+  }
+}
+<pound>. { BEGIN(INITIAL); yyless(1); return '#'; }
+
+\~     { return '~'; }
+::     { return MOD_SEP; }
+:      { return ':'; }
+\$     { return '$'; }
+\?     { return '?'; }
+
+==    { return EQEQ; }
+=>    { return FAT_ARROW; }
+=     { return '='; }
+\!=   { return NE; }
+\!    { return '!'; }
+\<=   { return LE; }
+\<\<  { return SHL; }
+\<\<= { return SHLEQ; }
+\<    { return '<'; }
+\>=   { return GE; }
+\>\>  { return SHR; }
+\>\>= { return SHREQ; }
+\>    { return '>'; }
+
+\x27                                  { BEGIN(ltorchar); yymore(); }
+<ltorchar>static                      { BEGIN(INITIAL); return STATIC_LIFETIME; }
+<ltorchar>{ident}                     { BEGIN(INITIAL); return LIFETIME; }
+<ltorchar>\\[nrt\\\x27\x220]\x27      { BEGIN(suffix); return LIT_CHAR; }
+<ltorchar>\\x[0-9a-fA-F]{2}\x27       { BEGIN(suffix); return LIT_CHAR; }
+<ltorchar>\\u\{[0-9a-fA-F]?{6}\}\x27  { BEGIN(suffix); return LIT_CHAR; }
+<ltorchar>.\x27                       { BEGIN(suffix); return LIT_CHAR; }
+<ltorchar>[\x80-\xff]{2,4}\x27        { BEGIN(suffix); return LIT_CHAR; }
+<ltorchar><<EOF>>                     { BEGIN(INITIAL); return -1; }
+
+b\x22              { BEGIN(bytestr); yymore(); }
+<bytestr>\x22      { BEGIN(suffix); return LIT_BYTE_STR; }
+
+<bytestr><<EOF>>                { return -1; }
+<bytestr>\\[n\nrt\\\x27\x220]   { yymore(); }
+<bytestr>\\x[0-9a-fA-F]{2}      { yymore(); }
+<bytestr>\\u\{[0-9a-fA-F]?{6}\} { yymore(); }
+<bytestr>\\[^n\nrt\\\x27\x220]  { return -1; }
+<bytestr>(.|\n)                 { yymore(); }
+
+br\x22                      { BEGIN(rawbytestr_nohash); yymore(); }
+<rawbytestr_nohash>\x22     { BEGIN(suffix); return LIT_BYTE_STR_RAW; }
+<rawbytestr_nohash>(.|\n)   { yymore(); }
+<rawbytestr_nohash><<EOF>>  { return -1; }
+
+br/# {
+    BEGIN(rawbytestr);
+    yymore();
+    num_hashes = 0;
+    saw_non_hash = 0;
+    end_hashes = 0;
+}
+<rawbytestr># {
+    if (!saw_non_hash) {
+        num_hashes++;
+    } else if (end_hashes != 0) {
+        end_hashes++;
+        if (end_hashes == num_hashes) {
+            BEGIN(INITIAL);
+            return LIT_BYTE_STR_RAW;
+        }
+    }
+    yymore();
+}
+<rawbytestr>\x22# {
+    end_hashes = 1;
+    if (end_hashes == num_hashes) {
+        BEGIN(INITIAL);
+        return LIT_BYTE_STR_RAW;
+    }
+    yymore();
+}
+<rawbytestr>(.|\n) {
+    if (!saw_non_hash) {
+        saw_non_hash = 1;
+    }
+    if (end_hashes != 0) {
+        end_hashes = 0;
+    }
+    yymore();
+}
+<rawbytestr><<EOF>> { return -1; }
+
+b\x27                        { BEGIN(byte); yymore(); }
+<byte>\\[nrt\\\x27\x220]\x27 { BEGIN(INITIAL); return LIT_BYTE; }
+<byte>\\x[0-9a-fA-F]{2}\x27  { BEGIN(INITIAL); return LIT_BYTE; }
+<byte>\\u[0-9a-fA-F]{4}\x27  { BEGIN(INITIAL); return LIT_BYTE; }
+<byte>\\U[0-9a-fA-F]{8}\x27  { BEGIN(INITIAL); return LIT_BYTE; }
+<byte>.\x27                  { BEGIN(INITIAL); return LIT_BYTE; }
+<byte><<EOF>>                { BEGIN(INITIAL); return -1; }
+
+r\x22           { BEGIN(rawstr); yymore(); }
+<rawstr>\x22    { BEGIN(suffix); return LIT_STR_RAW; }
+<rawstr>(.|\n)  { yymore(); }
+<rawstr><<EOF>> { return -1; }
+
+r/#             {
+    BEGIN(rawstr_esc_begin);
+    yymore();
+    num_hashes = 0;
+    saw_non_hash = 0;
+    end_hashes = 0;
+}
+
+<rawstr_esc_begin># {
+    num_hashes++;
+    yymore();
+}
+<rawstr_esc_begin>\x22 {
+    BEGIN(rawstr_esc_body);
+    yymore();
+}
+<rawstr_esc_begin>(.|\n) { return -1; }
+
+<rawstr_esc_body>\x22/# {
+  BEGIN(rawstr_esc_end);
+  yymore();
+ }
+<rawstr_esc_body>(.|\n) {
+  yymore();
+ }
+
+<rawstr_esc_end># {
+  end_hashes++;
+  if (end_hashes == num_hashes) {
+    BEGIN(INITIAL);
+    return LIT_STR_RAW;
+  }
+  yymore();
+ }
+<rawstr_esc_end>[^#] {
+  end_hashes = 0;
+  BEGIN(rawstr_esc_body);
+  yymore();
+ }
+
+<rawstr_esc_begin,rawstr_esc_body,rawstr_esc_end><<EOF>> { return -1; }
+
+\x22                     { BEGIN(str); yymore(); }
+<str>\x22                { BEGIN(suffix); return LIT_STR; }
+
+<str><<EOF>>                { return -1; }
+<str>\\[n\nr\rt\\\x27\x220] { yymore(); }
+<str>\\x[0-9a-fA-F]{2}      { yymore(); }
+<str>\\u\{[0-9a-fA-F]?{6}\} { yymore(); }
+<str>\\[^n\nrt\\\x27\x220]  { return -1; }
+<str>(.|\n)                 { yymore(); }
+
+\<-  { return LARROW; }
+-\>  { return RARROW; }
+-    { return '-'; }
+-=   { return MINUSEQ; }
+&&   { return ANDAND; }
+&    { return '&'; }
+&=   { return ANDEQ; }
+\|\| { return OROR; }
+\|   { return '|'; }
+\|=  { return OREQ; }
+\+   { return '+'; }
+\+=  { return PLUSEQ; }
+\*   { return '*'; }
+\*=  { return STAREQ; }
+\/   { return '/'; }
+\/=  { return SLASHEQ; }
+\^   { return '^'; }
+\^=  { return CARETEQ; }
+%    { return '%'; }
+%=   { return PERCENTEQ; }
+
+<<EOF>> { return 0; }
+
+%%
diff --git a/src/grammar/parser-lalr-main.c b/src/grammar/parser-lalr-main.c
new file mode 100644
index 00000000000..db88a1f2999
--- /dev/null
+++ b/src/grammar/parser-lalr-main.c
@@ -0,0 +1,203 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+
+extern int yylex();
+extern int rsparse();
+
+#define PUSHBACK_LEN 4
+
+static char pushback[PUSHBACK_LEN];
+static int verbose;
+
+void print(const char* format, ...) {
+  va_list args;
+  va_start(args, format);
+  if (verbose) {
+    vprintf(format, args);
+  }
+  va_end(args);
+}
+
+// If there is a non-null char at the head of the pushback queue,
+// dequeue it and shift the rest of the queue forwards. Otherwise,
+// return the token from calling yylex.
+int rslex() {
+  if (pushback[0] == '\0') {
+    return yylex();
+  } else {
+    char c = pushback[0];
+    memmove(pushback, pushback + 1, PUSHBACK_LEN - 1);
+    pushback[PUSHBACK_LEN - 1] = '\0';
+    return c;
+  }
+}
+
+// Note: this does nothing if the pushback queue is full. As long as
+// there aren't more than PUSHBACK_LEN consecutive calls to push_back
+// in an action, this shouldn't be a problem.
+void push_back(char c) {
+  for (int i = 0; i < PUSHBACK_LEN; ++i) {
+    if (pushback[i] == '\0') {
+      pushback[i] = c;
+      break;
+    }
+  }
+}
+
+extern int rsdebug;
+
+struct node {
+  struct node *next;
+  struct node *prev;
+  int own_string;
+  char const *name;
+  int n_elems;
+  struct node *elems[];
+};
+
+struct node *nodes = NULL;
+int n_nodes;
+
+struct node *mk_node(char const *name, int n, ...) {
+  va_list ap;
+  int i = 0;
+  unsigned sz = sizeof(struct node) + (n * sizeof(struct node *));
+  struct node *nn, *nd = (struct node *)malloc(sz);
+
+  print("# New %d-ary node: %s = %p\n", n, name, nd);
+
+  nd->own_string = 0;
+  nd->prev = NULL;
+  nd->next = nodes;
+  if (nodes) {
+    nodes->prev = nd;
+  }
+  nodes = nd;
+
+  nd->name = name;
+  nd->n_elems = n;
+
+  va_start(ap, n);
+  while (i < n) {
+    nn = va_arg(ap, struct node *);
+    print("#   arg[%d]: %p\n", i, nn);
+    print("#            (%s ...)\n", nn->name);
+    nd->elems[i++] = nn;
+  }
+  va_end(ap);
+  n_nodes++;
+  return nd;
+}
+
+struct node *mk_atom(char *name) {
+  struct node *nd = mk_node((char const *)strdup(name), 0);
+  nd->own_string = 1;
+  return nd;
+}
+
+struct node *mk_none() {
+  return mk_atom("<none>");
+}
+
+struct node *ext_node(struct node *nd, int n, ...) {
+  va_list ap;
+  int i = 0, c = nd->n_elems + n;
+  unsigned sz = sizeof(struct node) + (c * sizeof(struct node *));
+  struct node *nn;
+
+  print("# Extending %d-ary node by %d nodes: %s = %p",
+        nd->n_elems, c, nd->name, nd);
+
+  if (nd->next) {
+    nd->next->prev = nd->prev;
+  }
+  if (nd->prev) {
+    nd->prev->next = nd->next;
+  }
+  nd = realloc(nd, sz);
+  nd->prev = NULL;
+  nd->next = nodes;
+  nodes->prev = nd;
+  nodes = nd;
+
+  print(" ==> %p\n", nd);
+
+  va_start(ap, n);
+  while (i < n) {
+    nn = va_arg(ap, struct node *);
+    print("#   arg[%d]: %p\n", i, nn);
+    print("#            (%s ...)\n", nn->name);
+    nd->elems[nd->n_elems++] = nn;
+    ++i;
+  }
+  va_end(ap);
+  return nd;
+}
+
+int const indent_step = 4;
+
+void print_indent(int depth) {
+  while (depth) {
+    if (depth-- % indent_step == 0) {
+      print("|");
+    } else {
+      print(" ");
+    }
+  }
+}
+
+void print_node(struct node *n, int depth) {
+  int i = 0;
+  print_indent(depth);
+  if (n->n_elems == 0) {
+    print("%s\n", n->name);
+  } else {
+    print("(%s\n", n->name);
+    for (i = 0; i < n->n_elems; ++i) {
+      print_node(n->elems[i], depth + indent_step);
+    }
+    print_indent(depth);
+    print(")\n");
+  }
+}
+
+int main(int argc, char **argv) {
+  if (argc == 2 && strcmp(argv[1], "-v") == 0) {
+    verbose = 1;
+  } else {
+    verbose = 0;
+  }
+  int ret = 0;
+  struct node *tmp;
+  memset(pushback, '\0', PUSHBACK_LEN);
+  ret = rsparse();
+  print("--- PARSE COMPLETE: ret:%d, n_nodes:%d ---\n", ret, n_nodes);
+  if (nodes) {
+    print_node(nodes, 0);
+  }
+  while (nodes) {
+    tmp = nodes;
+    nodes = tmp->next;
+    if (tmp->own_string) {
+      free((void*)tmp->name);
+    }
+    free(tmp);
+  }
+  return ret;
+}
+
+void rserror(char const *s) {
+  fprintf(stderr, "%s\n", s);
+}
diff --git a/src/grammar/parser-lalr.y b/src/grammar/parser-lalr.y
new file mode 100644
index 00000000000..c9fcdf7647b
--- /dev/null
+++ b/src/grammar/parser-lalr.y
@@ -0,0 +1,1945 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+%{
+#define YYERROR_VERBOSE
+#define YYSTYPE struct node *
+struct node;
+extern int yylex();
+extern void yyerror(char const *s);
+extern struct node *mk_node(char const *name, int n, ...);
+extern struct node *mk_atom(char *text);
+extern struct node *mk_none();
+extern struct node *ext_node(struct node *nd, int n, ...);
+extern void push_back(char c);
+extern char *yytext;
+%}
+%debug
+
+%token SHL
+%token SHR
+%token LE
+%token EQEQ
+%token NE
+%token GE
+%token ANDAND
+%token OROR
+%token SHLEQ
+%token SHREQ
+%token MINUSEQ
+%token ANDEQ
+%token OREQ
+%token PLUSEQ
+%token STAREQ
+%token SLASHEQ
+%token CARETEQ
+%token PERCENTEQ
+%token DOTDOT
+%token DOTDOTDOT
+%token MOD_SEP
+%token RARROW
+%token LARROW
+%token FAT_ARROW
+%token LIT_BYTE
+%token LIT_CHAR
+%token LIT_INTEGER
+%token LIT_FLOAT
+%token LIT_STR
+%token LIT_STR_RAW
+%token LIT_BYTE_STR
+%token LIT_BYTE_STR_RAW
+%token IDENT
+%token UNDERSCORE
+%token LIFETIME
+
+// keywords
+%token SELF
+%token STATIC
+%token AS
+%token BREAK
+%token CRATE
+%token ELSE
+%token ENUM
+%token EXTERN
+%token FALSE
+%token FN
+%token FOR
+%token IF
+%token IMPL
+%token IN
+%token LET
+%token LOOP
+%token MATCH
+%token MOD
+%token MOVE
+%token MUT
+%token PRIV
+%token PUB
+%token REF
+%token RETURN
+%token STRUCT
+%token TRUE
+%token TRAIT
+%token TYPE
+%token UNSAFE
+%token DEFAULT
+%token USE
+%token WHILE
+%token CONTINUE
+%token PROC
+%token BOX
+%token CONST
+%token WHERE
+%token TYPEOF
+%token INNER_DOC_COMMENT
+%token OUTER_DOC_COMMENT
+
+%token SHEBANG
+%token SHEBANG_LINE
+%token STATIC_LIFETIME
+
+ /*
+   Quoting from the Bison manual:
+
+   "Finally, the resolution of conflicts works by comparing the precedence
+   of the rule being considered with that of the lookahead token. If the
+   token's precedence is higher, the choice is to shift. If the rule's
+   precedence is higher, the choice is to reduce. If they have equal
+   precedence, the choice is made based on the associativity of that
+   precedence level. The verbose output file made by ‘-v’ (see Invoking
+   Bison) says how each conflict was resolved"
+ */
+
+// We expect no shift/reduce or reduce/reduce conflicts in this grammar;
+// all potential ambiguities are scrutinized and eliminated manually.
+%expect 0
+
+// fake-precedence symbol to cause '|' bars in lambda context to parse
+// at low precedence, permit things like |x| foo = bar, where '=' is
+// otherwise lower-precedence than '|'. Also used for proc() to cause
+// things like proc() a + b to parse as proc() { a + b }.
+%precedence LAMBDA
+
+%precedence SELF
+
+// MUT should be lower precedence than IDENT so that in the pat rule,
+// "& MUT pat" has higher precedence than "binding_mode ident [@ pat]"
+%precedence MUT
+
+// IDENT needs to be lower than '{' so that 'foo {' is shifted when
+// trying to decide if we've got a struct-construction expr (esp. in
+// contexts like 'if foo { .')
+//
+// IDENT also needs to be lower precedence than '<' so that '<' in
+// 'foo:bar . <' is shifted (in a trait reference occurring in a
+// bounds list), parsing as foo:(bar<baz>) rather than (foo:bar)<baz>.
+%precedence IDENT
+
+// A couple fake-precedence symbols to use in rules associated with +
+// and < in trailing type contexts. These come up when you have a type
+// in the RHS of operator-AS, such as "foo as bar<baz>". The "<" there
+// has to be shifted so the parser keeps trying to parse a type, even
+// though it might well consider reducing the type "bar" and then
+// going on to "<" as a subsequent binop. The "+" case is with
+// trailing type-bounds ("foo as bar:A+B"), for the same reason.
+%precedence SHIFTPLUS
+
+%precedence MOD_SEP
+%precedence RARROW ':'
+
+// In where clauses, "for" should have greater precedence when used as
+// a higher ranked constraint than when used as the beginning of a
+// for_in_type (which is a ty)
+%precedence FORTYPE
+%precedence FOR
+
+// Binops & unops, and their precedences
+%precedence BOX
+%precedence BOXPLACE
+%nonassoc DOTDOT
+
+// RETURN needs to be lower-precedence than tokens that start
+// prefix_exprs
+%precedence RETURN
+
+%right '=' SHLEQ SHREQ MINUSEQ ANDEQ OREQ PLUSEQ STAREQ SLASHEQ CARETEQ PERCENTEQ
+%right LARROW
+%left OROR
+%left ANDAND
+%left EQEQ NE
+%left '<' '>' LE GE
+%left '|'
+%left '^'
+%left '&'
+%left SHL SHR
+%left '+' '-'
+%precedence AS
+%left '*' '/' '%'
+%precedence '!'
+
+%precedence '{' '[' '(' '.'
+
+%precedence RANGE
+
+%start crate
+
+%%
+
+////////////////////////////////////////////////////////////////////////
+// Part 1: Items and attributes
+////////////////////////////////////////////////////////////////////////
+
+crate
+: maybe_shebang inner_attrs maybe_mod_items  { mk_node("crate", 2, $2, $3); }
+| maybe_shebang maybe_mod_items  { mk_node("crate", 1, $2); }
+;
+
+maybe_shebang
+: SHEBANG_LINE
+| %empty
+;
+
+maybe_inner_attrs
+: inner_attrs
+| %empty                   { $$ = mk_none(); }
+;
+
+inner_attrs
+: inner_attr               { $$ = mk_node("InnerAttrs", 1, $1); }
+| inner_attrs inner_attr   { $$ = ext_node($1, 1, $2); }
+;
+
+inner_attr
+: SHEBANG '[' meta_item ']'   { $$ = mk_node("InnerAttr", 1, $3); }
+| INNER_DOC_COMMENT           { $$ = mk_node("InnerAttr", 1, mk_node("doc-comment", 1, mk_atom(yytext))); }
+;
+
+maybe_outer_attrs
+: outer_attrs
+| %empty                   { $$ = mk_none(); }
+;
+
+outer_attrs
+: outer_attr               { $$ = mk_node("OuterAttrs", 1, $1); }
+| outer_attrs outer_attr   { $$ = ext_node($1, 1, $2); }
+;
+
+outer_attr
+: '#' '[' meta_item ']'    { $$ = $3; }
+| OUTER_DOC_COMMENT        { $$ = mk_node("doc-comment", 1, mk_atom(yytext)); }
+;
+
+meta_item
+: ident                      { $$ = mk_node("MetaWord", 1, $1); }
+| ident '=' lit              { $$ = mk_node("MetaNameValue", 2, $1, $3); }
+| ident '(' meta_seq ')'     { $$ = mk_node("MetaList", 2, $1, $3); }
+| ident '(' meta_seq ',' ')' { $$ = mk_node("MetaList", 2, $1, $3); }
+;
+
+meta_seq
+: %empty                   { $$ = mk_none(); }
+| meta_item                { $$ = mk_node("MetaItems", 1, $1); }
+| meta_seq ',' meta_item   { $$ = ext_node($1, 1, $3); }
+;
+
+maybe_mod_items
+: mod_items
+| %empty             { $$ = mk_none(); }
+;
+
+mod_items
+: mod_item                               { $$ = mk_node("Items", 1, $1); }
+| mod_items mod_item                     { $$ = ext_node($1, 1, $2); }
+;
+
+attrs_and_vis
+: maybe_outer_attrs visibility           { $$ = mk_node("AttrsAndVis", 2, $1, $2); }
+;
+
+mod_item
+: attrs_and_vis item    { $$ = mk_node("Item", 2, $1, $2); }
+;
+
+// items that can appear outside of a fn block
+item
+: stmt_item
+| item_macro
+;
+
+// items that can appear in "stmts"
+stmt_item
+: item_static
+| item_const
+| item_type
+| block_item
+| view_item
+;
+
+item_static
+: STATIC ident ':' ty '=' expr ';'  { $$ = mk_node("ItemStatic", 3, $2, $4, $6); }
+| STATIC MUT ident ':' ty '=' expr ';'  { $$ = mk_node("ItemStatic", 3, $3, $5, $7); }
+;
+
+item_const
+: CONST ident ':' ty '=' expr ';'  { $$ = mk_node("ItemConst", 3, $2, $4, $6); }
+;
+
+item_macro
+: path_expr '!' maybe_ident parens_delimited_token_trees ';'  { $$ = mk_node("ItemMacro", 3, $1, $3, $4); }
+| path_expr '!' maybe_ident braces_delimited_token_trees      { $$ = mk_node("ItemMacro", 3, $1, $3, $4); }
+| path_expr '!' maybe_ident brackets_delimited_token_trees ';'{ $$ = mk_node("ItemMacro", 3, $1, $3, $4); }
+;
+
+view_item
+: use_item
+| extern_fn_item
+| EXTERN CRATE ident ';'                      { $$ = mk_node("ViewItemExternCrate", 1, $3); }
+| EXTERN CRATE ident AS ident ';'             { $$ = mk_node("ViewItemExternCrate", 2, $3, $5); }
+;
+
+extern_fn_item
+: EXTERN maybe_abi item_fn                    { $$ = mk_node("ViewItemExternFn", 2, $2, $3); }
+;
+
+use_item
+: USE view_path ';'                           { $$ = mk_node("ViewItemUse", 1, $2); }
+;
+
+view_path
+: path_no_types_allowed                                    { $$ = mk_node("ViewPathSimple", 1, $1); }
+| path_no_types_allowed MOD_SEP '{'                '}'     { $$ = mk_node("ViewPathList", 2, $1, mk_atom("ViewPathListEmpty")); }
+|                       MOD_SEP '{'                '}'     { $$ = mk_node("ViewPathList", 1, mk_atom("ViewPathListEmpty")); }
+| path_no_types_allowed MOD_SEP '{' idents_or_self '}'     { $$ = mk_node("ViewPathList", 2, $1, $4); }
+|                       MOD_SEP '{' idents_or_self '}'     { $$ = mk_node("ViewPathList", 1, $3); }
+| path_no_types_allowed MOD_SEP '{' idents_or_self ',' '}' { $$ = mk_node("ViewPathList", 2, $1, $4); }
+|                       MOD_SEP '{' idents_or_self ',' '}' { $$ = mk_node("ViewPathList", 1, $3); }
+| path_no_types_allowed MOD_SEP '*'                        { $$ = mk_node("ViewPathGlob", 1, $1); }
+|                               '{'                '}'     { $$ = mk_atom("ViewPathListEmpty"); }
+|                               '{' idents_or_self '}'     { $$ = mk_node("ViewPathList", 1, $2); }
+|                               '{' idents_or_self ',' '}' { $$ = mk_node("ViewPathList", 1, $2); }
+| path_no_types_allowed AS ident                           { $$ = mk_node("ViewPathSimple", 2, $1, $3); }
+;
+
+block_item
+: item_fn
+| item_unsafe_fn
+| item_mod
+| item_foreign_mod          { $$ = mk_node("ItemForeignMod", 1, $1); }
+| item_struct
+| item_enum
+| item_trait
+| item_impl
+;
+
+maybe_ty_ascription
+: ':' ty_sum { $$ = $2; }
+| %empty { $$ = mk_none(); }
+;
+
+maybe_init_expr
+: '=' expr { $$ = $2; }
+| %empty   { $$ = mk_none(); }
+;
+
+// structs
+item_struct
+: STRUCT ident generic_params maybe_where_clause struct_decl_args
+{
+  $$ = mk_node("ItemStruct", 4, $2, $3, $4, $5);
+}
+| STRUCT ident generic_params struct_tuple_args maybe_where_clause ';'
+{
+  $$ = mk_node("ItemStruct", 4, $2, $3, $4, $5);
+}
+| STRUCT ident generic_params maybe_where_clause ';'
+{
+  $$ = mk_node("ItemStruct", 3, $2, $3, $4);
+}
+;
+
+struct_decl_args
+: '{' struct_decl_fields '}'                  { $$ = $2; }
+| '{' struct_decl_fields ',' '}'              { $$ = $2; }
+;
+
+struct_tuple_args
+: '(' struct_tuple_fields ')'                 { $$ = $2; }
+| '(' struct_tuple_fields ',' ')'             { $$ = $2; }
+;
+
+struct_decl_fields
+: struct_decl_field                           { $$ = mk_node("StructFields", 1, $1); }
+| struct_decl_fields ',' struct_decl_field    { $$ = ext_node($1, 1, $3); }
+| %empty                                      { $$ = mk_none(); }
+;
+
+struct_decl_field
+: attrs_and_vis ident ':' ty_sum              { $$ = mk_node("StructField", 3, $1, $2, $4); }
+;
+
+struct_tuple_fields
+: struct_tuple_field                          { $$ = mk_node("StructFields", 1, $1); }
+| struct_tuple_fields ',' struct_tuple_field  { $$ = ext_node($1, 1, $3); }
+;
+
+struct_tuple_field
+: attrs_and_vis ty_sum                    { $$ = mk_node("StructField", 2, $1, $2); }
+;
+
+// enums
+item_enum
+: ENUM ident generic_params maybe_where_clause '{' enum_defs '}'     { $$ = mk_node("ItemEnum", 0); }
+| ENUM ident generic_params maybe_where_clause '{' enum_defs ',' '}' { $$ = mk_node("ItemEnum", 0); }
+;
+
+enum_defs
+: enum_def               { $$ = mk_node("EnumDefs", 1, $1); }
+| enum_defs ',' enum_def { $$ = ext_node($1, 1, $3); }
+| %empty                 { $$ = mk_none(); }
+;
+
+enum_def
+: attrs_and_vis ident enum_args { $$ = mk_node("EnumDef", 3, $1, $2, $3); }
+;
+
+enum_args
+: '{' struct_decl_fields '}'     { $$ = mk_node("EnumArgs", 1, $2); }
+| '{' struct_decl_fields ',' '}' { $$ = mk_node("EnumArgs", 1, $2); }
+| '(' maybe_ty_sums ')'          { $$ = mk_node("EnumArgs", 1, $2); }
+| '=' expr                       { $$ = mk_node("EnumArgs", 1, $2); }
+| %empty                         { $$ = mk_none(); }
+;
+
+item_mod
+: MOD ident ';'                                 { $$ = mk_node("ItemMod", 1, $2); }
+| MOD ident '{' maybe_mod_items '}'             { $$ = mk_node("ItemMod", 2, $2, $4); }
+| MOD ident '{' inner_attrs maybe_mod_items '}' { $$ = mk_node("ItemMod", 3, $2, $4, $5); }
+;
+
+item_foreign_mod
+: EXTERN maybe_abi '{' maybe_foreign_items '}'             { $$ = mk_node("ItemForeignMod", 1, $4); }
+| EXTERN maybe_abi '{' inner_attrs maybe_foreign_items '}' { $$ = mk_node("ItemForeignMod", 2, $4, $5); }
+;
+
+maybe_abi
+: str
+| %empty { $$ = mk_none(); }
+;
+
+maybe_foreign_items
+: foreign_items
+| %empty { $$ = mk_none(); }
+;
+
+foreign_items
+: foreign_item               { $$ = mk_node("ForeignItems", 1, $1); }
+| foreign_items foreign_item { $$ = ext_node($1, 1, $2); }
+;
+
+foreign_item
+: attrs_and_vis STATIC item_foreign_static { $$ = mk_node("ForeignItem", 2, $1, $3); }
+| attrs_and_vis item_foreign_fn            { $$ = mk_node("ForeignItem", 2, $1, $2); }
+| attrs_and_vis UNSAFE item_foreign_fn     { $$ = mk_node("ForeignItem", 2, $1, $3); }
+;
+
+item_foreign_static
+: maybe_mut ident ':' ty ';'               { $$ = mk_node("StaticItem", 3, $1, $2, $4); }
+;
+
+item_foreign_fn
+: FN ident generic_params fn_decl_allow_variadic maybe_where_clause ';' { $$ = mk_node("ForeignFn", 4, $2, $3, $4, $5); }
+;
+
+fn_decl_allow_variadic
+: fn_params_allow_variadic ret_ty { $$ = mk_node("FnDecl", 2, $1, $2); }
+;
+
+fn_params_allow_variadic
+: '(' ')'                      { $$ = mk_none(); }
+| '(' params ')'               { $$ = $2; }
+| '(' params ',' ')'           { $$ = $2; }
+| '(' params ',' DOTDOTDOT ')' { $$ = $2; }
+;
+
+visibility
+: PUB      { $$ = mk_atom("Public"); }
+| %empty   { $$ = mk_atom("Inherited"); }
+;
+
+idents_or_self
+: ident_or_self                    { $$ = mk_node("IdentsOrSelf", 1, $1); }
+| ident_or_self AS ident           { $$ = mk_node("IdentsOrSelf", 2, $1, $3); }
+| idents_or_self ',' ident_or_self { $$ = ext_node($1, 1, $3); }
+;
+
+ident_or_self
+: ident
+| SELF  { $$ = mk_atom(yytext); }
+;
+
+item_type
+: TYPE ident generic_params maybe_where_clause '=' ty_sum ';'  { $$ = mk_node("ItemTy", 4, $2, $3, $4, $6); }
+;
+
+for_sized
+: FOR '?' ident { $$ = mk_node("ForSized", 1, $3); }
+| FOR ident '?' { $$ = mk_node("ForSized", 1, $2); }
+| %empty        { $$ = mk_none(); }
+;
+
+item_trait
+: maybe_unsafe TRAIT ident generic_params for_sized maybe_ty_param_bounds maybe_where_clause '{' maybe_trait_items '}'
+{
+  $$ = mk_node("ItemTrait", 7, $1, $3, $4, $5, $6, $7, $9);
+}
+;
+
+maybe_trait_items
+: trait_items
+| %empty { $$ = mk_none(); }
+;
+
+trait_items
+: trait_item               { $$ = mk_node("TraitItems", 1, $1); }
+| trait_items trait_item   { $$ = ext_node($1, 1, $2); }
+;
+
+trait_item
+: trait_const
+| trait_type
+| trait_method
+;
+
+trait_const
+: maybe_outer_attrs CONST ident maybe_ty_ascription maybe_const_default ';' { $$ = mk_node("ConstTraitItem", 4, $1, $3, $4, $5); }
+;
+
+maybe_const_default
+: '=' expr { $$ = mk_node("ConstDefault", 1, $2); }
+| %empty   { $$ = mk_none(); }
+;
+
+trait_type
+: maybe_outer_attrs TYPE ty_param ';' { $$ = mk_node("TypeTraitItem", 2, $1, $3); }
+;
+
+maybe_unsafe
+: UNSAFE { $$ = mk_atom("Unsafe"); }
+| %empty { $$ = mk_none(); }
+;
+
+maybe_default_maybe_unsafe
+: DEFAULT UNSAFE { $$ = mk_atom("DefaultUnsafe"); }
+| DEFAULT        { $$ = mk_atom("Default"); }
+|         UNSAFE { $$ = mk_atom("Unsafe"); }
+| %empty { $$ = mk_none(); }
+
+trait_method
+: type_method { $$ = mk_node("Required", 1, $1); }
+| method      { $$ = mk_node("Provided", 1, $1); }
+;
+
+type_method
+: attrs_and_vis maybe_unsafe FN ident generic_params fn_decl_with_self_allow_anon_params maybe_where_clause ';'
+{
+  $$ = mk_node("TypeMethod", 6, $1, $2, $4, $5, $6, $7);
+}
+| attrs_and_vis maybe_unsafe EXTERN maybe_abi FN ident generic_params fn_decl_with_self_allow_anon_params maybe_where_clause ';'
+{
+  $$ = mk_node("TypeMethod", 7, $1, $2, $4, $6, $7, $8, $9);
+}
+;
+
+method
+: attrs_and_vis maybe_unsafe FN ident generic_params fn_decl_with_self_allow_anon_params maybe_where_clause inner_attrs_and_block
+{
+  $$ = mk_node("Method", 7, $1, $2, $4, $5, $6, $7, $8);
+}
+| attrs_and_vis maybe_unsafe EXTERN maybe_abi FN ident generic_params fn_decl_with_self_allow_anon_params maybe_where_clause inner_attrs_and_block
+{
+  $$ = mk_node("Method", 8, $1, $2, $4, $6, $7, $8, $9, $10);
+}
+;
+
+impl_method
+: attrs_and_vis maybe_unsafe FN ident generic_params fn_decl_with_self maybe_where_clause inner_attrs_and_block
+{
+  $$ = mk_node("Method", 7, $1, $2, $4, $5, $6, $7, $8);
+}
+| attrs_and_vis maybe_unsafe EXTERN maybe_abi FN ident generic_params fn_decl_with_self maybe_where_clause inner_attrs_and_block
+{
+  $$ = mk_node("Method", 8, $1, $2, $4, $6, $7, $8, $9, $10);
+}
+;
+
+// There are two forms of impl:
+//
+// impl (<...>)? TY { ... }
+// impl (<...>)? TRAIT for TY { ... }
+//
+// Unfortunately since TY can begin with '<' itself -- as part of a
+// TyQualifiedPath type -- there's an s/r conflict when we see '<' after IMPL:
+// should we reduce one of the early rules of TY (such as maybe_once)
+// or shall we continue shifting into the generic_params list for the
+// impl?
+//
+// The production parser disambiguates a different case here by
+// permitting / requiring the user to provide parens around types when
+// they are ambiguous with traits. We do the same here, regrettably,
+// by splitting ty into ty and ty_prim.
+item_impl
+: maybe_default_maybe_unsafe IMPL generic_params ty_prim_sum maybe_where_clause '{' maybe_inner_attrs maybe_impl_items '}'
+{
+  $$ = mk_node("ItemImpl", 6, $1, $3, $4, $5, $7, $8);
+}
+| maybe_default_maybe_unsafe IMPL generic_params '(' ty ')' maybe_where_clause '{' maybe_inner_attrs maybe_impl_items '}'
+{
+  $$ = mk_node("ItemImpl", 6, $1, $3, 5, $6, $9, $10);
+}
+| maybe_default_maybe_unsafe IMPL generic_params trait_ref FOR ty_sum maybe_where_clause '{' maybe_inner_attrs maybe_impl_items '}'
+{
+  $$ = mk_node("ItemImpl", 6, $3, $4, $6, $7, $9, $10);
+}
+| maybe_default_maybe_unsafe IMPL generic_params '!' trait_ref FOR ty_sum maybe_where_clause '{' maybe_inner_attrs maybe_impl_items '}'
+{
+  $$ = mk_node("ItemImplNeg", 7, $1, $3, $5, $7, $8, $10, $11);
+}
+| maybe_default_maybe_unsafe IMPL generic_params trait_ref FOR DOTDOT '{' '}'
+{
+  $$ = mk_node("ItemImplDefault", 3, $1, $3, $4);
+}
+| maybe_default_maybe_unsafe IMPL generic_params '!' trait_ref FOR DOTDOT '{' '}'
+{
+  $$ = mk_node("ItemImplDefaultNeg", 3, $1, $3, $4);
+}
+;
+
+maybe_impl_items
+: impl_items
+| %empty { $$ = mk_none(); }
+;
+
+impl_items
+: impl_item               { $$ = mk_node("ImplItems", 1, $1); }
+| impl_item impl_items    { $$ = ext_node($1, 1, $2); }
+;
+
+impl_item
+: impl_method
+| attrs_and_vis item_macro { $$ = mk_node("ImplMacroItem", 2, $1, $2); }
+| impl_const
+| impl_type
+;
+
+impl_const
+: attrs_and_vis item_const { $$ = mk_node("ImplConst", 1, $1, $2); }
+;
+
+impl_type
+: attrs_and_vis TYPE ident generic_params '=' ty_sum ';'  { $$ = mk_node("ImplType", 4, $1, $3, $4, $6); }
+;
+
+item_fn
+: FN ident generic_params fn_decl maybe_where_clause inner_attrs_and_block
+{
+  $$ = mk_node("ItemFn", 5, $2, $3, $4, $5, $6);
+}
+;
+
+item_unsafe_fn
+: UNSAFE FN ident generic_params fn_decl maybe_where_clause inner_attrs_and_block
+{
+  $$ = mk_node("ItemUnsafeFn", 5, $3, $4, $5, $6, $7);
+}
+| UNSAFE EXTERN maybe_abi FN ident generic_params fn_decl maybe_where_clause inner_attrs_and_block
+{
+  $$ = mk_node("ItemUnsafeFn", 6, $3, $5, $6, $7, $8, $9);
+}
+;
+
+fn_decl
+: fn_params ret_ty   { $$ = mk_node("FnDecl", 2, $1, $2); }
+;
+
+fn_decl_with_self
+: fn_params_with_self ret_ty   { $$ = mk_node("FnDecl", 2, $1, $2); }
+;
+
+fn_decl_with_self_allow_anon_params
+: fn_anon_params_with_self ret_ty   { $$ = mk_node("FnDecl", 2, $1, $2); }
+;
+
+fn_params
+: '(' maybe_params ')'  { $$ = $2; }
+;
+
+fn_anon_params
+: '(' anon_param anon_params_allow_variadic_tail ')' { $$ = ext_node($2, 1, $3); }
+| '(' ')'                                            { $$ = mk_none(); }
+;
+
+fn_params_with_self
+: '(' maybe_mut SELF maybe_ty_ascription maybe_comma_params ')'              { $$ = mk_node("SelfValue", 3, $2, $4, $5); }
+| '(' '&' maybe_mut SELF maybe_ty_ascription maybe_comma_params ')'          { $$ = mk_node("SelfRegion", 3, $3, $5, $6); }
+| '(' '&' lifetime maybe_mut SELF maybe_ty_ascription maybe_comma_params ')' { $$ = mk_node("SelfRegion", 4, $3, $4, $6, $7); }
+| '(' maybe_params ')'                                                       { $$ = mk_node("SelfStatic", 1, $2); }
+;
+
+fn_anon_params_with_self
+: '(' maybe_mut SELF maybe_ty_ascription maybe_comma_anon_params ')'              { $$ = mk_node("SelfValue", 3, $2, $4, $5); }
+| '(' '&' maybe_mut SELF maybe_ty_ascription maybe_comma_anon_params ')'          { $$ = mk_node("SelfRegion", 3, $3, $5, $6); }
+| '(' '&' lifetime maybe_mut SELF maybe_ty_ascription maybe_comma_anon_params ')' { $$ = mk_node("SelfRegion", 4, $3, $4, $6, $7); }
+| '(' maybe_anon_params ')'                                                       { $$ = mk_node("SelfStatic", 1, $2); }
+;
+
+maybe_params
+: params
+| params ','
+| %empty  { $$ = mk_none(); }
+;
+
+params
+: param                { $$ = mk_node("Args", 1, $1); }
+| params ',' param     { $$ = ext_node($1, 1, $3); }
+;
+
+param
+: pat ':' ty_sum   { $$ = mk_node("Arg", 2, $1, $3); }
+;
+
+inferrable_params
+: inferrable_param                       { $$ = mk_node("InferrableParams", 1, $1); }
+| inferrable_params ',' inferrable_param { $$ = ext_node($1, 1, $3); }
+;
+
+inferrable_param
+: pat maybe_ty_ascription { $$ = mk_node("InferrableParam", 2, $1, $2); }
+;
+
+maybe_unboxed_closure_kind
+: %empty
+| ':'
+| '&' maybe_mut ':'
+;
+
+maybe_comma_params
+: ','            { $$ = mk_none(); }
+| ',' params     { $$ = $2; }
+| ',' params ',' { $$ = $2; }
+| %empty         { $$ = mk_none(); }
+;
+
+maybe_comma_anon_params
+: ','                 { $$ = mk_none(); }
+| ',' anon_params     { $$ = $2; }
+| ',' anon_params ',' { $$ = $2; }
+| %empty              { $$ = mk_none(); }
+;
+
+maybe_anon_params
+: anon_params
+| anon_params ','
+| %empty      { $$ = mk_none(); }
+;
+
+anon_params
+: anon_param                 { $$ = mk_node("Args", 1, $1); }
+| anon_params ',' anon_param { $$ = ext_node($1, 1, $3); }
+;
+
+// anon means it's allowed to be anonymous (type-only), but it can
+// still have a name
+anon_param
+: named_arg ':' ty   { $$ = mk_node("Arg", 2, $1, $3); }
+| ty
+;
+
+anon_params_allow_variadic_tail
+: ',' DOTDOTDOT                                  { $$ = mk_none(); }
+| ',' anon_param anon_params_allow_variadic_tail { $$ = mk_node("Args", 2, $2, $3); }
+| %empty                                         { $$ = mk_none(); }
+;
+
+named_arg
+: ident
+| UNDERSCORE        { $$ = mk_atom("PatWild"); }
+| '&' ident         { $$ = $2; }
+| '&' UNDERSCORE    { $$ = mk_atom("PatWild"); }
+| ANDAND ident      { $$ = $2; }
+| ANDAND UNDERSCORE { $$ = mk_atom("PatWild"); }
+| MUT ident         { $$ = $2; }
+;
+
+ret_ty
+: RARROW '!'         { $$ = mk_none(); }
+| RARROW ty          { $$ = mk_node("ret-ty", 1, $2); }
+| %prec IDENT %empty { $$ = mk_none(); }
+;
+
+generic_params
+: '<' lifetimes '>'                   { $$ = mk_node("Generics", 2, $2, mk_none()); }
+| '<' lifetimes ',' '>'               { $$ = mk_node("Generics", 2, $2, mk_none()); }
+| '<' lifetimes SHR                   { push_back('>'); $$ = mk_node("Generics", 2, $2, mk_none()); }
+| '<' lifetimes ',' SHR               { push_back('>'); $$ = mk_node("Generics", 2, $2, mk_none()); }
+| '<' lifetimes ',' ty_params '>'     { $$ = mk_node("Generics", 2, $2, $4); }
+| '<' lifetimes ',' ty_params ',' '>' { $$ = mk_node("Generics", 2, $2, $4); }
+| '<' lifetimes ',' ty_params SHR     { push_back('>'); $$ = mk_node("Generics", 2, $2, $4); }
+| '<' lifetimes ',' ty_params ',' SHR { push_back('>'); $$ = mk_node("Generics", 2, $2, $4); }
+| '<' ty_params '>'                   { $$ = mk_node("Generics", 2, mk_none(), $2); }
+| '<' ty_params ',' '>'               { $$ = mk_node("Generics", 2, mk_none(), $2); }
+| '<' ty_params SHR                   { push_back('>'); $$ = mk_node("Generics", 2, mk_none(), $2); }
+| '<' ty_params ',' SHR               { push_back('>'); $$ = mk_node("Generics", 2, mk_none(), $2); }
+| %empty                              { $$ = mk_none(); }
+;
+
+maybe_where_clause
+: %empty                              { $$ = mk_none(); }
+| where_clause
+;
+
+where_clause
+: WHERE where_predicates              { $$ = mk_node("WhereClause", 1, $2); }
+| WHERE where_predicates ','          { $$ = mk_node("WhereClause", 1, $2); }
+;
+
+where_predicates
+: where_predicate                      { $$ = mk_node("WherePredicates", 1, $1); }
+| where_predicates ',' where_predicate { $$ = ext_node($1, 1, $3); }
+;
+
+where_predicate
+: maybe_for_lifetimes lifetime ':' bounds    { $$ = mk_node("WherePredicate", 3, $1, $2, $4); }
+| maybe_for_lifetimes ty ':' ty_param_bounds { $$ = mk_node("WherePredicate", 3, $1, $2, $4); }
+;
+
+maybe_for_lifetimes
+: FOR '<' lifetimes '>' { $$ = mk_none(); }
+| %prec FORTYPE %empty  { $$ = mk_none(); }
+
+ty_params
+: ty_param               { $$ = mk_node("TyParams", 1, $1); }
+| ty_params ',' ty_param { $$ = ext_node($1, 1, $3); }
+;
+
+// A path with no type parameters; e.g. `foo::bar::Baz`
+//
+// These show up in 'use' view-items, because these are processed
+// without respect to types.
+path_no_types_allowed
+: ident                               { $$ = mk_node("ViewPath", 1, $1); }
+| MOD_SEP ident                       { $$ = mk_node("ViewPath", 1, $2); }
+| SELF                                { $$ = mk_node("ViewPath", 1, mk_atom("Self")); }
+| MOD_SEP SELF                        { $$ = mk_node("ViewPath", 1, mk_atom("Self")); }
+| path_no_types_allowed MOD_SEP ident { $$ = ext_node($1, 1, $3); }
+;
+
+// A path with a lifetime and type parameters, with no double colons
+// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
+//
+// These show up in "trait references", the components of
+// type-parameter bounds lists, as well as in the prefix of the
+// path_generic_args_and_bounds rule, which is the full form of a
+// named typed expression.
+//
+// They do not have (nor need) an extra '::' before '<' because
+// unlike in expr context, there are no "less-than" type exprs to
+// be ambiguous with.
+path_generic_args_without_colons
+: %prec IDENT
+  ident                                                                       { $$ = mk_node("components", 1, $1); }
+| %prec IDENT
+  ident generic_args                                                          { $$ = mk_node("components", 2, $1, $2); }
+| %prec IDENT
+  ident '(' maybe_ty_sums ')' ret_ty                                          { $$ = mk_node("components", 2, $1, $3); }
+| %prec IDENT
+  path_generic_args_without_colons MOD_SEP ident                              { $$ = ext_node($1, 1, $3); }
+| %prec IDENT
+  path_generic_args_without_colons MOD_SEP ident generic_args                 { $$ = ext_node($1, 2, $3, $4); }
+| %prec IDENT
+  path_generic_args_without_colons MOD_SEP ident '(' maybe_ty_sums ')' ret_ty { $$ = ext_node($1, 2, $3, $5); }
+;
+
+generic_args
+: '<' generic_values '>'   { $$ = $2; }
+| '<' generic_values SHR   { push_back('>'); $$ = $2; }
+| '<' generic_values GE    { push_back('='); $$ = $2; }
+| '<' generic_values SHREQ { push_back('>'); push_back('='); $$ = $2; }
+// If generic_args starts with "<<", the first arg must be a
+// TyQualifiedPath because that's the only type that can start with a
+// '<'. This rule parses that as the first ty_sum and then continues
+// with the rest of generic_values.
+| SHL ty_qualified_path_and_generic_values '>'   { $$ = $2; }
+| SHL ty_qualified_path_and_generic_values SHR   { push_back('>'); $$ = $2; }
+| SHL ty_qualified_path_and_generic_values GE    { push_back('='); $$ = $2; }
+| SHL ty_qualified_path_and_generic_values SHREQ { push_back('>'); push_back('='); $$ = $2; }
+;
+
+generic_values
+: maybe_lifetimes maybe_ty_sums_and_or_bindings { $$ = mk_node("GenericValues", 2, $1, $2); }
+;
+
+maybe_ty_sums_and_or_bindings
+: ty_sums
+| ty_sums ','
+| ty_sums ',' bindings { $$ = mk_node("TySumsAndBindings", 2, $1, $3); }
+| bindings
+| bindings ','
+| %empty               { $$ = mk_none(); }
+;
+
+maybe_bindings
+: ',' bindings { $$ = $2; }
+| %empty       { $$ = mk_none(); }
+;
+
+////////////////////////////////////////////////////////////////////////
+// Part 2: Patterns
+////////////////////////////////////////////////////////////////////////
+
+pat
+: UNDERSCORE                                      { $$ = mk_atom("PatWild"); }
+| '&' pat                                         { $$ = mk_node("PatRegion", 1, $2); }
+| '&' MUT pat                                     { $$ = mk_node("PatRegion", 1, $3); }
+| ANDAND pat                                      { $$ = mk_node("PatRegion", 1, mk_node("PatRegion", 1, $2)); }
+| '(' ')'                                         { $$ = mk_atom("PatUnit"); }
+| '(' pat_tup ')'                                 { $$ = mk_node("PatTup", 1, $2); }
+| '(' pat_tup ',' ')'                             { $$ = mk_node("PatTup", 1, $2); }
+| '[' pat_vec ']'                                 { $$ = mk_node("PatVec", 1, $2); }
+| lit_or_path
+| lit_or_path DOTDOTDOT lit_or_path               { $$ = mk_node("PatRange", 2, $1, $3); }
+| path_expr '{' pat_struct '}'                    { $$ = mk_node("PatStruct", 2, $1, $3); }
+| path_expr '(' DOTDOT ')'                        { $$ = mk_node("PatEnum", 1, $1); }
+| path_expr '(' pat_tup ')'                       { $$ = mk_node("PatEnum", 2, $1, $3); }
+| path_expr '!' maybe_ident delimited_token_trees { $$ = mk_node("PatMac", 3, $1, $3, $4); }
+| binding_mode ident                              { $$ = mk_node("PatIdent", 2, $1, $2); }
+|              ident '@' pat                      { $$ = mk_node("PatIdent", 3, mk_node("BindByValue", 1, mk_atom("MutImmutable")), $1, $3); }
+| binding_mode ident '@' pat                      { $$ = mk_node("PatIdent", 3, $1, $2, $4); }
+| BOX pat                                         { $$ = mk_node("PatUniq", 1, $2); }
+| '<' ty_sum maybe_as_trait_ref '>' MOD_SEP ident { $$ = mk_node("PatQualifiedPath", 3, $2, $3, $6); }
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident maybe_as_trait_ref '>' MOD_SEP ident
+{
+  $$ = mk_node("PatQualifiedPath", 3, mk_node("PatQualifiedPath", 3, $2, $3, $6), $7, $10);
+}
+;
+
+pats_or
+: pat              { $$ = mk_node("Pats", 1, $1); }
+| pats_or '|' pat  { $$ = ext_node($1, 1, $3); }
+;
+
+binding_mode
+: REF         { $$ = mk_node("BindByRef", 1, mk_atom("MutImmutable")); }
+| REF MUT     { $$ = mk_node("BindByRef", 1, mk_atom("MutMutable")); }
+| MUT         { $$ = mk_node("BindByValue", 1, mk_atom("MutMutable")); }
+;
+
+lit_or_path
+: path_expr    { $$ = mk_node("PatLit", 1, $1); }
+| lit          { $$ = mk_node("PatLit", 1, $1); }
+| '-' lit      { $$ = mk_node("PatLit", 1, $2); }
+;
+
+pat_field
+:                  ident        { $$ = mk_node("PatField", 1, $1); }
+|     binding_mode ident        { $$ = mk_node("PatField", 2, $1, $2); }
+| BOX              ident        { $$ = mk_node("PatField", 2, mk_atom("box"), $2); }
+| BOX binding_mode ident        { $$ = mk_node("PatField", 3, mk_atom("box"), $2, $3); }
+|              ident ':' pat    { $$ = mk_node("PatField", 2, $1, $3); }
+| binding_mode ident ':' pat    { $$ = mk_node("PatField", 3, $1, $2, $4); }
+;
+
+pat_fields
+: pat_field                  { $$ = mk_node("PatFields", 1, $1); }
+| pat_fields ',' pat_field   { $$ = ext_node($1, 1, $3); }
+;
+
+pat_struct
+: pat_fields                 { $$ = mk_node("PatStruct", 2, $1, mk_atom("false")); }
+| pat_fields ','             { $$ = mk_node("PatStruct", 2, $1, mk_atom("false")); }
+| pat_fields ',' DOTDOT      { $$ = mk_node("PatStruct", 2, $1, mk_atom("true")); }
+| DOTDOT                     { $$ = mk_node("PatStruct", 1, mk_atom("true")); }
+;
+
+pat_tup
+: pat               { $$ = mk_node("pat_tup", 1, $1); }
+| pat_tup ',' pat   { $$ = ext_node($1, 1, $3); }
+;
+
+pat_vec
+: pat_vec_elts                                  { $$ = mk_node("PatVec", 2, $1, mk_none()); }
+| pat_vec_elts                             ','  { $$ = mk_node("PatVec", 2, $1, mk_none()); }
+| pat_vec_elts     DOTDOT                       { $$ = mk_node("PatVec", 2, $1, mk_none()); }
+| pat_vec_elts ',' DOTDOT                       { $$ = mk_node("PatVec", 2, $1, mk_none()); }
+| pat_vec_elts     DOTDOT ',' pat_vec_elts      { $$ = mk_node("PatVec", 2, $1, $4); }
+| pat_vec_elts     DOTDOT ',' pat_vec_elts ','  { $$ = mk_node("PatVec", 2, $1, $4); }
+| pat_vec_elts ',' DOTDOT ',' pat_vec_elts      { $$ = mk_node("PatVec", 2, $1, $5); }
+| pat_vec_elts ',' DOTDOT ',' pat_vec_elts ','  { $$ = mk_node("PatVec", 2, $1, $5); }
+|                  DOTDOT ',' pat_vec_elts      { $$ = mk_node("PatVec", 2, mk_none(), $3); }
+|                  DOTDOT ',' pat_vec_elts ','  { $$ = mk_node("PatVec", 2, mk_none(), $3); }
+|                  DOTDOT                       { $$ = mk_node("PatVec", 2, mk_none(), mk_none()); }
+| %empty                                        { $$ = mk_node("PatVec", 2, mk_none(), mk_none()); }
+;
+
+pat_vec_elts
+: pat                    { $$ = mk_node("PatVecElts", 1, $1); }
+| pat_vec_elts ',' pat   { $$ = ext_node($1, 1, $3); }
+;
+
+////////////////////////////////////////////////////////////////////////
+// Part 3: Types
+////////////////////////////////////////////////////////////////////////
+
+ty
+: ty_prim
+| ty_closure
+| '<' ty_sum maybe_as_trait_ref '>' MOD_SEP ident                                      { $$ = mk_node("TyQualifiedPath", 3, $2, $3, $6); }
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident maybe_as_trait_ref '>' MOD_SEP ident { $$ = mk_node("TyQualifiedPath", 3, mk_node("TyQualifiedPath", 3, $2, $3, $6), $7, $10); }
+| '(' ty_sums ')'                                                                      { $$ = mk_node("TyTup", 1, $2); }
+| '(' ty_sums ',' ')'                                                                  { $$ = mk_node("TyTup", 1, $2); }
+| '(' ')'                                                                              { $$ = mk_atom("TyNil"); }
+;
+
+ty_prim
+: %prec IDENT path_generic_args_without_colons              { $$ = mk_node("TyPath", 2, mk_node("global", 1, mk_atom("false")), $1); }
+| %prec IDENT MOD_SEP path_generic_args_without_colons      { $$ = mk_node("TyPath", 2, mk_node("global", 1, mk_atom("true")), $2); }
+| %prec IDENT SELF MOD_SEP path_generic_args_without_colons { $$ = mk_node("TyPath", 2, mk_node("self", 1, mk_atom("true")), $3); }
+| BOX ty                                                    { $$ = mk_node("TyBox", 1, $2); }
+| '*' maybe_mut_or_const ty                                 { $$ = mk_node("TyPtr", 2, $2, $3); }
+| '&' ty                                                    { $$ = mk_node("TyRptr", 2, mk_atom("MutImmutable"), $2); }
+| '&' MUT ty                                                { $$ = mk_node("TyRptr", 2, mk_atom("MutMutable"), $3); }
+| ANDAND ty                                                 { $$ = mk_node("TyRptr", 1, mk_node("TyRptr", 2, mk_atom("MutImmutable"), $2)); }
+| ANDAND MUT ty                                             { $$ = mk_node("TyRptr", 1, mk_node("TyRptr", 2, mk_atom("MutMutable"), $3)); }
+| '&' lifetime maybe_mut ty                                 { $$ = mk_node("TyRptr", 3, $2, $3, $4); }
+| ANDAND lifetime maybe_mut ty                              { $$ = mk_node("TyRptr", 1, mk_node("TyRptr", 3, $2, $3, $4)); }
+| '[' ty ']'                                                { $$ = mk_node("TyVec", 1, $2); }
+| '[' ty ',' DOTDOT expr ']'                                { $$ = mk_node("TyFixedLengthVec", 2, $2, $5); }
+| '[' ty ';' expr ']'                                       { $$ = mk_node("TyFixedLengthVec", 2, $2, $4); }
+| TYPEOF '(' expr ')'                                       { $$ = mk_node("TyTypeof", 1, $3); }
+| UNDERSCORE                                                { $$ = mk_atom("TyInfer"); }
+| ty_bare_fn
+| ty_proc
+| for_in_type
+;
+
+ty_bare_fn
+:                         FN ty_fn_decl { $$ = $2; }
+| UNSAFE                  FN ty_fn_decl { $$ = $3; }
+|        EXTERN maybe_abi FN ty_fn_decl { $$ = $4; }
+| UNSAFE EXTERN maybe_abi FN ty_fn_decl { $$ = $5; }
+;
+
+ty_fn_decl
+: generic_params fn_anon_params ret_ty { $$ = mk_node("TyFnDecl", 3, $1, $2, $3); }
+;
+
+ty_closure
+: UNSAFE '|' anon_params '|' maybe_bounds ret_ty { $$ = mk_node("TyClosure", 3, $3, $5, $6); }
+|        '|' anon_params '|' maybe_bounds ret_ty { $$ = mk_node("TyClosure", 3, $2, $4, $5); }
+| UNSAFE OROR maybe_bounds ret_ty                { $$ = mk_node("TyClosure", 2, $3, $4); }
+|        OROR maybe_bounds ret_ty                { $$ = mk_node("TyClosure", 2, $2, $3); }
+;
+
+ty_proc
+: PROC generic_params fn_params maybe_bounds ret_ty { $$ = mk_node("TyProc", 4, $2, $3, $4, $5); }
+;
+
+for_in_type
+: FOR '<' maybe_lifetimes '>' for_in_type_suffix { $$ = mk_node("ForInType", 2, $3, $5); }
+;
+
+for_in_type_suffix
+: ty_proc
+| ty_bare_fn
+| trait_ref
+| ty_closure
+;
+
+maybe_mut
+: MUT              { $$ = mk_atom("MutMutable"); }
+| %prec MUT %empty { $$ = mk_atom("MutImmutable"); }
+;
+
+maybe_mut_or_const
+: MUT    { $$ = mk_atom("MutMutable"); }
+| CONST  { $$ = mk_atom("MutImmutable"); }
+| %empty { $$ = mk_atom("MutImmutable"); }
+;
+
+ty_qualified_path_and_generic_values
+: ty_qualified_path maybe_bindings
+{
+  $$ = mk_node("GenericValues", 3, mk_none(), mk_node("TySums", 1, mk_node("TySum", 1, $1)), $2);
+}
+| ty_qualified_path ',' ty_sums maybe_bindings
+{
+  $$ = mk_node("GenericValues", 3, mk_none(), mk_node("TySums", 2, $1, $3), $4);
+}
+;
+
+ty_qualified_path
+: ty_sum AS trait_ref '>' MOD_SEP ident                     { $$ = mk_node("TyQualifiedPath", 3, $1, $3, $6); }
+| ty_sum AS trait_ref '>' MOD_SEP ident '+' ty_param_bounds { $$ = mk_node("TyQualifiedPath", 3, $1, $3, $6); }
+;
+
+maybe_ty_sums
+: ty_sums
+| ty_sums ','
+| %empty { $$ = mk_none(); }
+;
+
+ty_sums
+: ty_sum             { $$ = mk_node("TySums", 1, $1); }
+| ty_sums ',' ty_sum { $$ = ext_node($1, 1, $3); }
+;
+
+ty_sum
+: ty                     { $$ = mk_node("TySum", 1, $1); }
+| ty '+' ty_param_bounds { $$ = mk_node("TySum", 2, $1, $3); }
+;
+
+ty_prim_sum
+: ty_prim                     { $$ = mk_node("TySum", 1, $1); }
+| ty_prim '+' ty_param_bounds { $$ = mk_node("TySum", 2, $1, $3); }
+;
+
+maybe_ty_param_bounds
+: ':' ty_param_bounds { $$ = $2; }
+| %empty              { $$ = mk_none(); }
+;
+
+ty_param_bounds
+: boundseq
+| %empty { $$ = mk_none(); }
+;
+
+boundseq
+: polybound
+| boundseq '+' polybound { $$ = ext_node($1, 1, $3); }
+;
+
+polybound
+: FOR '<' maybe_lifetimes '>' bound { $$ = mk_node("PolyBound", 2, $3, $5); }
+| bound
+| '?' bound { $$ = $2; }
+;
+
+bindings
+: binding              { $$ = mk_node("Bindings", 1, $1); }
+| bindings ',' binding { $$ = ext_node($1, 1, $3); }
+;
+
+binding
+: ident '=' ty { mk_node("Binding", 2, $1, $3); }
+;
+
+ty_param
+: ident maybe_ty_param_bounds maybe_ty_default           { $$ = mk_node("TyParam", 3, $1, $2, $3); }
+| ident '?' ident maybe_ty_param_bounds maybe_ty_default { $$ = mk_node("TyParam", 4, $1, $3, $4, $5); }
+;
+
+maybe_bounds
+: %prec SHIFTPLUS
+  ':' bounds             { $$ = $2; }
+| %prec SHIFTPLUS %empty { $$ = mk_none(); }
+;
+
+bounds
+: bound            { $$ = mk_node("bounds", 1, $1); }
+| bounds '+' bound { $$ = ext_node($1, 1, $3); }
+;
+
+bound
+: lifetime
+| trait_ref
+;
+
+maybe_ltbounds
+: %prec SHIFTPLUS
+  ':' ltbounds       { $$ = $2; }
+| %empty             { $$ = mk_none(); }
+;
+
+ltbounds
+: lifetime              { $$ = mk_node("ltbounds", 1, $1); }
+| ltbounds '+' lifetime { $$ = ext_node($1, 1, $3); }
+;
+
+maybe_ty_default
+: '=' ty_sum { $$ = mk_node("TyDefault", 1, $2); }
+| %empty     { $$ = mk_none(); }
+;
+
+maybe_lifetimes
+: lifetimes
+| lifetimes ','
+| %empty { $$ = mk_none(); }
+;
+
+lifetimes
+: lifetime_and_bounds               { $$ = mk_node("Lifetimes", 1, $1); }
+| lifetimes ',' lifetime_and_bounds { $$ = ext_node($1, 1, $3); }
+;
+
+lifetime_and_bounds
+: LIFETIME maybe_ltbounds         { $$ = mk_node("lifetime", 2, mk_atom(yytext), $2); }
+| STATIC_LIFETIME                 { $$ = mk_atom("static_lifetime"); }
+;
+
+lifetime
+: LIFETIME         { $$ = mk_node("lifetime", 1, mk_atom(yytext)); }
+| STATIC_LIFETIME  { $$ = mk_atom("static_lifetime"); }
+;
+
+trait_ref
+: %prec IDENT path_generic_args_without_colons
+| %prec IDENT MOD_SEP path_generic_args_without_colons { $$ = $2; }
+;
+
+////////////////////////////////////////////////////////////////////////
+// Part 4: Blocks, statements, and expressions
+////////////////////////////////////////////////////////////////////////
+
+inner_attrs_and_block
+: '{' maybe_inner_attrs maybe_stmts '}'        { $$ = mk_node("ExprBlock", 2, $2, $3); }
+;
+
+block
+: '{' maybe_stmts '}'                          { $$ = mk_node("ExprBlock", 1, $2); }
+;
+
+maybe_stmts
+: stmts
+| stmts nonblock_expr { $$ = ext_node($1, 1, $2); }
+| nonblock_expr
+| %empty              { $$ = mk_none(); }
+;
+
+// There are two sub-grammars within a "stmts: exprs" derivation
+// depending on whether each stmt-expr is a block-expr form; this is to
+// handle the "semicolon rule" for stmt sequencing that permits
+// writing
+//
+//     if foo { bar } 10
+//
+// as a sequence of two stmts (one if-expr stmt, one lit-10-expr
+// stmt). Unfortunately by permitting juxtaposition of exprs in
+// sequence like that, the non-block expr grammar has to have a
+// second limited sub-grammar that excludes the prefix exprs that
+// are ambiguous with binops. That is to say:
+//
+//     {10} - 1
+//
+// should parse as (progn (progn 10) (- 1)) not (- (progn 10) 1), that
+// is to say, two statements rather than one, at least according to
+// the mainline rust parser.
+//
+// So we wind up with a 3-way split in exprs that occur in stmt lists:
+// block, nonblock-prefix, and nonblock-nonprefix.
+//
+// In non-stmts contexts, expr can relax this trichotomy.
+//
+// There is also one other expr subtype: nonparen_expr disallows exprs
+// surrounded by parens (including tuple expressions), this is
+// necessary for BOX (place) expressions, so a parens expr following
+// the BOX is always parsed as the place.
+
+stmts
+: stmt           { $$ = mk_node("stmts", 1, $1); }
+| stmts stmt     { $$ = ext_node($1, 1, $2); }
+;
+
+stmt
+: let
+|                 stmt_item
+|             PUB stmt_item { $$ = $2; }
+| outer_attrs     stmt_item { $$ = $2; }
+| outer_attrs PUB stmt_item { $$ = $3; }
+| full_block_expr
+| block
+| nonblock_expr ';'
+| ';'                   { $$ = mk_none(); }
+;
+
+maybe_exprs
+: exprs
+| exprs ','
+| %empty { $$ = mk_none(); }
+;
+
+maybe_expr
+: expr
+| %empty { $$ = mk_none(); }
+;
+
+exprs
+: expr                                                        { $$ = mk_node("exprs", 1, $1); }
+| exprs ',' expr                                              { $$ = ext_node($1, 1, $3); }
+;
+
+path_expr
+: path_generic_args_with_colons
+| MOD_SEP path_generic_args_with_colons      { $$ = $2; }
+| SELF MOD_SEP path_generic_args_with_colons { $$ = mk_node("SelfPath", 1, $3); }
+;
+
+// A path with a lifetime and type parameters with double colons before
+// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
+//
+// These show up in expr context, in order to disambiguate from "less-than"
+// expressions.
+path_generic_args_with_colons
+: ident                                              { $$ = mk_node("components", 1, $1); }
+| path_generic_args_with_colons MOD_SEP ident        { $$ = ext_node($1, 1, $3); }
+| path_generic_args_with_colons MOD_SEP generic_args { $$ = ext_node($1, 1, $3); }
+;
+
+// the braces-delimited macro is a block_expr so it doesn't appear here
+macro_expr
+: path_expr '!' maybe_ident parens_delimited_token_trees   { $$ = mk_node("MacroExpr", 3, $1, $3, $4); }
+| path_expr '!' maybe_ident brackets_delimited_token_trees { $$ = mk_node("MacroExpr", 3, $1, $3, $4); }
+;
+
+nonblock_expr
+: lit                                                           { $$ = mk_node("ExprLit", 1, $1); }
+| %prec IDENT
+  path_expr                                                     { $$ = mk_node("ExprPath", 1, $1); }
+| SELF                                                          { $$ = mk_node("ExprPath", 1, mk_node("ident", 1, mk_atom("self"))); }
+| macro_expr                                                    { $$ = mk_node("ExprMac", 1, $1); }
+| path_expr '{' struct_expr_fields '}'                          { $$ = mk_node("ExprStruct", 2, $1, $3); }
+| nonblock_expr '.' path_generic_args_with_colons               { $$ = mk_node("ExprField", 2, $1, $3); }
+| nonblock_expr '.' LIT_INTEGER                                 { $$ = mk_node("ExprTupleIndex", 1, $1); }
+| nonblock_expr '[' maybe_expr ']'                              { $$ = mk_node("ExprIndex", 2, $1, $3); }
+| nonblock_expr '(' maybe_exprs ')'                             { $$ = mk_node("ExprCall", 2, $1, $3); }
+| '[' vec_expr ']'                                              { $$ = mk_node("ExprVec", 1, $2); }
+| '(' maybe_exprs ')'                                           { $$ = mk_node("ExprParen", 1, $2); }
+| CONTINUE                                                      { $$ = mk_node("ExprAgain", 0); }
+| CONTINUE lifetime                                             { $$ = mk_node("ExprAgain", 1, $2); }
+| RETURN                                                        { $$ = mk_node("ExprRet", 0); }
+| RETURN expr                                                   { $$ = mk_node("ExprRet", 1, $2); }
+| BREAK                                                         { $$ = mk_node("ExprBreak", 0); }
+| BREAK lifetime                                                { $$ = mk_node("ExprBreak", 1, $2); }
+| nonblock_expr LARROW expr                                     { $$ = mk_node("ExprInPlace", 2, $1, $3); }
+| nonblock_expr '=' expr                                        { $$ = mk_node("ExprAssign", 2, $1, $3); }
+| nonblock_expr SHLEQ expr                                      { $$ = mk_node("ExprAssignShl", 2, $1, $3); }
+| nonblock_expr SHREQ expr                                      { $$ = mk_node("ExprAssignShr", 2, $1, $3); }
+| nonblock_expr MINUSEQ expr                                    { $$ = mk_node("ExprAssignSub", 2, $1, $3); }
+| nonblock_expr ANDEQ expr                                      { $$ = mk_node("ExprAssignBitAnd", 2, $1, $3); }
+| nonblock_expr OREQ expr                                       { $$ = mk_node("ExprAssignBitOr", 2, $1, $3); }
+| nonblock_expr PLUSEQ expr                                     { $$ = mk_node("ExprAssignAdd", 2, $1, $3); }
+| nonblock_expr STAREQ expr                                     { $$ = mk_node("ExprAssignMul", 2, $1, $3); }
+| nonblock_expr SLASHEQ expr                                    { $$ = mk_node("ExprAssignDiv", 2, $1, $3); }
+| nonblock_expr CARETEQ expr                                    { $$ = mk_node("ExprAssignBitXor", 2, $1, $3); }
+| nonblock_expr PERCENTEQ expr                                  { $$ = mk_node("ExprAssignRem", 2, $1, $3); }
+| nonblock_expr OROR expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiOr"), $1, $3); }
+| nonblock_expr ANDAND expr                                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiAnd"), $1, $3); }
+| nonblock_expr EQEQ expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiEq"), $1, $3); }
+| nonblock_expr NE expr                                         { $$ = mk_node("ExprBinary", 3, mk_atom("BiNe"), $1, $3); }
+| nonblock_expr '<' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiLt"), $1, $3); }
+| nonblock_expr '>' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiGt"), $1, $3); }
+| nonblock_expr LE expr                                         { $$ = mk_node("ExprBinary", 3, mk_atom("BiLe"), $1, $3); }
+| nonblock_expr GE expr                                         { $$ = mk_node("ExprBinary", 3, mk_atom("BiGe"), $1, $3); }
+| nonblock_expr '|' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitOr"), $1, $3); }
+| nonblock_expr '^' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitXor"), $1, $3); }
+| nonblock_expr '&' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitAnd"), $1, $3); }
+| nonblock_expr SHL expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiShl"), $1, $3); }
+| nonblock_expr SHR expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiShr"), $1, $3); }
+| nonblock_expr '+' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiAdd"), $1, $3); }
+| nonblock_expr '-' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiSub"), $1, $3); }
+| nonblock_expr '*' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiMul"), $1, $3); }
+| nonblock_expr '/' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiDiv"), $1, $3); }
+| nonblock_expr '%' expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiRem"), $1, $3); }
+| nonblock_expr DOTDOT                                          { $$ = mk_node("ExprRange", 2, $1, mk_none()); }
+| nonblock_expr DOTDOT expr                                     { $$ = mk_node("ExprRange", 2, $1, $3); }
+|               DOTDOT expr                                     { $$ = mk_node("ExprRange", 2, mk_none(), $2); }
+|               DOTDOT                                          { $$ = mk_node("ExprRange", 2, mk_none(), mk_none()); }
+| nonblock_expr AS ty                                           { $$ = mk_node("ExprCast", 2, $1, $3); }
+| BOX nonparen_expr                                             { $$ = mk_node("ExprBox", 1, $2); }
+| %prec BOXPLACE BOX '(' maybe_expr ')' nonblock_expr           { $$ = mk_node("ExprBox", 2, $3, $5); }
+| expr_qualified_path
+| nonblock_prefix_expr
+;
+
+expr
+: lit                                                 { $$ = mk_node("ExprLit", 1, $1); }
+| %prec IDENT
+  path_expr                                           { $$ = mk_node("ExprPath", 1, $1); }
+| SELF                                                { $$ = mk_node("ExprPath", 1, mk_node("ident", 1, mk_atom("self"))); }
+| macro_expr                                          { $$ = mk_node("ExprMac", 1, $1); }
+| path_expr '{' struct_expr_fields '}'                { $$ = mk_node("ExprStruct", 2, $1, $3); }
+| expr '.' path_generic_args_with_colons              { $$ = mk_node("ExprField", 2, $1, $3); }
+| expr '.' LIT_INTEGER                                { $$ = mk_node("ExprTupleIndex", 1, $1); }
+| expr '[' maybe_expr ']'                             { $$ = mk_node("ExprIndex", 2, $1, $3); }
+| expr '(' maybe_exprs ')'                            { $$ = mk_node("ExprCall", 2, $1, $3); }
+| '(' maybe_exprs ')'                                 { $$ = mk_node("ExprParen", 1, $2); }
+| '[' vec_expr ']'                                    { $$ = mk_node("ExprVec", 1, $2); }
+| CONTINUE                                            { $$ = mk_node("ExprAgain", 0); }
+| CONTINUE ident                                      { $$ = mk_node("ExprAgain", 1, $2); }
+| RETURN                                              { $$ = mk_node("ExprRet", 0); }
+| RETURN expr                                         { $$ = mk_node("ExprRet", 1, $2); }
+| BREAK                                               { $$ = mk_node("ExprBreak", 0); }
+| BREAK ident                                         { $$ = mk_node("ExprBreak", 1, $2); }
+| expr LARROW expr                                    { $$ = mk_node("ExprInPlace", 2, $1, $3); }
+| expr '=' expr                                       { $$ = mk_node("ExprAssign", 2, $1, $3); }
+| expr SHLEQ expr                                     { $$ = mk_node("ExprAssignShl", 2, $1, $3); }
+| expr SHREQ expr                                     { $$ = mk_node("ExprAssignShr", 2, $1, $3); }
+| expr MINUSEQ expr                                   { $$ = mk_node("ExprAssignSub", 2, $1, $3); }
+| expr ANDEQ expr                                     { $$ = mk_node("ExprAssignBitAnd", 2, $1, $3); }
+| expr OREQ expr                                      { $$ = mk_node("ExprAssignBitOr", 2, $1, $3); }
+| expr PLUSEQ expr                                    { $$ = mk_node("ExprAssignAdd", 2, $1, $3); }
+| expr STAREQ expr                                    { $$ = mk_node("ExprAssignMul", 2, $1, $3); }
+| expr SLASHEQ expr                                   { $$ = mk_node("ExprAssignDiv", 2, $1, $3); }
+| expr CARETEQ expr                                   { $$ = mk_node("ExprAssignBitXor", 2, $1, $3); }
+| expr PERCENTEQ expr                                 { $$ = mk_node("ExprAssignRem", 2, $1, $3); }
+| expr OROR expr                                      { $$ = mk_node("ExprBinary", 3, mk_atom("BiOr"), $1, $3); }
+| expr ANDAND expr                                    { $$ = mk_node("ExprBinary", 3, mk_atom("BiAnd"), $1, $3); }
+| expr EQEQ expr                                      { $$ = mk_node("ExprBinary", 3, mk_atom("BiEq"), $1, $3); }
+| expr NE expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiNe"), $1, $3); }
+| expr '<' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiLt"), $1, $3); }
+| expr '>' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiGt"), $1, $3); }
+| expr LE expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiLe"), $1, $3); }
+| expr GE expr                                        { $$ = mk_node("ExprBinary", 3, mk_atom("BiGe"), $1, $3); }
+| expr '|' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitOr"), $1, $3); }
+| expr '^' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitXor"), $1, $3); }
+| expr '&' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitAnd"), $1, $3); }
+| expr SHL expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiShl"), $1, $3); }
+| expr SHR expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiShr"), $1, $3); }
+| expr '+' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiAdd"), $1, $3); }
+| expr '-' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiSub"), $1, $3); }
+| expr '*' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiMul"), $1, $3); }
+| expr '/' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiDiv"), $1, $3); }
+| expr '%' expr                                       { $$ = mk_node("ExprBinary", 3, mk_atom("BiRem"), $1, $3); }
+| expr DOTDOT                                         { $$ = mk_node("ExprRange", 2, $1, mk_none()); }
+| expr DOTDOT expr                                    { $$ = mk_node("ExprRange", 2, $1, $3); }
+|      DOTDOT expr                                    { $$ = mk_node("ExprRange", 2, mk_none(), $2); }
+|      DOTDOT                                         { $$ = mk_node("ExprRange", 2, mk_none(), mk_none()); }
+| expr AS ty                                          { $$ = mk_node("ExprCast", 2, $1, $3); }
+| BOX nonparen_expr                                   { $$ = mk_node("ExprBox", 1, $2); }
+| %prec BOXPLACE BOX '(' maybe_expr ')' expr          { $$ = mk_node("ExprBox", 2, $3, $5); }
+| expr_qualified_path
+| block_expr
+| block
+| nonblock_prefix_expr
+;
+
+nonparen_expr
+: lit                                                 { $$ = mk_node("ExprLit", 1, $1); }
+| %prec IDENT
+  path_expr                                           { $$ = mk_node("ExprPath", 1, $1); }
+| SELF                                                { $$ = mk_node("ExprPath", 1, mk_node("ident", 1, mk_atom("self"))); }
+| macro_expr                                          { $$ = mk_node("ExprMac", 1, $1); }
+| path_expr '{' struct_expr_fields '}'                { $$ = mk_node("ExprStruct", 2, $1, $3); }
+| nonparen_expr '.' path_generic_args_with_colons     { $$ = mk_node("ExprField", 2, $1, $3); }
+| nonparen_expr '.' LIT_INTEGER                       { $$ = mk_node("ExprTupleIndex", 1, $1); }
+| nonparen_expr '[' maybe_expr ']'                    { $$ = mk_node("ExprIndex", 2, $1, $3); }
+| nonparen_expr '(' maybe_exprs ')'                   { $$ = mk_node("ExprCall", 2, $1, $3); }
+| '[' vec_expr ']'                                    { $$ = mk_node("ExprVec", 1, $2); }
+| CONTINUE                                            { $$ = mk_node("ExprAgain", 0); }
+| CONTINUE ident                                      { $$ = mk_node("ExprAgain", 1, $2); }
+| RETURN                                              { $$ = mk_node("ExprRet", 0); }
+| RETURN expr                                         { $$ = mk_node("ExprRet", 1, $2); }
+| BREAK                                               { $$ = mk_node("ExprBreak", 0); }
+| BREAK ident                                         { $$ = mk_node("ExprBreak", 1, $2); }
+| nonparen_expr LARROW nonparen_expr                  { $$ = mk_node("ExprInPlace", 2, $1, $3); }
+| nonparen_expr '=' nonparen_expr                     { $$ = mk_node("ExprAssign", 2, $1, $3); }
+| nonparen_expr SHLEQ nonparen_expr                   { $$ = mk_node("ExprAssignShl", 2, $1, $3); }
+| nonparen_expr SHREQ nonparen_expr                   { $$ = mk_node("ExprAssignShr", 2, $1, $3); }
+| nonparen_expr MINUSEQ nonparen_expr                 { $$ = mk_node("ExprAssignSub", 2, $1, $3); }
+| nonparen_expr ANDEQ nonparen_expr                   { $$ = mk_node("ExprAssignBitAnd", 2, $1, $3); }
+| nonparen_expr OREQ nonparen_expr                    { $$ = mk_node("ExprAssignBitOr", 2, $1, $3); }
+| nonparen_expr PLUSEQ nonparen_expr                  { $$ = mk_node("ExprAssignAdd", 2, $1, $3); }
+| nonparen_expr STAREQ nonparen_expr                  { $$ = mk_node("ExprAssignMul", 2, $1, $3); }
+| nonparen_expr SLASHEQ nonparen_expr                 { $$ = mk_node("ExprAssignDiv", 2, $1, $3); }
+| nonparen_expr CARETEQ nonparen_expr                 { $$ = mk_node("ExprAssignBitXor", 2, $1, $3); }
+| nonparen_expr PERCENTEQ nonparen_expr               { $$ = mk_node("ExprAssignRem", 2, $1, $3); }
+| nonparen_expr OROR nonparen_expr                    { $$ = mk_node("ExprBinary", 3, mk_atom("BiOr"), $1, $3); }
+| nonparen_expr ANDAND nonparen_expr                  { $$ = mk_node("ExprBinary", 3, mk_atom("BiAnd"), $1, $3); }
+| nonparen_expr EQEQ nonparen_expr                    { $$ = mk_node("ExprBinary", 3, mk_atom("BiEq"), $1, $3); }
+| nonparen_expr NE nonparen_expr                      { $$ = mk_node("ExprBinary", 3, mk_atom("BiNe"), $1, $3); }
+| nonparen_expr '<' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiLt"), $1, $3); }
+| nonparen_expr '>' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiGt"), $1, $3); }
+| nonparen_expr LE nonparen_expr                      { $$ = mk_node("ExprBinary", 3, mk_atom("BiLe"), $1, $3); }
+| nonparen_expr GE nonparen_expr                      { $$ = mk_node("ExprBinary", 3, mk_atom("BiGe"), $1, $3); }
+| nonparen_expr '|' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitOr"), $1, $3); }
+| nonparen_expr '^' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitXor"), $1, $3); }
+| nonparen_expr '&' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitAnd"), $1, $3); }
+| nonparen_expr SHL nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiShl"), $1, $3); }
+| nonparen_expr SHR nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiShr"), $1, $3); }
+| nonparen_expr '+' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiAdd"), $1, $3); }
+| nonparen_expr '-' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiSub"), $1, $3); }
+| nonparen_expr '*' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiMul"), $1, $3); }
+| nonparen_expr '/' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiDiv"), $1, $3); }
+| nonparen_expr '%' nonparen_expr                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiRem"), $1, $3); }
+| nonparen_expr DOTDOT                                { $$ = mk_node("ExprRange", 2, $1, mk_none()); }
+| nonparen_expr DOTDOT nonparen_expr                  { $$ = mk_node("ExprRange", 2, $1, $3); }
+|               DOTDOT nonparen_expr                  { $$ = mk_node("ExprRange", 2, mk_none(), $2); }
+|               DOTDOT                                { $$ = mk_node("ExprRange", 2, mk_none(), mk_none()); }
+| nonparen_expr AS ty                                 { $$ = mk_node("ExprCast", 2, $1, $3); }
+| BOX nonparen_expr                                   { $$ = mk_node("ExprBox", 1, $2); }
+| %prec BOXPLACE BOX '(' maybe_expr ')' expr          { $$ = mk_node("ExprBox", 1, $3, $5); }
+| expr_qualified_path
+| block_expr
+| block
+| nonblock_prefix_expr
+;
+
+expr_nostruct
+: lit                                                 { $$ = mk_node("ExprLit", 1, $1); }
+| %prec IDENT
+  path_expr                                           { $$ = mk_node("ExprPath", 1, $1); }
+| SELF                                                { $$ = mk_node("ExprPath", 1, mk_node("ident", 1, mk_atom("self"))); }
+| macro_expr                                          { $$ = mk_node("ExprMac", 1, $1); }
+| expr_nostruct '.' path_generic_args_with_colons     { $$ = mk_node("ExprField", 2, $1, $3); }
+| expr_nostruct '.' LIT_INTEGER                       { $$ = mk_node("ExprTupleIndex", 1, $1); }
+| expr_nostruct '[' maybe_expr ']'                    { $$ = mk_node("ExprIndex", 2, $1, $3); }
+| expr_nostruct '(' maybe_exprs ')'                   { $$ = mk_node("ExprCall", 2, $1, $3); }
+| '[' vec_expr ']'                                    { $$ = mk_node("ExprVec", 1, $2); }
+| '(' maybe_exprs ')'                                 { $$ = mk_node("ExprParen", 1, $2); }
+| CONTINUE                                            { $$ = mk_node("ExprAgain", 0); }
+| CONTINUE ident                                      { $$ = mk_node("ExprAgain", 1, $2); }
+| RETURN                                              { $$ = mk_node("ExprRet", 0); }
+| RETURN expr                                         { $$ = mk_node("ExprRet", 1, $2); }
+| BREAK                                               { $$ = mk_node("ExprBreak", 0); }
+| BREAK ident                                         { $$ = mk_node("ExprBreak", 1, $2); }
+| expr_nostruct LARROW expr_nostruct                  { $$ = mk_node("ExprInPlace", 2, $1, $3); }
+| expr_nostruct '=' expr_nostruct                     { $$ = mk_node("ExprAssign", 2, $1, $3); }
+| expr_nostruct SHLEQ expr_nostruct                   { $$ = mk_node("ExprAssignShl", 2, $1, $3); }
+| expr_nostruct SHREQ expr_nostruct                   { $$ = mk_node("ExprAssignShr", 2, $1, $3); }
+| expr_nostruct MINUSEQ expr_nostruct                 { $$ = mk_node("ExprAssignSub", 2, $1, $3); }
+| expr_nostruct ANDEQ expr_nostruct                   { $$ = mk_node("ExprAssignBitAnd", 2, $1, $3); }
+| expr_nostruct OREQ expr_nostruct                    { $$ = mk_node("ExprAssignBitOr", 2, $1, $3); }
+| expr_nostruct PLUSEQ expr_nostruct                  { $$ = mk_node("ExprAssignAdd", 2, $1, $3); }
+| expr_nostruct STAREQ expr_nostruct                  { $$ = mk_node("ExprAssignMul", 2, $1, $3); }
+| expr_nostruct SLASHEQ expr_nostruct                 { $$ = mk_node("ExprAssignDiv", 2, $1, $3); }
+| expr_nostruct CARETEQ expr_nostruct                 { $$ = mk_node("ExprAssignBitXor", 2, $1, $3); }
+| expr_nostruct PERCENTEQ expr_nostruct               { $$ = mk_node("ExprAssignRem", 2, $1, $3); }
+| expr_nostruct OROR expr_nostruct                    { $$ = mk_node("ExprBinary", 3, mk_atom("BiOr"), $1, $3); }
+| expr_nostruct ANDAND expr_nostruct                  { $$ = mk_node("ExprBinary", 3, mk_atom("BiAnd"), $1, $3); }
+| expr_nostruct EQEQ expr_nostruct                    { $$ = mk_node("ExprBinary", 3, mk_atom("BiEq"), $1, $3); }
+| expr_nostruct NE expr_nostruct                      { $$ = mk_node("ExprBinary", 3, mk_atom("BiNe"), $1, $3); }
+| expr_nostruct '<' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiLt"), $1, $3); }
+| expr_nostruct '>' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiGt"), $1, $3); }
+| expr_nostruct LE expr_nostruct                      { $$ = mk_node("ExprBinary", 3, mk_atom("BiLe"), $1, $3); }
+| expr_nostruct GE expr_nostruct                      { $$ = mk_node("ExprBinary", 3, mk_atom("BiGe"), $1, $3); }
+| expr_nostruct '|' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitOr"), $1, $3); }
+| expr_nostruct '^' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitXor"), $1, $3); }
+| expr_nostruct '&' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiBitAnd"), $1, $3); }
+| expr_nostruct SHL expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiShl"), $1, $3); }
+| expr_nostruct SHR expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiShr"), $1, $3); }
+| expr_nostruct '+' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiAdd"), $1, $3); }
+| expr_nostruct '-' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiSub"), $1, $3); }
+| expr_nostruct '*' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiMul"), $1, $3); }
+| expr_nostruct '/' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiDiv"), $1, $3); }
+| expr_nostruct '%' expr_nostruct                     { $$ = mk_node("ExprBinary", 3, mk_atom("BiRem"), $1, $3); }
+| expr_nostruct DOTDOT               %prec RANGE      { $$ = mk_node("ExprRange", 2, $1, mk_none()); }
+| expr_nostruct DOTDOT expr_nostruct                  { $$ = mk_node("ExprRange", 2, $1, $3); }
+|               DOTDOT expr_nostruct                  { $$ = mk_node("ExprRange", 2, mk_none(), $2); }
+|               DOTDOT                                { $$ = mk_node("ExprRange", 2, mk_none(), mk_none()); }
+| expr_nostruct AS ty                                 { $$ = mk_node("ExprCast", 2, $1, $3); }
+| BOX nonparen_expr                                   { $$ = mk_node("ExprBox", 1, $2); }
+| %prec BOXPLACE BOX '(' maybe_expr ')' expr_nostruct { $$ = mk_node("ExprBox", 1, $3, $5); }
+| expr_qualified_path
+| block_expr
+| block
+| nonblock_prefix_expr_nostruct
+;
+
+nonblock_prefix_expr_nostruct
+: '-' expr_nostruct                         { $$ = mk_node("ExprUnary", 2, mk_atom("UnNeg"), $2); }
+| '!' expr_nostruct                         { $$ = mk_node("ExprUnary", 2, mk_atom("UnNot"), $2); }
+| '*' expr_nostruct                         { $$ = mk_node("ExprUnary", 2, mk_atom("UnDeref"), $2); }
+| '&' maybe_mut expr_nostruct               { $$ = mk_node("ExprAddrOf", 2, $2, $3); }
+| ANDAND maybe_mut expr_nostruct            { $$ = mk_node("ExprAddrOf", 1, mk_node("ExprAddrOf", 2, $2, $3)); }
+| lambda_expr_nostruct
+| MOVE lambda_expr_nostruct                 { $$ = $2; }
+| proc_expr_nostruct
+;
+
+nonblock_prefix_expr
+: '-' expr                         { $$ = mk_node("ExprUnary", 2, mk_atom("UnNeg"), $2); }
+| '!' expr                         { $$ = mk_node("ExprUnary", 2, mk_atom("UnNot"), $2); }
+| '*' expr                         { $$ = mk_node("ExprUnary", 2, mk_atom("UnDeref"), $2); }
+| '&' maybe_mut expr               { $$ = mk_node("ExprAddrOf", 2, $2, $3); }
+| ANDAND maybe_mut expr            { $$ = mk_node("ExprAddrOf", 1, mk_node("ExprAddrOf", 2, $2, $3)); }
+| lambda_expr
+| MOVE lambda_expr                 { $$ = $2; }
+| proc_expr
+;
+
+expr_qualified_path
+: '<' ty_sum maybe_as_trait_ref '>' MOD_SEP ident maybe_qpath_params
+{
+  $$ = mk_node("ExprQualifiedPath", 4, $2, $3, $6, $7);
+}
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident maybe_as_trait_ref '>' MOD_SEP ident
+{
+  $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 3, $2, $3, $6), $7, $10);
+}
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident generic_args maybe_as_trait_ref '>' MOD_SEP ident
+{
+  $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 4, $2, $3, $6, $7), $8, $11);
+}
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident maybe_as_trait_ref '>' MOD_SEP ident generic_args
+{
+  $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 3, $2, $3, $6), $7, $10, $11);
+}
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident generic_args maybe_as_trait_ref '>' MOD_SEP ident generic_args
+{
+  $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 4, $2, $3, $6, $7), $8, $11, $12);
+}
+
+maybe_qpath_params
+: MOD_SEP generic_args { $$ = $2; }
+| %empty               { $$ = mk_none(); }
+;
+
+maybe_as_trait_ref
+: AS trait_ref { $$ = $2; }
+| %empty       { $$ = mk_none(); }
+;
+
+lambda_expr
+: %prec LAMBDA
+  OROR ret_ty expr                                        { $$ = mk_node("ExprFnBlock", 3, mk_none(), $2, $3); }
+| %prec LAMBDA
+  '|' maybe_unboxed_closure_kind '|' ret_ty expr          { $$ = mk_node("ExprFnBlock", 3, mk_none(), $4, $5); }
+| %prec LAMBDA
+  '|' inferrable_params '|' ret_ty expr                   { $$ = mk_node("ExprFnBlock", 3, $2, $4, $5); }
+| %prec LAMBDA
+  '|' '&' maybe_mut ':' inferrable_params '|' ret_ty expr { $$ = mk_node("ExprFnBlock", 3, $5, $7, $8); }
+| %prec LAMBDA
+  '|' ':' inferrable_params '|' ret_ty expr               { $$ = mk_node("ExprFnBlock", 3, $3, $5, $6); }
+;
+
+lambda_expr_nostruct
+: %prec LAMBDA
+  OROR expr_nostruct                                        { $$ = mk_node("ExprFnBlock", 2, mk_none(), $2); }
+| %prec LAMBDA
+  '|' maybe_unboxed_closure_kind '|'  expr_nostruct         { $$ = mk_node("ExprFnBlock", 2, mk_none(), $4); }
+| %prec LAMBDA
+  '|' inferrable_params '|' expr_nostruct                   { $$ = mk_node("ExprFnBlock", 2, $2, $4); }
+| %prec LAMBDA
+  '|' '&' maybe_mut ':' inferrable_params '|' expr_nostruct { $$ = mk_node("ExprFnBlock", 2, $5, $7); }
+| %prec LAMBDA
+  '|' ':' inferrable_params '|' expr_nostruct               { $$ = mk_node("ExprFnBlock", 2, $3, $5); }
+
+;
+
+proc_expr
+: %prec LAMBDA
+  PROC '(' ')' expr                         { $$ = mk_node("ExprProc", 2, mk_none(), $4); }
+| %prec LAMBDA
+  PROC '(' inferrable_params ')' expr       { $$ = mk_node("ExprProc", 2, $3, $5); }
+;
+
+proc_expr_nostruct
+: %prec LAMBDA
+  PROC '(' ')' expr_nostruct                     { $$ = mk_node("ExprProc", 2, mk_none(), $4); }
+| %prec LAMBDA
+  PROC '(' inferrable_params ')' expr_nostruct   { $$ = mk_node("ExprProc", 2, $3, $5); }
+;
+
+vec_expr
+: maybe_exprs
+| exprs ';' expr { $$ = mk_node("VecRepeat", 2, $1, $3); }
+;
+
+struct_expr_fields
+: field_inits
+| field_inits ','
+| maybe_field_inits default_field_init { $$ = ext_node($1, 1, $2); }
+;
+
+maybe_field_inits
+: field_inits
+| field_inits ','
+| %empty { $$ = mk_none(); }
+;
+
+field_inits
+: field_init                 { $$ = mk_node("FieldInits", 1, $1); }
+| field_inits ',' field_init { $$ = ext_node($1, 1, $3); }
+;
+
+field_init
+: ident ':' expr   { $$ = mk_node("FieldInit", 2, $1, $3); }
+;
+
+default_field_init
+: DOTDOT expr   { $$ = mk_node("DefaultFieldInit", 1, $2); }
+;
+
+block_expr
+: expr_match
+| expr_if
+| expr_if_let
+| expr_while
+| expr_while_let
+| expr_loop
+| expr_for
+| UNSAFE block                                           { $$ = mk_node("UnsafeBlock", 1, $2); }
+| path_expr '!' maybe_ident braces_delimited_token_trees { $$ = mk_node("Macro", 3, $1, $3, $4); }
+;
+
+full_block_expr
+: block_expr
+| full_block_expr '.' path_generic_args_with_colons %prec IDENT         { $$ = mk_node("ExprField", 2, $1, $3); }
+| full_block_expr '.' path_generic_args_with_colons '[' maybe_expr ']'  { $$ = mk_node("ExprIndex", 3, $1, $3, $5); }
+| full_block_expr '.' path_generic_args_with_colons '(' maybe_exprs ')' { $$ = mk_node("ExprCall", 3, $1, $3, $5); }
+| full_block_expr '.' LIT_INTEGER                                       { $$ = mk_node("ExprTupleIndex", 1, $1); }
+;
+
+expr_match
+: MATCH expr_nostruct '{' '}'                                     { $$ = mk_node("ExprMatch", 1, $2); }
+| MATCH expr_nostruct '{' match_clauses                       '}' { $$ = mk_node("ExprMatch", 2, $2, $4); }
+| MATCH expr_nostruct '{' match_clauses nonblock_match_clause '}' { $$ = mk_node("ExprMatch", 2, $2, ext_node($4, 1, $5)); }
+| MATCH expr_nostruct '{'               nonblock_match_clause '}' { $$ = mk_node("ExprMatch", 2, $2, mk_node("Arms", 1, $4)); }
+;
+
+match_clauses
+: match_clause               { $$ = mk_node("Arms", 1, $1); }
+| match_clauses match_clause { $$ = ext_node($1, 1, $2); }
+;
+
+match_clause
+: nonblock_match_clause ','
+| block_match_clause
+| block_match_clause ','
+;
+
+nonblock_match_clause
+: maybe_outer_attrs pats_or maybe_guard FAT_ARROW nonblock_expr   { $$ = mk_node("Arm", 4, $1, $2, $3, $5); }
+| maybe_outer_attrs pats_or maybe_guard FAT_ARROW full_block_expr { $$ = mk_node("Arm", 4, $1, $2, $3, $5); }
+;
+
+block_match_clause
+: maybe_outer_attrs pats_or maybe_guard FAT_ARROW block { $$ = mk_node("Arm", 4, $1, $2, $3, $5); }
+;
+
+maybe_guard
+: IF expr_nostruct           { $$ = $2; }
+| %empty                     { $$ = mk_none(); }
+;
+
+expr_if
+: IF expr_nostruct block                              { $$ = mk_node("ExprIf", 2, $2, $3); }
+| IF expr_nostruct block ELSE block_or_if             { $$ = mk_node("ExprIf", 3, $2, $3, $5); }
+;
+
+expr_if_let
+: IF LET pat '=' expr_nostruct block                  { $$ = mk_node("ExprIfLet", 3, $3, $5, $6); }
+| IF LET pat '=' expr_nostruct block ELSE block_or_if { $$ = mk_node("ExprIfLet", 4, $3, $5, $6, $8); }
+;
+
+block_or_if
+: block
+| expr_if
+| expr_if_let
+;
+
+expr_while
+: maybe_label WHILE expr_nostruct block               { $$ = mk_node("ExprWhile", 3, $1, $3, $4); }
+;
+
+expr_while_let
+: maybe_label WHILE LET pat '=' expr_nostruct block   { $$ = mk_node("ExprWhileLet", 4, $1, $4, $6, $7); }
+;
+
+expr_loop
+: maybe_label LOOP block                              { $$ = mk_node("ExprLoop", 2, $1, $3); }
+;
+
+expr_for
+: maybe_label FOR pat IN expr_nostruct block          { $$ = mk_node("ExprForLoop", 4, $1, $3, $5, $6); }
+;
+
+maybe_label
+: lifetime ':'
+| %empty { $$ = mk_none(); }
+;
+
+let
+: LET pat maybe_ty_ascription maybe_init_expr ';' { $$ = mk_node("DeclLocal", 3, $2, $3, $4); }
+;
+
+////////////////////////////////////////////////////////////////////////
+// Part 5: Macros and misc. rules
+////////////////////////////////////////////////////////////////////////
+
+lit
+: LIT_BYTE                   { $$ = mk_node("LitByte", 1, mk_atom(yytext)); }
+| LIT_CHAR                   { $$ = mk_node("LitChar", 1, mk_atom(yytext)); }
+| LIT_INTEGER                { $$ = mk_node("LitInteger", 1, mk_atom(yytext)); }
+| LIT_FLOAT                  { $$ = mk_node("LitFloat", 1, mk_atom(yytext)); }
+| TRUE                       { $$ = mk_node("LitBool", 1, mk_atom(yytext)); }
+| FALSE                      { $$ = mk_node("LitBool", 1, mk_atom(yytext)); }
+| str
+;
+
+str
+: LIT_STR                    { $$ = mk_node("LitStr", 1, mk_atom(yytext), mk_atom("CookedStr")); }
+| LIT_STR_RAW                { $$ = mk_node("LitStr", 1, mk_atom(yytext), mk_atom("RawStr")); }
+| LIT_BYTE_STR                 { $$ = mk_node("LitByteStr", 1, mk_atom(yytext), mk_atom("ByteStr")); }
+| LIT_BYTE_STR_RAW             { $$ = mk_node("LitByteStr", 1, mk_atom(yytext), mk_atom("RawByteStr")); }
+;
+
+maybe_ident
+: %empty { $$ = mk_none(); }
+| ident
+;
+
+ident
+: IDENT                      { $$ = mk_node("ident", 1, mk_atom(yytext)); }
+;
+
+unpaired_token
+: SHL                        { $$ = mk_atom(yytext); }
+| SHR                        { $$ = mk_atom(yytext); }
+| LE                         { $$ = mk_atom(yytext); }
+| EQEQ                       { $$ = mk_atom(yytext); }
+| NE                         { $$ = mk_atom(yytext); }
+| GE                         { $$ = mk_atom(yytext); }
+| ANDAND                     { $$ = mk_atom(yytext); }
+| OROR                       { $$ = mk_atom(yytext); }
+| LARROW                     { $$ = mk_atom(yytext); }
+| SHLEQ                      { $$ = mk_atom(yytext); }
+| SHREQ                      { $$ = mk_atom(yytext); }
+| MINUSEQ                    { $$ = mk_atom(yytext); }
+| ANDEQ                      { $$ = mk_atom(yytext); }
+| OREQ                       { $$ = mk_atom(yytext); }
+| PLUSEQ                     { $$ = mk_atom(yytext); }
+| STAREQ                     { $$ = mk_atom(yytext); }
+| SLASHEQ                    { $$ = mk_atom(yytext); }
+| CARETEQ                    { $$ = mk_atom(yytext); }
+| PERCENTEQ                  { $$ = mk_atom(yytext); }
+| DOTDOT                     { $$ = mk_atom(yytext); }
+| DOTDOTDOT                  { $$ = mk_atom(yytext); }
+| MOD_SEP                    { $$ = mk_atom(yytext); }
+| RARROW                     { $$ = mk_atom(yytext); }
+| FAT_ARROW                  { $$ = mk_atom(yytext); }
+| LIT_BYTE                   { $$ = mk_atom(yytext); }
+| LIT_CHAR                   { $$ = mk_atom(yytext); }
+| LIT_INTEGER                { $$ = mk_atom(yytext); }
+| LIT_FLOAT                  { $$ = mk_atom(yytext); }
+| LIT_STR                    { $$ = mk_atom(yytext); }
+| LIT_STR_RAW                { $$ = mk_atom(yytext); }
+| LIT_BYTE_STR               { $$ = mk_atom(yytext); }
+| LIT_BYTE_STR_RAW           { $$ = mk_atom(yytext); }
+| IDENT                      { $$ = mk_atom(yytext); }
+| UNDERSCORE                 { $$ = mk_atom(yytext); }
+| LIFETIME                   { $$ = mk_atom(yytext); }
+| SELF                       { $$ = mk_atom(yytext); }
+| STATIC                     { $$ = mk_atom(yytext); }
+| AS                         { $$ = mk_atom(yytext); }
+| BREAK                      { $$ = mk_atom(yytext); }
+| CRATE                      { $$ = mk_atom(yytext); }
+| ELSE                       { $$ = mk_atom(yytext); }
+| ENUM                       { $$ = mk_atom(yytext); }
+| EXTERN                     { $$ = mk_atom(yytext); }
+| FALSE                      { $$ = mk_atom(yytext); }
+| FN                         { $$ = mk_atom(yytext); }
+| FOR                        { $$ = mk_atom(yytext); }
+| IF                         { $$ = mk_atom(yytext); }
+| IMPL                       { $$ = mk_atom(yytext); }
+| IN                         { $$ = mk_atom(yytext); }
+| LET                        { $$ = mk_atom(yytext); }
+| LOOP                       { $$ = mk_atom(yytext); }
+| MATCH                      { $$ = mk_atom(yytext); }
+| MOD                        { $$ = mk_atom(yytext); }
+| MOVE                       { $$ = mk_atom(yytext); }
+| MUT                        { $$ = mk_atom(yytext); }
+| PRIV                       { $$ = mk_atom(yytext); }
+| PUB                        { $$ = mk_atom(yytext); }
+| REF                        { $$ = mk_atom(yytext); }
+| RETURN                     { $$ = mk_atom(yytext); }
+| STRUCT                     { $$ = mk_atom(yytext); }
+| TRUE                       { $$ = mk_atom(yytext); }
+| TRAIT                      { $$ = mk_atom(yytext); }
+| TYPE                       { $$ = mk_atom(yytext); }
+| UNSAFE                     { $$ = mk_atom(yytext); }
+| USE                        { $$ = mk_atom(yytext); }
+| WHILE                      { $$ = mk_atom(yytext); }
+| CONTINUE                   { $$ = mk_atom(yytext); }
+| PROC                       { $$ = mk_atom(yytext); }
+| BOX                        { $$ = mk_atom(yytext); }
+| CONST                      { $$ = mk_atom(yytext); }
+| WHERE                      { $$ = mk_atom(yytext); }
+| TYPEOF                     { $$ = mk_atom(yytext); }
+| INNER_DOC_COMMENT          { $$ = mk_atom(yytext); }
+| OUTER_DOC_COMMENT          { $$ = mk_atom(yytext); }
+| SHEBANG                    { $$ = mk_atom(yytext); }
+| STATIC_LIFETIME            { $$ = mk_atom(yytext); }
+| ';'                        { $$ = mk_atom(yytext); }
+| ','                        { $$ = mk_atom(yytext); }
+| '.'                        { $$ = mk_atom(yytext); }
+| '@'                        { $$ = mk_atom(yytext); }
+| '#'                        { $$ = mk_atom(yytext); }
+| '~'                        { $$ = mk_atom(yytext); }
+| ':'                        { $$ = mk_atom(yytext); }
+| '$'                        { $$ = mk_atom(yytext); }
+| '='                        { $$ = mk_atom(yytext); }
+| '?'                        { $$ = mk_atom(yytext); }
+| '!'                        { $$ = mk_atom(yytext); }
+| '<'                        { $$ = mk_atom(yytext); }
+| '>'                        { $$ = mk_atom(yytext); }
+| '-'                        { $$ = mk_atom(yytext); }
+| '&'                        { $$ = mk_atom(yytext); }
+| '|'                        { $$ = mk_atom(yytext); }
+| '+'                        { $$ = mk_atom(yytext); }
+| '*'                        { $$ = mk_atom(yytext); }
+| '/'                        { $$ = mk_atom(yytext); }
+| '^'                        { $$ = mk_atom(yytext); }
+| '%'                        { $$ = mk_atom(yytext); }
+;
+
+token_trees
+: %empty                     { $$ = mk_node("TokenTrees", 0); }
+| token_trees token_tree     { $$ = ext_node($1, 1, $2); }
+;
+
+token_tree
+: delimited_token_trees
+| unpaired_token         { $$ = mk_node("TTTok", 1, $1); }
+;
+
+delimited_token_trees
+: parens_delimited_token_trees
+| braces_delimited_token_trees
+| brackets_delimited_token_trees
+;
+
+parens_delimited_token_trees
+: '(' token_trees ')'
+{
+  $$ = mk_node("TTDelim", 3,
+               mk_node("TTTok", 1, mk_atom("(")),
+               $2,
+               mk_node("TTTok", 1, mk_atom(")")));
+}
+;
+
+braces_delimited_token_trees
+: '{' token_trees '}'
+{
+  $$ = mk_node("TTDelim", 3,
+               mk_node("TTTok", 1, mk_atom("{")),
+               $2,
+               mk_node("TTTok", 1, mk_atom("}")));
+}
+;
+
+brackets_delimited_token_trees
+: '[' token_trees ']'
+{
+  $$ = mk_node("TTDelim", 3,
+               mk_node("TTTok", 1, mk_atom("[")),
+               $2,
+               mk_node("TTTok", 1, mk_atom("]")));
+}
+;
\ No newline at end of file
diff --git a/src/grammar/raw-string-literal-ambiguity.md b/src/grammar/raw-string-literal-ambiguity.md
new file mode 100644
index 00000000000..c909f233314
--- /dev/null
+++ b/src/grammar/raw-string-literal-ambiguity.md
@@ -0,0 +1,64 @@
+Rust's lexical grammar is not context-free. Raw string literals are the source
+of the problem. Informally, a raw string literal is an `r`, followed by `N`
+hashes (where N can be zero), a quote, any characters, then a quote followed
+by `N` hashes. Critically, once inside the first pair of quotes,
+another quote cannot be followed by `N` consecutive hashes. e.g.
+`r###""###"###` is invalid.
+
+This grammar describes this as best possible:
+
+    R -> 'r' S
+    S -> '"' B '"'
+    S -> '#' S '#'
+    B -> . B
+    B -> ε
+
+Where `.` represents any character, and `ε` the empty string. Consider the
+string `r#""#"#`. This string is not a valid raw string literal, but can be
+accepted as one by the above grammar, using the derivation:
+
+    R : #""#"#
+    S : ""#"
+    S : "#
+    B : #
+    B : ε
+
+(Where `T : U` means the rule `T` is applied, and `U` is the remainder of the
+string.) The difficulty arises from the fact that it is fundamentally
+context-sensitive. In particular, the context needed is the number of hashes.
+
+To prove that Rust's string literals are not context-free, we will use
+the fact that context-free languages are closed under intersection with
+regular languages, and the
+[pumping lemma for context-free languages](https://en.wikipedia.org/wiki/Pumping_lemma_for_context-free_languages).
+
+Consider the regular language `R = r#+""#*"#+`. If Rust's raw string literals are
+context-free, then their intersection with `R`, `R'`, should also be context-free.
+Therefore, to prove that raw string literals are not context-free,
+it is sufficient to prove that `R'` is not context-free.
+
+The language `R'` is `{r#^n""#^m"#^n | m < n}`.
+
+Assume `R'` *is* context-free. Then `R'` has some pumping length `p > 0` for which
+the pumping lemma applies. Consider the following string `s` in `R'`:
+
+`r#^p""#^{p-1}"#^p`
+
+e.g. for `p = 2`: `s = r##""#"##`
+
+Then `s = uvwxy` for some choice of `uvwxy` such that `vx` is non-empty,
+`|vwx| < p+1`, and `uv^iwx^iy` is in `R'` for all `i >= 0`.
+
+Neither `v` nor `x` can contain a `"` or `r`, as the number of these characters
+in any string in `R'` is fixed. So `v` and `x` contain only hashes.
+Consequently, of the three sequences of hashes, `v` and `x` combined
+can only pump two of them.
+If we ever choose the central sequence of hashes, then one of the outer sequences
+will not grow when we pump, leading to an imbalance between the outer sequences.
+Therefore, we must pump both outer sequences of hashes. However,
+there are `p+2` characters between these two sequences of hashes, and `|vwx|` must
+be less than `p+1`. Therefore we have a contradiction, and `R'` must not be
+context-free.
+
+Since `R'` is not context-free, it follows that the Rust's raw string literals
+must not be context-free.
diff --git a/src/grammar/testparser.py b/src/grammar/testparser.py
new file mode 100755
index 00000000000..37be41b935f
--- /dev/null
+++ b/src/grammar/testparser.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+# file at the top-level directory of this distribution and at
+# http://rust-lang.org/COPYRIGHT.
+#
+# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+# option. This file may not be copied, modified, or distributed
+# except according to those terms.
+
+# ignore-tidy-linelength
+
+import sys
+
+import os
+import subprocess
+import argparse
+
+# usage: testparser.py [-h] [-p PARSER [PARSER ...]] -s SOURCE_DIR
+
+# Parsers should read from stdin and return exit status 0 for a
+# successful parse, and nonzero for an unsuccessful parse
+
+parser = argparse.ArgumentParser()
+parser.add_argument('-p', '--parser', nargs='+')
+parser.add_argument('-s', '--source-dir', nargs=1, required=True)
+args = parser.parse_args(sys.argv[1:])
+
+total = 0
+ok = {}
+bad = {}
+for parser in args.parser:
+    ok[parser] = 0
+    bad[parser] = []
+devnull = open(os.devnull, 'w')
+print("\n")
+
+for base, dirs, files in os.walk(args.source_dir[0]):
+    for f in filter(lambda p: p.endswith('.rs'), files):
+        p = os.path.join(base, f)
+        parse_fail = 'parse-fail' in p
+        if sys.version_info.major == 3:
+            lines = open(p, encoding='utf-8').readlines()
+        else:
+            lines = open(p).readlines()
+        if any('ignore-test' in line or 'ignore-lexer-test' in line for line in lines):
+            continue
+        total += 1
+        for parser in args.parser:
+            if subprocess.call(parser, stdin=open(p), stderr=subprocess.STDOUT, stdout=devnull) == 0:
+                if parse_fail:
+                    bad[parser].append(p)
+                else:
+                    ok[parser] += 1
+            else:
+                if parse_fail:
+                    ok[parser] += 1
+                else:
+                    bad[parser].append(p)
+        parser_stats = ', '.join(['{}: {}'.format(parser, ok[parser]) for parser in args.parser])
+        sys.stdout.write("\033[K\r total: {}, {}, scanned {}"
+                         .format(total, os.path.relpath(parser_stats), os.path.relpath(p)))
+
+devnull.close()
+
+print("\n")
+
+for parser in args.parser:
+    filename = os.path.basename(parser) + '.bad'
+    print("writing {} files that did not yield the correct result with {} to {}".format(len(bad[parser]), parser, filename))
+    with open(filename, "w") as f:
+        for p in bad[parser]:
+            f.write(p)
+            f.write("\n")
diff --git a/src/grammar/tokens.h b/src/grammar/tokens.h
new file mode 100644
index 00000000000..081bd050259
--- /dev/null
+++ b/src/grammar/tokens.h
@@ -0,0 +1,91 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+enum Token {
+  SHL = 257, // Parser generators reserve 0-256 for char literals
+  SHR,
+  LE,
+  EQEQ,
+  NE,
+  GE,
+  ANDAND,
+  OROR,
+  SHLEQ,
+  SHREQ,
+  MINUSEQ,
+  ANDEQ,
+  OREQ,
+  PLUSEQ,
+  STAREQ,
+  SLASHEQ,
+  CARETEQ,
+  PERCENTEQ,
+  DOTDOT,
+  DOTDOTDOT,
+  MOD_SEP,
+  RARROW,
+  FAT_ARROW,
+  LIT_BYTE,
+  LIT_CHAR,
+  LIT_INTEGER,
+  LIT_FLOAT,
+  LIT_STR,
+  LIT_STR_RAW,
+  LIT_BYTE_STR,
+  LIT_BYTE_STR_RAW,
+  IDENT,
+  UNDERSCORE,
+  LIFETIME,
+
+  // keywords
+  SELF,
+  STATIC,
+  AS,
+  BREAK,
+  CRATE,
+  ELSE,
+  ENUM,
+  EXTERN,
+  FALSE,
+  FN,
+  FOR,
+  IF,
+  IMPL,
+  IN,
+  LET,
+  LOOP,
+  MATCH,
+  MOD,
+  MOVE,
+  MUT,
+  PRIV,
+  PUB,
+  REF,
+  RETURN,
+  STRUCT,
+  TRUE,
+  TRAIT,
+  TYPE,
+  UNSAFE,
+  USE,
+  WHILE,
+  CONTINUE,
+  PROC,
+  BOX,
+  CONST,
+  WHERE,
+  TYPEOF,
+  INNER_DOC_COMMENT,
+  OUTER_DOC_COMMENT,
+
+  SHEBANG,
+  SHEBANG_LINE,
+  STATIC_LIFETIME
+};
diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs
index 182a107e3f7..6d85183faf7 100644
--- a/src/liballoc/arc.rs
+++ b/src/liballoc/arc.rs
@@ -277,8 +277,7 @@ impl<T> Arc<T> {
         atomic::fence(Acquire);
 
         unsafe {
-            let ptr = *this.ptr;
-            let elem = ptr::read(&(*ptr).data);
+            let elem = ptr::read(&this.ptr.as_ref().data);
 
             // Make a weak pointer to clean up the implicit strong-weak reference
             let _weak = Weak { ptr: this.ptr };
@@ -306,7 +305,7 @@ impl<T> Arc<T> {
     /// ```
     #[stable(feature = "rc_raw", since = "1.17.0")]
     pub fn into_raw(this: Self) -> *const T {
-        let ptr = unsafe { &(**this.ptr).data as *const _ };
+        let ptr: *const T = &*this;
         mem::forget(this);
         ptr
     }
@@ -345,7 +344,7 @@ impl<T> Arc<T> {
         // `data` field from the pointer.
         let ptr = (ptr as *const u8).offset(-offset_of!(ArcInner<T>, data));
         Arc {
-            ptr: Shared::new(ptr as *const _),
+            ptr: Shared::new(ptr as *mut u8 as *mut _),
         }
     }
 }
@@ -452,17 +451,17 @@ impl<T: ?Sized> Arc<T> {
         // `ArcInner` structure itself is `Sync` because the inner data is
         // `Sync` as well, so we're ok loaning out an immutable pointer to these
         // contents.
-        unsafe { &**self.ptr }
+        unsafe { self.ptr.as_ref() }
     }
 
     // Non-inlined part of `drop`.
     #[inline(never)]
     unsafe fn drop_slow(&mut self) {
-        let ptr = self.ptr.as_mut_ptr();
+        let ptr = self.ptr.as_ptr();
 
         // Destroy the data at this time, even though we may not free the box
         // allocation itself (there may still be weak pointers lying around).
-        ptr::drop_in_place(&mut (*ptr).data);
+        ptr::drop_in_place(&mut self.ptr.as_mut().data);
 
         if self.inner().weak.fetch_sub(1, Release) == 1 {
             atomic::fence(Acquire);
@@ -488,9 +487,7 @@ impl<T: ?Sized> Arc<T> {
     /// assert!(!Arc::ptr_eq(&five, &other_five));
     /// ```
     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
-        let this_ptr: *const ArcInner<T> = *this.ptr;
-        let other_ptr: *const ArcInner<T> = *other.ptr;
-        this_ptr == other_ptr
+        this.ptr.as_ptr() == other.ptr.as_ptr()
     }
 }
 
@@ -621,7 +618,7 @@ impl<T: Clone> Arc<T> {
                 // here (due to zeroing) because data is no longer accessed by
                 // other threads (due to there being no more strong refs at this
                 // point).
-                let mut swap = Arc::new(ptr::read(&(**weak.ptr).data));
+                let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data));
                 mem::swap(this, &mut swap);
                 mem::forget(swap);
             }
@@ -634,8 +631,7 @@ impl<T: Clone> Arc<T> {
         // As with `get_mut()`, the unsafety is ok because our reference was
         // either unique to begin with, or became one upon cloning the contents.
         unsafe {
-            let inner = &mut *this.ptr.as_mut_ptr();
-            &mut inner.data
+            &mut this.ptr.as_mut().data
         }
     }
 }
@@ -677,8 +673,7 @@ impl<T: ?Sized> Arc<T> {
             // the Arc itself to be `mut`, so we're returning the only possible
             // reference to the inner data.
             unsafe {
-                let inner = &mut *this.ptr.as_mut_ptr();
-                Some(&mut inner.data)
+                Some(&mut this.ptr.as_mut().data)
             }
         } else {
             None
@@ -767,7 +762,18 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
         // > through this reference must obviously happened before), and an
         // > "acquire" operation before deleting the object.
         //
+        // In particular, while the contents of an Arc are usually immutable, it's
+        // possible to have interior writes to something like a Mutex<T>. Since a
+        // Mutex is not acquired when it is deleted, we can't rely on its
+        // synchronization logic to make writes in thread A visible to a destructor
+        // running in thread B.
+        //
+        // Also note that the Acquire fence here could probably be replaced with an
+        // Acquire load, which could improve performance in highly-contended
+        // situations. See [2].
+        //
         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
+        // [2]: (https://github.com/rust-lang/rust/pull/41714)
         atomic::fence(Acquire);
 
         unsafe {
@@ -867,7 +873,7 @@ impl<T: ?Sized> Weak<T> {
     #[inline]
     fn inner(&self) -> &ArcInner<T> {
         // See comments above for why this is "safe"
-        unsafe { &**self.ptr }
+        unsafe { self.ptr.as_ref() }
     }
 }
 
@@ -951,7 +957,7 @@ impl<T: ?Sized> Drop for Weak<T> {
     /// assert!(other_weak_foo.upgrade().is_none());
     /// ```
     fn drop(&mut self) {
-        let ptr = *self.ptr;
+        let ptr = self.ptr.as_ptr();
 
         // If we find out that we were the last weak pointer, then its time to
         // deallocate the data entirely. See the discussion in Arc::drop() about
@@ -1132,7 +1138,7 @@ impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T: ?Sized> fmt::Pointer for Arc<T> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        fmt::Pointer::fmt(&*self.ptr, f)
+        fmt::Pointer::fmt(&self.ptr, f)
     }
 }
 
diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs
index b03e3bb7a4b..fc6929f896e 100644
--- a/src/liballoc/boxed.rs
+++ b/src/liballoc/boxed.rs
@@ -156,7 +156,7 @@ fn make_place<T>() -> IntermediateBox<T> {
     let align = mem::align_of::<T>();
 
     let p = if size == 0 {
-        heap::EMPTY as *mut u8
+        mem::align_of::<T>() as *mut u8
     } else {
         let p = unsafe { heap::allocate(size, align) };
         if p.is_null() {
diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs
index 056af13016c..5ff21c86483 100644
--- a/src/liballoc/heap.rs
+++ b/src/liballoc/heap.rs
@@ -138,7 +138,9 @@ pub fn usable_size(size: usize, align: usize) -> usize {
 ///
 /// This preserves the non-null invariant for types like `Box<T>`. The address
 /// may overlap with non-zero-size memory allocations.
-pub const EMPTY: *mut () = 0x1 as *mut ();
+#[rustc_deprecated(since = "1.19", reason = "Use Unique/Shared::empty() instead")]
+#[unstable(feature = "heap_api", issue = "27700")]
+pub const EMPTY: *mut () = 1 as *mut ();
 
 /// The allocator for unique pointers.
 // This function must not unwind. If it does, MIR trans will fail.
@@ -147,7 +149,7 @@ pub const EMPTY: *mut () = 0x1 as *mut ();
 #[inline]
 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
     if size == 0 {
-        EMPTY as *mut u8
+        align as *mut u8
     } else {
         let ptr = allocate(size, align);
         if ptr.is_null() {
diff --git a/src/liballoc/raw_vec.rs b/src/liballoc/raw_vec.rs
index 6a53d3a9ca5..7edf07944ec 100644
--- a/src/liballoc/raw_vec.rs
+++ b/src/liballoc/raw_vec.rs
@@ -22,13 +22,13 @@ use core::cmp;
 /// involved. This type is excellent for building your own data structures like Vec and VecDeque.
 /// In particular:
 ///
-/// * Produces heap::EMPTY on zero-sized types
-/// * Produces heap::EMPTY on zero-length allocations
+/// * Produces Unique::empty() on zero-sized types
+/// * Produces Unique::empty() on zero-length allocations
 /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics)
 /// * Guards against 32-bit systems allocating more than isize::MAX bytes
 /// * Guards against overflowing your length
 /// * Aborts on OOM
-/// * Avoids freeing heap::EMPTY
+/// * Avoids freeing Unique::empty()
 /// * Contains a ptr::Unique and thus endows the user with all related benefits
 ///
 /// This type does not in anyway inspect the memory that it manages. When dropped it *will*
@@ -55,15 +55,13 @@ impl<T> RawVec<T> {
     /// it makes a RawVec with capacity `usize::MAX`. Useful for implementing
     /// delayed allocation.
     pub fn new() -> Self {
-        unsafe {
-            // !0 is usize::MAX. This branch should be stripped at compile time.
-            let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };
+        // !0 is usize::MAX. This branch should be stripped at compile time.
+        let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };
 
-            // heap::EMPTY doubles as "unallocated" and "zero-sized allocation"
-            RawVec {
-                ptr: Unique::new(heap::EMPTY as *mut T),
-                cap: cap,
-            }
+        // Unique::empty() doubles as "unallocated" and "zero-sized allocation"
+        RawVec {
+            ptr: Unique::empty(),
+            cap: cap,
         }
     }
 
@@ -101,7 +99,7 @@ impl<T> RawVec<T> {
 
             // handles ZSTs and `cap = 0` alike
             let ptr = if alloc_size == 0 {
-                heap::EMPTY as *mut u8
+                mem::align_of::<T>() as *mut u8
             } else {
                 let align = mem::align_of::<T>();
                 let ptr = if zeroed {
@@ -148,10 +146,10 @@ impl<T> RawVec<T> {
 
 impl<T> RawVec<T> {
     /// Gets a raw pointer to the start of the allocation. Note that this is
-    /// heap::EMPTY if `cap = 0` or T is zero-sized. In the former case, you must
+    /// Unique::empty() if `cap = 0` or T is zero-sized. In the former case, you must
     /// be careful.
     pub fn ptr(&self) -> *mut T {
-        *self.ptr
+        self.ptr.as_ptr()
     }
 
     /// Gets the capacity of the allocation.
@@ -563,7 +561,7 @@ unsafe impl<#[may_dangle] T> Drop for RawVec<T> {
 
             let num_bytes = elem_size * self.cap;
             unsafe {
-                heap::deallocate(*self.ptr as *mut _, num_bytes, align);
+                heap::deallocate(self.ptr() as *mut u8, num_bytes, align);
             }
         }
     }
diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs
index 38dc9145835..d6dbf77bfac 100644
--- a/src/liballoc/rc.rs
+++ b/src/liballoc/rc.rs
@@ -230,7 +230,7 @@ use core::cell::Cell;
 use core::cmp::Ordering;
 use core::fmt;
 use core::hash::{Hash, Hasher};
-use core::intrinsics::{abort, assume};
+use core::intrinsics::abort;
 use core::marker;
 use core::marker::Unsize;
 use core::mem::{self, align_of_val, forget, size_of, size_of_val, uninitialized};
@@ -358,7 +358,7 @@ impl<T> Rc<T> {
     /// ```
     #[stable(feature = "rc_raw", since = "1.17.0")]
     pub fn into_raw(this: Self) -> *const T {
-        let ptr = unsafe { &mut (*this.ptr.as_mut_ptr()).value as *const _ };
+        let ptr: *const T = &*this;
         mem::forget(this);
         ptr
     }
@@ -395,7 +395,11 @@ impl<T> Rc<T> {
     pub unsafe fn from_raw(ptr: *const T) -> Self {
         // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
         // `value` field from the pointer.
-        Rc { ptr: Shared::new((ptr as *const u8).offset(-offset_of!(RcBox<T>, value)) as *const _) }
+
+        let ptr = (ptr as *const u8).offset(-offset_of!(RcBox<T>, value));
+        Rc {
+            ptr: Shared::new(ptr as *mut u8 as *mut _)
+        }
     }
 }
 
@@ -451,7 +455,7 @@ impl<T> Rc<[T]> {
             // Free the original allocation without freeing its (moved) contents.
             box_free(Box::into_raw(value));
 
-            Rc { ptr: Shared::new(ptr as *const _) }
+            Rc { ptr: Shared::new(ptr as *mut _) }
         }
     }
 }
@@ -553,8 +557,9 @@ impl<T: ?Sized> Rc<T> {
     #[stable(feature = "rc_unique", since = "1.4.0")]
     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
         if Rc::is_unique(this) {
-            let inner = unsafe { &mut *this.ptr.as_mut_ptr() };
-            Some(&mut inner.value)
+            unsafe {
+                Some(&mut this.ptr.as_mut().value)
+            }
         } else {
             None
         }
@@ -578,9 +583,7 @@ impl<T: ?Sized> Rc<T> {
     /// assert!(!Rc::ptr_eq(&five, &other_five));
     /// ```
     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
-        let this_ptr: *const RcBox<T> = *this.ptr;
-        let other_ptr: *const RcBox<T> = *other.ptr;
-        this_ptr == other_ptr
+        this.ptr.as_ptr() == other.ptr.as_ptr()
     }
 }
 
@@ -623,7 +626,7 @@ impl<T: Clone> Rc<T> {
         } else if Rc::weak_count(this) != 0 {
             // Can just steal the data, all that's left is Weaks
             unsafe {
-                let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
+                let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
                 mem::swap(this, &mut swap);
                 swap.dec_strong();
                 // Remove implicit strong-weak ref (no need to craft a fake
@@ -637,8 +640,9 @@ impl<T: Clone> Rc<T> {
         // reference count is guaranteed to be 1 at this point, and we required
         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
         // reference to the inner value.
-        let inner = unsafe { &mut *this.ptr.as_mut_ptr() };
-        &mut inner.value
+        unsafe {
+            &mut this.ptr.as_mut().value
+        }
     }
 }
 
@@ -683,12 +687,12 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
     /// ```
     fn drop(&mut self) {
         unsafe {
-            let ptr = self.ptr.as_mut_ptr();
+            let ptr = self.ptr.as_ptr();
 
             self.dec_strong();
             if self.strong() == 0 {
                 // destroy the contained object
-                ptr::drop_in_place(&mut (*ptr).value);
+                ptr::drop_in_place(self.ptr.as_mut());
 
                 // remove the implicit "strong weak" pointer now that we've
                 // destroyed the contents.
@@ -925,7 +929,7 @@ impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T: ?Sized> fmt::Pointer for Rc<T> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        fmt::Pointer::fmt(&*self.ptr, f)
+        fmt::Pointer::fmt(&self.ptr, f)
     }
 }
 
@@ -1067,7 +1071,7 @@ impl<T: ?Sized> Drop for Weak<T> {
     /// ```
     fn drop(&mut self) {
         unsafe {
-            let ptr = *self.ptr;
+            let ptr = self.ptr.as_ptr();
 
             self.dec_weak();
             // the weak count starts at 1, and will only go to zero if all
@@ -1175,12 +1179,7 @@ impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
     #[inline(always)]
     fn inner(&self) -> &RcBox<T> {
         unsafe {
-            // Safe to assume this here, as if it weren't true, we'd be breaking
-            // the contract anyway.
-            // This allows the null check to be elided in the destructor if we
-            // manipulated the reference count in the same function.
-            assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
-            &(**self.ptr)
+            self.ptr.as_ref()
         }
     }
 }
@@ -1189,12 +1188,7 @@ impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
     #[inline(always)]
     fn inner(&self) -> &RcBox<T> {
         unsafe {
-            // Safe to assume this here, as if it weren't true, we'd be breaking
-            // the contract anyway.
-            // This allows the null check to be elided in the destructor if we
-            // manipulated the reference count in the same function.
-            assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
-            &(**self.ptr)
+            self.ptr.as_ref()
         }
     }
 }
diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs
index a3cfc15895e..321fa2edd56 100644
--- a/src/libarena/lib.rs
+++ b/src/libarena/lib.rs
@@ -31,7 +31,6 @@
 #![feature(alloc)]
 #![feature(core_intrinsics)]
 #![feature(dropck_eyepatch)]
-#![feature(heap_api)]
 #![feature(generic_param_attrs)]
 #![feature(staged_api)]
 #![cfg_attr(test, feature(test))]
@@ -48,7 +47,6 @@ use std::mem;
 use std::ptr;
 use std::slice;
 
-use alloc::heap;
 use alloc::raw_vec::RawVec;
 
 /// An arena that can hold objects of only one type.
@@ -140,7 +138,7 @@ impl<T> TypedArena<T> {
         unsafe {
             if mem::size_of::<T>() == 0 {
                 self.ptr.set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1) as *mut T);
-                let ptr = heap::EMPTY as *mut T;
+                let ptr = mem::align_of::<T>() as *mut T;
                 // Don't drop the object. This `write` is equivalent to `forget`.
                 ptr::write(ptr, object);
                 &mut *ptr
diff --git a/src/libcollections/btree/node.rs b/src/libcollections/btree/node.rs
index e9bc29118d5..52cdd39d8f9 100644
--- a/src/libcollections/btree/node.rs
+++ b/src/libcollections/btree/node.rs
@@ -152,12 +152,12 @@ impl<K, V> BoxedNode<K, V> {
     }
 
     unsafe fn from_ptr(ptr: NonZero<*const LeafNode<K, V>>) -> Self {
-        BoxedNode { ptr: Unique::new(*ptr as *mut LeafNode<K, V>) }
+        BoxedNode { ptr: Unique::new(ptr.get() as *mut LeafNode<K, V>) }
     }
 
     fn as_ptr(&self) -> NonZero<*const LeafNode<K, V>> {
         unsafe {
-            NonZero::new(*self.ptr as *const LeafNode<K, V>)
+            NonZero::new(self.ptr.as_ptr())
         }
     }
 }
@@ -241,7 +241,7 @@ impl<K, V> Root<K, V> {
     pub fn pop_level(&mut self) {
         debug_assert!(self.height > 0);
 
-        let top = *self.node.ptr as *mut u8;
+        let top = self.node.ptr.as_ptr() as *mut u8;
 
         self.node = unsafe {
             BoxedNode::from_ptr(self.as_mut()
@@ -308,7 +308,7 @@ unsafe impl<K: Send, V: Send, Type> Send
 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
     fn as_internal(&self) -> &InternalNode<K, V> {
         unsafe {
-            &*(*self.node as *const InternalNode<K, V>)
+            &*(self.node.get() as *const InternalNode<K, V>)
         }
     }
 }
@@ -316,7 +316,7 @@ impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
     fn as_internal_mut(&mut self) -> &mut InternalNode<K, V> {
         unsafe {
-            &mut *(*self.node as *mut InternalNode<K, V>)
+            &mut *(self.node.get() as *mut InternalNode<K, V>)
         }
     }
 }
@@ -358,7 +358,7 @@ impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
 
     fn as_leaf(&self) -> &LeafNode<K, V> {
         unsafe {
-            &**self.node
+            &*self.node.get()
         }
     }
 
@@ -510,7 +510,7 @@ impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
 
     fn as_leaf_mut(&mut self) -> &mut LeafNode<K, V> {
         unsafe {
-            &mut *(*self.node as *mut LeafNode<K, V>)
+            &mut *(self.node.get() as *mut LeafNode<K, V>)
         }
     }
 
@@ -1253,13 +1253,13 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::
                 }
 
                 heap::deallocate(
-                    *right_node.node as *mut u8,
+                    right_node.node.get() as *mut u8,
                     mem::size_of::<InternalNode<K, V>>(),
                     mem::align_of::<InternalNode<K, V>>()
                 );
             } else {
                 heap::deallocate(
-                    *right_node.node as *mut u8,
+                    right_node.node.get() as *mut u8,
                     mem::size_of::<LeafNode<K, V>>(),
                     mem::align_of::<LeafNode<K, V>>()
                 );
diff --git a/src/libcollections/linked_list.rs b/src/libcollections/linked_list.rs
index adfd91bec48..ae258083546 100644
--- a/src/libcollections/linked_list.rs
+++ b/src/libcollections/linked_list.rs
@@ -161,7 +161,7 @@ impl<T> LinkedList<T> {
 
             match self.head {
                 None => self.tail = node,
-                Some(head) => (*head.as_mut_ptr()).prev = node,
+                Some(mut head) => head.as_mut().prev = node,
             }
 
             self.head = node;
@@ -173,12 +173,12 @@ impl<T> LinkedList<T> {
     #[inline]
     fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
         self.head.map(|node| unsafe {
-            let node = Box::from_raw(node.as_mut_ptr());
+            let node = Box::from_raw(node.as_ptr());
             self.head = node.next;
 
             match self.head {
                 None => self.tail = None,
-                Some(head) => (*head.as_mut_ptr()).prev = None,
+                Some(mut head) => head.as_mut().prev = None,
             }
 
             self.len -= 1;
@@ -196,7 +196,7 @@ impl<T> LinkedList<T> {
 
             match self.tail {
                 None => self.head = node,
-                Some(tail) => (*tail.as_mut_ptr()).next = node,
+                Some(mut tail) => tail.as_mut().next = node,
             }
 
             self.tail = node;
@@ -208,12 +208,12 @@ impl<T> LinkedList<T> {
     #[inline]
     fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
         self.tail.map(|node| unsafe {
-            let node = Box::from_raw(node.as_mut_ptr());
+            let node = Box::from_raw(node.as_ptr());
             self.tail = node.prev;
 
             match self.tail {
                 None => self.head = None,
-                Some(tail) => (*tail.as_mut_ptr()).next = None,
+                Some(mut tail) => tail.as_mut().next = None,
             }
 
             self.len -= 1;
@@ -285,11 +285,11 @@ impl<T> LinkedList<T> {
     pub fn append(&mut self, other: &mut Self) {
         match self.tail {
             None => mem::swap(self, other),
-            Some(tail) => {
-                if let Some(other_head) = other.head.take() {
+            Some(mut tail) => {
+                if let Some(mut other_head) = other.head.take() {
                     unsafe {
-                        (*tail.as_mut_ptr()).next = Some(other_head);
-                        (*other_head.as_mut_ptr()).prev = Some(tail);
+                        tail.as_mut().next = Some(other_head);
+                        other_head.as_mut().prev = Some(tail);
                     }
 
                     self.tail = other.tail.take();
@@ -477,7 +477,9 @@ impl<T> LinkedList<T> {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn front(&self) -> Option<&T> {
-        self.head.map(|node| unsafe { &(**node).element })
+        unsafe {
+            self.head.as_ref().map(|node| &node.as_ref().element)
+        }
     }
 
     /// Provides a mutable reference to the front element, or `None` if the list
@@ -503,7 +505,9 @@ impl<T> LinkedList<T> {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn front_mut(&mut self) -> Option<&mut T> {
-        self.head.map(|node| unsafe { &mut (*node.as_mut_ptr()).element })
+        unsafe {
+            self.head.as_mut().map(|node| &mut node.as_mut().element)
+        }
     }
 
     /// Provides a reference to the back element, or `None` if the list is
@@ -523,7 +527,9 @@ impl<T> LinkedList<T> {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn back(&self) -> Option<&T> {
-        self.tail.map(|node| unsafe { &(**node).element })
+        unsafe {
+            self.tail.as_ref().map(|node| &node.as_ref().element)
+        }
     }
 
     /// Provides a mutable reference to the back element, or `None` if the list
@@ -549,7 +555,9 @@ impl<T> LinkedList<T> {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn back_mut(&mut self) -> Option<&mut T> {
-        self.tail.map(|node| unsafe { &mut (*node.as_mut_ptr()).element })
+        unsafe {
+            self.tail.as_mut().map(|node| &mut node.as_mut().element)
+        }
     }
 
     /// Adds an element first in the list.
@@ -694,9 +702,9 @@ impl<T> LinkedList<T> {
         let second_part_head;
 
         unsafe {
-            second_part_head = (*split_node.unwrap().as_mut_ptr()).next.take();
-            if let Some(head) = second_part_head {
-                (*head.as_mut_ptr()).prev = None;
+            second_part_head = split_node.unwrap().as_mut().next.take();
+            if let Some(mut head) = second_part_head {
+                head.as_mut().prev = None;
             }
         }
 
@@ -788,7 +796,8 @@ impl<'a, T> Iterator for Iter<'a, T> {
             None
         } else {
             self.head.map(|node| unsafe {
-                let node = &**node;
+                // Need an unbound lifetime to get 'a
+                let node = &*node.as_ptr();
                 self.len -= 1;
                 self.head = node.next;
                 &node.element
@@ -810,7 +819,8 @@ impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
             None
         } else {
             self.tail.map(|node| unsafe {
-                let node = &**node;
+                // Need an unbound lifetime to get 'a
+                let node = &*node.as_ptr();
                 self.len -= 1;
                 self.tail = node.prev;
                 &node.element
@@ -835,7 +845,8 @@ impl<'a, T> Iterator for IterMut<'a, T> {
             None
         } else {
             self.head.map(|node| unsafe {
-                let node = &mut *node.as_mut_ptr();
+                // Need an unbound lifetime to get 'a
+                let node = &mut *node.as_ptr();
                 self.len -= 1;
                 self.head = node.next;
                 &mut node.element
@@ -857,7 +868,8 @@ impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
             None
         } else {
             self.tail.map(|node| unsafe {
-                let node = &mut *node.as_mut_ptr();
+                // Need an unbound lifetime to get 'a
+                let node = &mut *node.as_ptr();
                 self.len -= 1;
                 self.tail = node.prev;
                 &mut node.element
@@ -903,8 +915,8 @@ impl<'a, T> IterMut<'a, T> {
     pub fn insert_next(&mut self, element: T) {
         match self.head {
             None => self.list.push_back(element),
-            Some(head) => unsafe {
-                let prev = match (**head).prev {
+            Some(mut head) => unsafe {
+                let mut prev = match head.as_ref().prev {
                     None => return self.list.push_front(element),
                     Some(prev) => prev,
                 };
@@ -915,8 +927,8 @@ impl<'a, T> IterMut<'a, T> {
                     element: element,
                 })));
 
-                (*prev.as_mut_ptr()).next = node;
-                (*head.as_mut_ptr()).prev = node;
+                prev.as_mut().next = node;
+                head.as_mut().prev = node;
 
                 self.list.len += 1;
             },
@@ -948,7 +960,9 @@ impl<'a, T> IterMut<'a, T> {
         if self.len == 0 {
             None
         } else {
-            self.head.map(|node| unsafe { &mut (*node.as_mut_ptr()).element })
+            unsafe {
+                self.head.as_mut().map(|node| &mut node.as_mut().element)
+            }
         }
     }
 }
@@ -1276,21 +1290,21 @@ mod tests {
                     assert_eq!(0, list.len);
                     return;
                 }
-                Some(node) => node_ptr = &**node,
+                Some(node) => node_ptr = &*node.as_ptr(),
             }
             loop {
                 match (last_ptr, node_ptr.prev) {
                     (None, None) => {}
                     (None, _) => panic!("prev link for head"),
                     (Some(p), Some(pptr)) => {
-                        assert_eq!(p as *const Node<T>, *pptr as *const Node<T>);
+                        assert_eq!(p as *const Node<T>, pptr.as_ptr() as *const Node<T>);
                     }
                     _ => panic!("prev link is none, not good"),
                 }
                 match node_ptr.next {
                     Some(next) => {
                         last_ptr = Some(node_ptr);
-                        node_ptr = &**next;
+                        node_ptr = &*next.as_ptr();
                         len += 1;
                     }
                     None => {
diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs
index 2eef132374e..3efda1faa3b 100644
--- a/src/libcollections/slice.rs
+++ b/src/libcollections/slice.rs
@@ -1341,6 +1341,9 @@ impl<T> [T] {
     ///
     /// The length of `src` must be the same as `self`.
     ///
+    /// If `src` implements `Copy`, it can be more performant to use
+    /// [`copy_from_slice`].
+    ///
     /// # Panics
     ///
     /// This function will panic if the two slices have different lengths.
@@ -1354,6 +1357,8 @@ impl<T> [T] {
     /// dst.clone_from_slice(&src);
     /// assert!(dst == [1, 2, 3]);
     /// ```
+    ///
+    /// [`copy_from_slice`]: #method.copy_from_slice
     #[stable(feature = "clone_from_slice", since = "1.7.0")]
     pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
         core_slice::SliceExt::clone_from_slice(self, src)
@@ -1363,6 +1368,8 @@ impl<T> [T] {
     ///
     /// The length of `src` must be the same as `self`.
     ///
+    /// If `src` does not implement `Copy`, use [`clone_from_slice`].
+    ///
     /// # Panics
     ///
     /// This function will panic if the two slices have different lengths.
@@ -1376,6 +1383,8 @@ impl<T> [T] {
     /// dst.copy_from_slice(&src);
     /// assert_eq!(src, dst);
     /// ```
+    ///
+    /// [`clone_from_slice`]: #method.clone_from_slice
     #[stable(feature = "copy_from_slice", since = "1.9.0")]
     pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
         core_slice::SliceExt::copy_from_slice(self, src)
diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs
index fc5de70e983..7ec5c29de6b 100644
--- a/src/libcollections/vec.rs
+++ b/src/libcollections/vec.rs
@@ -67,7 +67,6 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 use alloc::boxed::Box;
-use alloc::heap::EMPTY;
 use alloc::raw_vec::RawVec;
 use borrow::ToOwned;
 use borrow::Cow;
@@ -1776,9 +1775,9 @@ impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
         // A common case is passing a vector into a function which immediately
         // re-collects into a vector. We can short circuit this if the IntoIter
         // has not been advanced at all.
-        if *iterator.buf == iterator.ptr as *mut T {
+        if iterator.buf.as_ptr() as *const _ == iterator.ptr {
             unsafe {
-                let vec = Vec::from_raw_parts(*iterator.buf as *mut T,
+                let vec = Vec::from_raw_parts(iterator.buf.as_ptr(),
                                               iterator.len(),
                                               iterator.cap);
                 mem::forget(iterator);
@@ -2192,7 +2191,8 @@ impl<T> Iterator for IntoIter<T> {
                     self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
 
                     // Use a non-null pointer value
-                    Some(ptr::read(EMPTY as *mut T))
+                    // (self.ptr might be null because of wrapping)
+                    Some(ptr::read(1 as *mut T))
                 } else {
                     let old = self.ptr;
                     self.ptr = self.ptr.offset(1);
@@ -2231,7 +2231,8 @@ impl<T> DoubleEndedIterator for IntoIter<T> {
                     self.end = arith_offset(self.end as *const i8, -1) as *mut T;
 
                     // Use a non-null pointer value
-                    Some(ptr::read(EMPTY as *mut T))
+                    // (self.end might be null because of wrapping)
+                    Some(ptr::read(1 as *mut T))
                 } else {
                     self.end = self.end.offset(-1);
 
@@ -2269,7 +2270,7 @@ unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
         for _x in self.by_ref() {}
 
         // RawVec handles deallocation
-        let _ = unsafe { RawVec::from_raw_parts(self.buf.as_mut_ptr(), self.cap) };
+        let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
     }
 }
 
@@ -2334,7 +2335,7 @@ impl<'a, T> Drop for Drain<'a, T> {
 
         if self.tail_len > 0 {
             unsafe {
-                let source_vec = &mut *self.vec.as_mut_ptr();
+                let source_vec = self.vec.as_mut();
                 // memmove back untouched tail, update to new length
                 let start = source_vec.len();
                 let tail = self.tail_start;
@@ -2456,8 +2457,7 @@ impl<'a, I: Iterator> Drop for Splice<'a, I> {
 
         unsafe {
             if self.drain.tail_len == 0 {
-                let vec = &mut *self.drain.vec.as_mut_ptr();
-                vec.extend(self.replace_with.by_ref());
+                self.drain.vec.as_mut().extend(self.replace_with.by_ref());
                 return
             }
 
@@ -2498,7 +2498,7 @@ impl<'a, T> Drain<'a, T> {
     /// Fill that range as much as possible with new elements from the `replace_with` iterator.
     /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.)
     unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
-        let vec = &mut *self.vec.as_mut_ptr();
+        let vec = self.vec.as_mut();
         let range_start = vec.len;
         let range_end = self.tail_start;
         let range_slice = slice::from_raw_parts_mut(
@@ -2518,7 +2518,7 @@ impl<'a, T> Drain<'a, T> {
 
     /// Make room for inserting more elements before the tail.
     unsafe fn move_tail(&mut self, extra_capacity: usize) {
-        let vec = &mut *self.vec.as_mut_ptr();
+        let vec = self.vec.as_mut();
         let used_capacity = self.tail_start + self.tail_len;
         vec.buf.reserve(used_capacity, extra_capacity);
 
diff --git a/src/libcollections/vec_deque.rs b/src/libcollections/vec_deque.rs
index 079d3acf376..e826c9432b5 100644
--- a/src/libcollections/vec_deque.rs
+++ b/src/libcollections/vec_deque.rs
@@ -2160,7 +2160,7 @@ impl<'a, T: 'a> Drop for Drain<'a, T> {
     fn drop(&mut self) {
         for _ in self.by_ref() {}
 
-        let source_deque = unsafe { &mut *self.deque.as_mut_ptr() };
+        let source_deque = unsafe { self.deque.as_mut() };
 
         // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
         //
diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs
index f62057b3a52..7886f90b66e 100644
--- a/src/libcore/cell.rs
+++ b/src/libcore/cell.rs
@@ -132,7 +132,6 @@
 //! use std::cell::Cell;
 //! use std::ptr::Shared;
 //! use std::intrinsics::abort;
-//! use std::intrinsics::assume;
 //!
 //! struct Rc<T: ?Sized> {
 //!     ptr: Shared<RcBox<T>>
@@ -171,8 +170,7 @@
 //! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
 //!    fn inner(&self) -> &RcBox<T> {
 //!        unsafe {
-//!            assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
-//!            &(**self.ptr)
+//!            self.ptr.as_ref()
 //!        }
 //!    }
 //! }
diff --git a/src/libcore/nonzero.rs b/src/libcore/nonzero.rs
index d7382501bc3..d93085e96db 100644
--- a/src/libcore/nonzero.rs
+++ b/src/libcore/nonzero.rs
@@ -13,7 +13,7 @@
             reason = "needs an RFC to flesh out the design",
             issue = "27730")]
 
-use ops::{CoerceUnsized, Deref};
+use ops::CoerceUnsized;
 
 /// Unsafe trait to indicate what types are usable with the NonZero struct
 pub unsafe trait Zeroable {}
@@ -46,15 +46,10 @@ impl<T: Zeroable> NonZero<T> {
     pub const unsafe fn new(inner: T) -> NonZero<T> {
         NonZero(inner)
     }
-}
-
-impl<T: Zeroable> Deref for NonZero<T> {
-    type Target = T;
 
-    #[inline]
-    fn deref(&self) -> &T {
-        let NonZero(ref inner) = *self;
-        inner
+    /// Gets the inner value.
+    pub fn get(self) -> T {
+        self.0
     }
 }
 
diff --git a/src/libcore/option.rs b/src/libcore/option.rs
index 1a48f277625..515f49d6f0b 100644
--- a/src/libcore/option.rs
+++ b/src/libcore/option.rs
@@ -66,14 +66,14 @@
 //! not ([`None`]).
 //!
 //! ```
-//! let optional: Option<Box<i32>> = None;
-//! check_optional(&optional);
+//! let optional = None;
+//! check_optional(optional);
 //!
-//! let optional: Option<Box<i32>> = Some(Box::new(9000));
-//! check_optional(&optional);
+//! let optional = Some(Box::new(9000));
+//! check_optional(optional);
 //!
-//! fn check_optional(optional: &Option<Box<i32>>) {
-//!     match *optional {
+//! fn check_optional(optional: Option<Box<i32>>) {
+//!     match optional {
 //!         Some(ref p) => println!("has value {}", p),
 //!         None => println!("has no value"),
 //!     }
diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs
index 115326bb916..a60abefc076 100644
--- a/src/libcore/ptr.rs
+++ b/src/libcore/ptr.rs
@@ -17,7 +17,7 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 use intrinsics;
-use ops::{CoerceUnsized, Deref};
+use ops::CoerceUnsized;
 use fmt;
 use hash;
 use marker::{PhantomData, Unsize};
@@ -957,13 +957,25 @@ impl<T: ?Sized> PartialOrd for *mut T {
 }
 
 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
-/// of this wrapper owns the referent. This in turn implies that the
-/// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
-/// `*mut T` (which conveys no particular ownership semantics).  It
-/// also implies that the referent of the pointer should not be
-/// modified without a unique path to the `Unique` reference. Useful
-/// for building abstractions like `Vec<T>` or `Box<T>`, which
-/// internally use raw pointers to manage the memory that they own.
+/// of this wrapper owns the referent. Useful for building abstractions like
+/// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
+///
+/// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
+/// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
+/// the kind of strong aliasing guarantees an instance of `T` can expect:
+/// the referent of the pointer should not be modified without a unique path to
+/// its owning Unique.
+///
+/// If you're uncertain of whether it's correct to use `Unique` for your purposes,
+/// consider using `Shared`, which has weaker semantics.
+///
+/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
+/// is never dereferenced. This is so that enums may use this forbidden value
+/// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
+/// However the pointer may still dangle if it isn't dereferenced.
+///
+/// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
+/// for any type which upholds Unique's aliasing requirements.
 #[allow(missing_debug_implementations)]
 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
            issue = "27730")]
@@ -992,6 +1004,20 @@ unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
 
 #[unstable(feature = "unique", issue = "27730")]
+impl<T: Sized> Unique<T> {
+    /// Creates a new `Shared` that is dangling, but well-aligned.
+    ///
+    /// This is useful for initializing types which lazily allocate, like
+    /// `Vec::new` does.
+    pub fn empty() -> Self {
+        unsafe {
+            let ptr = mem::align_of::<T>() as *mut T;
+            Unique::new(ptr)
+        }
+    }
+}
+
+#[unstable(feature = "unique", issue = "27730")]
 impl<T: ?Sized> Unique<T> {
     /// Creates a new `Unique`.
     ///
@@ -1002,41 +1028,72 @@ impl<T: ?Sized> Unique<T> {
         Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
     }
 
+    /// Acquires the underlying `*mut` pointer.
+    pub fn as_ptr(self) -> *mut T {
+        self.pointer.get() as *mut T
+    }
+
     /// Dereferences the content.
-    pub unsafe fn get(&self) -> &T {
-        &**self.pointer
+    ///
+    /// The resulting lifetime is bound to self so this behaves "as if"
+    /// it were actually an instance of T that is getting borrowed. If a longer
+    /// (unbound) lifetime is needed, use `&*my_ptr.ptr()`.
+    pub unsafe fn as_ref(&self) -> &T {
+        &*self.as_ptr()
     }
 
     /// Mutably dereferences the content.
-    pub unsafe fn get_mut(&mut self) -> &mut T {
-        &mut ***self
+    ///
+    /// The resulting lifetime is bound to self so this behaves "as if"
+    /// it were actually an instance of T that is getting borrowed. If a longer
+    /// (unbound) lifetime is needed, use `&mut *my_ptr.ptr()`.
+    pub unsafe fn as_mut(&mut self) -> &mut T {
+        &mut *self.as_ptr()
     }
 }
 
-#[unstable(feature = "unique", issue = "27730")]
-impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
-
-#[unstable(feature = "unique", issue= "27730")]
-impl<T:?Sized> Deref for Unique<T> {
-    type Target = *mut T;
-
-    #[inline]
-    fn deref(&self) -> &*mut T {
-        unsafe { mem::transmute(&*self.pointer) }
+#[unstable(feature = "shared", issue = "27730")]
+impl<T: ?Sized> Clone for Unique<T> {
+    fn clone(&self) -> Self {
+        *self
     }
 }
 
+#[unstable(feature = "shared", issue = "27730")]
+impl<T: ?Sized> Copy for Unique<T> { }
+
+#[unstable(feature = "unique", issue = "27730")]
+impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
+
 #[unstable(feature = "unique", issue = "27730")]
-impl<T> fmt::Pointer for Unique<T> {
+impl<T: ?Sized> fmt::Pointer for Unique<T> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        fmt::Pointer::fmt(&*self.pointer, f)
+        fmt::Pointer::fmt(&self.as_ptr(), f)
     }
 }
 
-/// A wrapper around a raw non-null `*mut T` that indicates that the possessor
+/// A wrapper around a raw `*mut T` that indicates that the possessor
 /// of this wrapper has shared ownership of the referent. Useful for
-/// building abstractions like `Rc<T>` or `Arc<T>`, which internally
-/// use raw pointers to manage the memory that they own.
+/// building abstractions like `Rc<T>`, `Arc<T>`, or doubly-linked lists, which
+/// internally use aliased raw pointers to manage the memory that they own.
+///
+/// This is similar to `Unique`, except that it doesn't make any aliasing
+/// guarantees, and doesn't derive Send and Sync. Note that unlike `&T`,
+/// Shared has no special mutability requirements. Shared may mutate data
+/// aliased by other Shared pointers. More precise rules require Rust to
+/// develop an actual aliasing model.
+///
+/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
+/// is never dereferenced. This is so that enums may use this forbidden value
+/// as a discriminant -- `Option<Shared<T>>` has the same size as `Shared<T>`.
+/// However the pointer may still dangle if it isn't dereferenced.
+///
+/// Unlike `*mut T`, `Shared<T>` is covariant over `T`. If this is incorrect
+/// for your use case, you should include some PhantomData in your type to
+/// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
+/// Usually this won't be necessary; covariance is correct for Rc, Arc, and LinkedList
+/// because they provide a public API that follows the normal shared XOR mutable
+/// rules of Rust.
 #[allow(missing_debug_implementations)]
 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
            issue = "27730")]
@@ -1061,22 +1118,58 @@ impl<T: ?Sized> !Send for Shared<T> { }
 impl<T: ?Sized> !Sync for Shared<T> { }
 
 #[unstable(feature = "shared", issue = "27730")]
+impl<T: Sized> Shared<T> {
+    /// Creates a new `Shared` that is dangling, but well-aligned.
+    ///
+    /// This is useful for initializing types which lazily allocate, like
+    /// `Vec::new` does.
+    pub fn empty() -> Self {
+        unsafe {
+            let ptr = mem::align_of::<T>() as *mut T;
+            Shared::new(ptr)
+        }
+    }
+}
+
+#[unstable(feature = "shared", issue = "27730")]
 impl<T: ?Sized> Shared<T> {
     /// Creates a new `Shared`.
     ///
     /// # Safety
     ///
     /// `ptr` must be non-null.
-    pub unsafe fn new(ptr: *const T) -> Self {
+    pub unsafe fn new(ptr: *mut T) -> Self {
         Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
     }
-}
 
-#[unstable(feature = "shared", issue = "27730")]
-impl<T: ?Sized> Shared<T> {
+    /// Acquires the underlying `*mut` pointer.
+    pub fn as_ptr(self) -> *mut T {
+        self.pointer.get() as *mut T
+    }
+
+    /// Dereferences the content.
+    ///
+    /// The resulting lifetime is bound to self so this behaves "as if"
+    /// it were actually an instance of T that is getting borrowed. If a longer
+    /// (unbound) lifetime is needed, use `&*my_ptr.ptr()`.
+    pub unsafe fn as_ref(&self) -> &T {
+        &*self.as_ptr()
+    }
+
+    /// Mutably dereferences the content.
+    ///
+    /// The resulting lifetime is bound to self so this behaves "as if"
+    /// it were actually an instance of T that is getting borrowed. If a longer
+    /// (unbound) lifetime is needed, use `&mut *my_ptr.ptr_mut()`.
+    pub unsafe fn as_mut(&mut self) -> &mut T {
+        &mut *self.as_ptr()
+    }
+
     /// Acquires the underlying pointer as a `*mut` pointer.
+    #[rustc_deprecated(since = "1.19", reason = "renamed to `as_ptr` for ergonomics/consistency")]
+    #[unstable(feature = "shared", issue = "27730")]
     pub unsafe fn as_mut_ptr(&self) -> *mut T {
-        **self as _
+        self.as_ptr()
     }
 }
 
@@ -1094,18 +1187,8 @@ impl<T: ?Sized> Copy for Shared<T> { }
 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
 
 #[unstable(feature = "shared", issue = "27730")]
-impl<T: ?Sized> Deref for Shared<T> {
-    type Target = *const T;
-
-    #[inline]
-    fn deref(&self) -> &*const T {
-        unsafe { mem::transmute(&*self.pointer) }
-    }
-}
-
-#[unstable(feature = "shared", issue = "27730")]
-impl<T> fmt::Pointer for Shared<T> {
+impl<T: ?Sized> fmt::Pointer for Shared<T> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        fmt::Pointer::fmt(&*self.pointer, f)
+        fmt::Pointer::fmt(&self.as_ptr(), f)
     }
 }
diff --git a/src/libcore/tests/nonzero.rs b/src/libcore/tests/nonzero.rs
index 7a367ddeec8..588fffda35f 100644
--- a/src/libcore/tests/nonzero.rs
+++ b/src/libcore/tests/nonzero.rs
@@ -31,12 +31,12 @@ fn test_match_on_nonzero_option() {
         NonZero::new(42)
     });
     match a {
-        Some(val) => assert_eq!(*val, 42),
+        Some(val) => assert_eq!(val.get(), 42),
         None => panic!("unexpected None while matching on Some(NonZero(_))")
     }
 
     match unsafe { Some(NonZero::new(43)) } {
-        Some(val) => assert_eq!(*val, 43),
+        Some(val) => assert_eq!(val.get(), 43),
         None => panic!("unexpected None while matching on Some(NonZero(_))")
     }
 }
diff --git a/src/libcore/tests/ptr.rs b/src/libcore/tests/ptr.rs
index 7f6f472bfbb..e28dc6a6881 100644
--- a/src/libcore/tests/ptr.rs
+++ b/src/libcore/tests/ptr.rs
@@ -166,10 +166,10 @@ fn test_set_memory() {
 
 #[test]
 fn test_unsized_unique() {
-    let xs: &mut [i32] = &mut [1, 2, 3];
-    let ptr = unsafe { Unique::new(xs as *mut [i32]) };
-    let ys = unsafe { &mut **ptr };
-    let zs: &mut [i32] = &mut [1, 2, 3];
+    let xs: &[i32] = &[1, 2, 3];
+    let ptr = unsafe { Unique::new(xs as *const [i32] as *mut [i32]) };
+    let ys = unsafe { ptr.as_ref() };
+    let zs: &[i32] = &[1, 2, 3];
     assert!(ys == zs);
 }
 
diff --git a/src/libflate/lib.rs b/src/libflate/lib.rs
index dedec7b1609..3619be82829 100644
--- a/src/libflate/lib.rs
+++ b/src/libflate/lib.rs
@@ -62,14 +62,14 @@ pub struct Bytes {
 impl Deref for Bytes {
     type Target = [u8];
     fn deref(&self) -> &[u8] {
-        unsafe { slice::from_raw_parts(*self.ptr, self.len) }
+        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
     }
 }
 
 impl Drop for Bytes {
     fn drop(&mut self) {
         unsafe {
-            libc::free(*self.ptr as *mut _);
+            libc::free(self.ptr.as_ptr() as *mut _);
         }
     }
 }
diff --git a/src/liblibc b/src/liblibc
-Subproject c34a802d1eb037b44c5252078c7270b5472e0f6
+Subproject 03562b0cb26a00f49d4eaf18ca3e49608110b0c
diff --git a/src/libpanic_unwind/windows.rs b/src/libpanic_unwind/windows.rs
index fd8429d262e..a7e90071cea 100644
--- a/src/libpanic_unwind/windows.rs
+++ b/src/libpanic_unwind/windows.rs
@@ -12,11 +12,11 @@
 #![allow(dead_code)]
 #![cfg(windows)]
 
-use libc::{c_long, c_ulong, c_ulonglong, c_void};
+use libc::{c_long, c_ulong, c_void};
 
 pub type DWORD = c_ulong;
 pub type LONG = c_long;
-pub type ULONG_PTR = c_ulonglong;
+pub type ULONG_PTR = usize;
 pub type LPVOID = *mut c_void;
 
 pub const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15;
diff --git a/src/librustc/dep_graph/dep_node.rs b/src/librustc/dep_graph/dep_node.rs
index 712ada4ec65..25fc5b7a4f6 100644
--- a/src/librustc/dep_graph/dep_node.rs
+++ b/src/librustc/dep_graph/dep_node.rs
@@ -51,6 +51,9 @@ pub enum DepNode<D: Clone + Debug> {
     // in an extern crate.
     MetaData(D),
 
+    // Represents some piece of metadata global to its crate.
+    GlobalMetaData(D, GlobalMetaDataKind),
+
     // Represents some artifact that we save to disk. Note that these
     // do not have a def-id as part of their identifier.
     WorkProduct(Arc<WorkProductId>),
@@ -79,8 +82,8 @@ pub enum DepNode<D: Clone + Debug> {
     MirKeys,
     LateLintCheck,
     TransCrateItem(D),
-    TransInlinedItem(D),
     TransWriteMetadata,
+    CrateVariances,
 
     // Nodes representing bits of computed IR in the tcx. Each shared
     // table in the tcx (or elsewhere) maps to one of these
@@ -89,6 +92,8 @@ pub enum DepNode<D: Clone + Debug> {
     // predicates for an item wind up in `ItemSignature`).
     AssociatedItems(D),
     ItemSignature(D),
+    ItemVarianceConstraints(D),
+    ItemVariances(D),
     IsForeignItem(D),
     TypeParamPredicates((D, D)),
     SizedConstraint(D),
@@ -162,6 +167,7 @@ pub enum DepNode<D: Clone + Debug> {
     IsMirAvailable(D),
     ItemAttrs(D),
     FnArgNames(D),
+    FileMap(D, Arc<String>),
 }
 
 impl<D: Clone + Debug> DepNode<D> {
@@ -188,6 +194,7 @@ impl<D: Clone + Debug> DepNode<D> {
             TransCrateItem,
             AssociatedItems,
             ItemSignature,
+            ItemVariances,
             IsForeignItem,
             AssociatedItemDefIds,
             InherentImpls,
@@ -209,6 +216,7 @@ impl<D: Clone + Debug> DepNode<D> {
             MirKrate => Some(MirKrate),
             TypeckBodiesKrate => Some(TypeckBodiesKrate),
             Coherence => Some(Coherence),
+            CrateVariances => Some(CrateVariances),
             Resolve => Some(Resolve),
             Variance => Some(Variance),
             PrivacyAccessLevels(k) => Some(PrivacyAccessLevels(k)),
@@ -237,9 +245,10 @@ impl<D: Clone + Debug> DepNode<D> {
             RegionMaps(ref d) => op(d).map(RegionMaps),
             RvalueCheck(ref d) => op(d).map(RvalueCheck),
             TransCrateItem(ref d) => op(d).map(TransCrateItem),
-            TransInlinedItem(ref d) => op(d).map(TransInlinedItem),
             AssociatedItems(ref d) => op(d).map(AssociatedItems),
             ItemSignature(ref d) => op(d).map(ItemSignature),
+            ItemVariances(ref d) => op(d).map(ItemVariances),
+            ItemVarianceConstraints(ref d) => op(d).map(ItemVarianceConstraints),
             IsForeignItem(ref d) => op(d).map(IsForeignItem),
             TypeParamPredicates((ref item, ref param)) => {
                 Some(TypeParamPredicates((try_opt!(op(item)), try_opt!(op(param)))))
@@ -280,6 +289,8 @@ impl<D: Clone + Debug> DepNode<D> {
             ItemBodyNestedBodies(ref d) => op(d).map(ItemBodyNestedBodies),
             ConstIsRvaluePromotableToStatic(ref d) => op(d).map(ConstIsRvaluePromotableToStatic),
             IsMirAvailable(ref d) => op(d).map(IsMirAvailable),
+            GlobalMetaData(ref d, kind) => op(d).map(|d| GlobalMetaData(d, kind)),
+            FileMap(ref d, ref file_name) => op(d).map(|d| FileMap(d, file_name.clone())),
         }
     }
 }
@@ -291,3 +302,16 @@ impl<D: Clone + Debug> DepNode<D> {
 /// them even in the absence of a tcx.)
 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
 pub struct WorkProductId(pub String);
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
+pub enum GlobalMetaDataKind {
+    Krate,
+    CrateDeps,
+    DylibDependencyFormats,
+    LangItems,
+    LangItemsMissing,
+    NativeLibraries,
+    CodeMap,
+    Impls,
+    ExportedSymbols,
+}
diff --git a/src/librustc/dep_graph/mod.rs b/src/librustc/dep_graph/mod.rs
index 6cb86a30400..822b61df7a4 100644
--- a/src/librustc/dep_graph/mod.rs
+++ b/src/librustc/dep_graph/mod.rs
@@ -18,15 +18,14 @@ mod raii;
 mod safe;
 mod shadow;
 mod thread;
-mod visit;
 
 pub use self::dep_tracking_map::{DepTrackingMap, DepTrackingMapConfig};
 pub use self::dep_node::DepNode;
 pub use self::dep_node::WorkProductId;
+pub use self::dep_node::GlobalMetaDataKind;
 pub use self::graph::DepGraph;
 pub use self::graph::WorkProduct;
 pub use self::query::DepGraphQuery;
 pub use self::safe::AssertDepGraphSafe;
 pub use self::safe::DepGraphSafe;
-pub use self::visit::visit_all_item_likes_in_krate;
 pub use self::raii::DepTask;
diff --git a/src/librustc/dep_graph/visit.rs b/src/librustc/dep_graph/visit.rs
deleted file mode 100644
index bf3748659fe..00000000000
--- a/src/librustc/dep_graph/visit.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use hir;
-use hir::def_id::DefId;
-use hir::itemlikevisit::ItemLikeVisitor;
-use ty::TyCtxt;
-
-use super::dep_node::DepNode;
-
-/// Visit all the items in the krate in some order. When visiting a
-/// particular item, first create a dep-node by calling `dep_node_fn`
-/// and push that onto the dep-graph stack of tasks, and also create a
-/// read edge from the corresponding AST node. This is used in
-/// compiler passes to automatically record the item that they are
-/// working on.
-pub fn visit_all_item_likes_in_krate<'a, 'tcx, V, F>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                                                     mut dep_node_fn: F,
-                                                     visitor: &mut V)
-    where F: FnMut(DefId) -> DepNode<DefId>, V: ItemLikeVisitor<'tcx>
-{
-    struct TrackingVisitor<'visit, 'tcx: 'visit, F: 'visit, V: 'visit> {
-        tcx: TyCtxt<'visit, 'tcx, 'tcx>,
-        dep_node_fn: &'visit mut F,
-        visitor: &'visit mut V,
-    }
-
-    impl<'visit, 'tcx, F, V> ItemLikeVisitor<'tcx> for TrackingVisitor<'visit, 'tcx, F, V>
-        where F: FnMut(DefId) -> DepNode<DefId>, V: ItemLikeVisitor<'tcx>
-    {
-        fn visit_item(&mut self, i: &'tcx hir::Item) {
-            let item_def_id = self.tcx.hir.local_def_id(i.id);
-            let task_id = (self.dep_node_fn)(item_def_id);
-            let _task = self.tcx.dep_graph.in_task(task_id.clone());
-            debug!("Started task {:?}", task_id);
-            self.tcx.dep_graph.read(DepNode::Hir(item_def_id));
-            self.visitor.visit_item(i);
-            debug!("Ended task {:?}", task_id);
-        }
-
-        fn visit_trait_item(&mut self, i: &'tcx hir::TraitItem) {
-            let trait_item_def_id = self.tcx.hir.local_def_id(i.id);
-            let task_id = (self.dep_node_fn)(trait_item_def_id);
-            let _task = self.tcx.dep_graph.in_task(task_id.clone());
-            debug!("Started task {:?}", task_id);
-            self.tcx.dep_graph.read(DepNode::Hir(trait_item_def_id));
-            self.visitor.visit_trait_item(i);
-            debug!("Ended task {:?}", task_id);
-        }
-
-        fn visit_impl_item(&mut self, i: &'tcx hir::ImplItem) {
-            let impl_item_def_id = self.tcx.hir.local_def_id(i.id);
-            let task_id = (self.dep_node_fn)(impl_item_def_id);
-            let _task = self.tcx.dep_graph.in_task(task_id.clone());
-            debug!("Started task {:?}", task_id);
-            self.tcx.dep_graph.read(DepNode::Hir(impl_item_def_id));
-            self.visitor.visit_impl_item(i);
-            debug!("Ended task {:?}", task_id);
-        }
-    }
-
-    let krate = tcx.dep_graph.with_ignore(|| tcx.hir.krate());
-    let mut tracking_visitor = TrackingVisitor {
-        tcx: tcx,
-        dep_node_fn: &mut dep_node_fn,
-        visitor: visitor,
-    };
-    krate.visit_all_item_likes(&mut tracking_visitor)
-}
-
diff --git a/src/librustc/hir/check_attr.rs b/src/librustc/hir/check_attr.rs
index bf292ccb8d8..f553c03d09b 100644
--- a/src/librustc/hir/check_attr.rs
+++ b/src/librustc/hir/check_attr.rs
@@ -43,7 +43,7 @@ impl<'a> CheckAttrVisitor<'a> {
     fn check_inline(&self, attr: &ast::Attribute, target: Target) {
         if target != Target::Fn {
             struct_span_err!(self.sess, attr.span, E0518, "attribute should be applied to function")
-                .span_label(attr.span, &format!("requires a function"))
+                .span_label(attr.span, "requires a function")
                 .emit();
         }
     }
@@ -123,7 +123,7 @@ impl<'a> CheckAttrVisitor<'a> {
                 _ => continue,
             };
             struct_span_err!(self.sess, attr.span, E0517, "{}", message)
-                .span_label(attr.span, &format!("requires {}", label))
+                .span_label(attr.span, format!("requires {}", label))
                 .emit();
         }
         if conflicting_reprs > 1 {
diff --git a/src/librustc/hir/def_id.rs b/src/librustc/hir/def_id.rs
index a6b18ac10a7..47604b961ae 100644
--- a/src/librustc/hir/def_id.rs
+++ b/src/librustc/hir/def_id.rs
@@ -36,7 +36,10 @@ pub const LOCAL_CRATE: CrateNum = CrateNum(0);
 
 /// Virtual crate for builtin macros
 // FIXME(jseyfried): this is also used for custom derives until proc-macro crates get `CrateNum`s.
-pub const BUILTIN_MACROS_CRATE: CrateNum = CrateNum(!0);
+pub const BUILTIN_MACROS_CRATE: CrateNum = CrateNum(u32::MAX);
+
+/// A CrateNum value that indicates that something is wrong.
+pub const INVALID_CRATE: CrateNum = CrateNum(u32::MAX - 1);
 
 impl CrateNum {
     pub fn new(x: usize) -> CrateNum {
diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs
index 3e610dd3c0d..836d9775a3f 100644
--- a/src/librustc/hir/intravisit.rs
+++ b/src/librustc/hir/intravisit.rs
@@ -88,7 +88,7 @@ pub enum NestedVisitorMap<'this, 'tcx: 'this> {
     /// that are inside of an item-like.
     ///
     /// **This is the most common choice.** A very commmon pattern is
-    /// to use `tcx.visit_all_item_likes_in_krate()` as an outer loop,
+    /// to use `visit_all_item_likes()` as an outer loop,
     /// and to have the visitor that visits the contents of each item
     /// using this setting.
     OnlyBodies(&'this Map<'tcx>),
@@ -140,23 +140,6 @@ impl<'this, 'tcx> NestedVisitorMap<'this, 'tcx> {
 /// to monitor future changes to `Visitor` in case a new method with a
 /// new default implementation gets introduced.)
 pub trait Visitor<'v> : Sized {
-    /// Invokes the suitable visitor method for the given `Node`
-    /// extracted from the hir map.
-    fn visit_hir_map_node(&mut self, node: map::Node<'v>) {
-        match node {
-            map::NodeItem(a) => self.visit_item(a),
-            map::NodeForeignItem(a) => self.visit_foreign_item(a),
-            map::NodeTraitItem(a) => self.visit_trait_item(a),
-            map::NodeImplItem(a) => self.visit_impl_item(a),
-            map::NodeExpr(a) => self.visit_expr(a),
-            map::NodeStmt(a) => self.visit_stmt(a),
-            map::NodeTy(a) => self.visit_ty(a),
-            map::NodePat(a) => self.visit_pat(a),
-            map::NodeBlock(a) => self.visit_block(a),
-            _ => bug!("Visitor::visit_hir_map_node() not yet impl for node `{:?}`", node)
-        }
-    }
-
     ///////////////////////////////////////////////////////////////////////////
     // Nested items.
 
diff --git a/src/librustc/hir/itemlikevisit.rs b/src/librustc/hir/itemlikevisit.rs
index 0d79017066b..ce1a34faf5e 100644
--- a/src/librustc/hir/itemlikevisit.rs
+++ b/src/librustc/hir/itemlikevisit.rs
@@ -19,9 +19,8 @@ use super::intravisit::Visitor;
 ///
 /// 1. **Shallow visit**: Get a simple callback for every item (or item-like thing) in the HIR.
 ///    - Example: find all items with a `#[foo]` attribute on them.
-///    - How: Implement `ItemLikeVisitor` and call `tcx.visit_all_item_likes_in_krate()`.
+///    - How: Implement `ItemLikeVisitor` and call `tcx.hir.krate().visit_all_item_likes()`.
 ///    - Pro: Efficient; just walks the lists of item-like things, not the nodes themselves.
-///    - Pro: Integrates well into dependency tracking.
 ///    - Con: Don't get information about nesting
 ///    - Con: Don't have methods for specific bits of HIR, like "on
 ///      every expr, do this".
@@ -30,7 +29,7 @@ use super::intravisit::Visitor;
 ///    within one another.
 ///    - Example: Examine each expression to look for its type and do some check or other.
 ///    - How: Implement `intravisit::Visitor` and use
-///      `tcx.visit_all_item_likes_in_krate(visitor.as_deep_visitor())`. Within
+///      `tcx.hir.krate().visit_all_item_likes(visitor.as_deep_visitor())`. Within
 ///      your `intravisit::Visitor` impl, implement methods like
 ///      `visit_expr()`; don't forget to invoke
 ///      `intravisit::walk_visit_expr()` to keep walking the subparts.
diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs
index abc967dec90..c715484a934 100644
--- a/src/librustc/hir/map/mod.rs
+++ b/src/librustc/hir/map/mod.rs
@@ -442,20 +442,21 @@ impl<'hir> Map<'hir> {
         self.local_def_id(self.body_owner(id))
     }
 
-    /// Given a body owner's id, returns the `BodyId` associated with it.
-    pub fn body_owned_by(&self, id: NodeId) -> BodyId {
+    /// Given a node id, returns the `BodyId` associated with it,
+    /// if the node is a body owner, otherwise returns `None`.
+    pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
         if let Some(entry) = self.find_entry(id) {
             if let Some(body_id) = entry.associated_body() {
                 // For item-like things and closures, the associated
                 // body has its own distinct id, and that is returned
                 // by `associated_body`.
-                body_id
+                Some(body_id)
             } else {
                 // For some expressions, the expression is its own body.
                 if let EntryExpr(_, expr) = entry {
-                    BodyId { node_id: expr.id }
+                    Some(BodyId { node_id: expr.id })
                 } else {
-                    span_bug!(self.span(id), "id `{}` has no associated body: {:?}", id, entry);
+                    None
                 }
             }
         } else {
@@ -463,6 +464,14 @@ impl<'hir> Map<'hir> {
         }
     }
 
+    /// Given a body owner's id, returns the `BodyId` associated with it.
+    pub fn body_owned_by(&self, id: NodeId) -> BodyId {
+        self.maybe_body_owned_by(id).unwrap_or_else(|| {
+            span_bug!(self.span(id), "body_owned_by: {} has no associated body",
+                      self.node_to_string(id));
+        })
+    }
+
     pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
         match self.get(id) {
             NodeItem(&Item { node: ItemTrait(..), .. }) => id,
diff --git a/src/librustc/hir/svh.rs b/src/librustc/hir/svh.rs
index ae1f9d3028c..a6cfcb710ed 100644
--- a/src/librustc/hir/svh.rs
+++ b/src/librustc/hir/svh.rs
@@ -66,3 +66,7 @@ impl Decodable for Svh {
          .map(Svh::new)
     }
 }
+
+impl_stable_hash_for!(struct Svh {
+    hash
+});
diff --git a/src/librustc/ich/caching_codemap_view.rs b/src/librustc/ich/caching_codemap_view.rs
index 1278d9f5171..b21c3a2b216 100644
--- a/src/librustc/ich/caching_codemap_view.rs
+++ b/src/librustc/ich/caching_codemap_view.rs
@@ -8,10 +8,14 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use ty::TyCtxt;
+use dep_graph::{DepGraph, DepNode};
+use hir::def_id::{DefId, CrateNum, CRATE_DEF_INDEX};
+use rustc_data_structures::bitvec::BitVector;
 use std::rc::Rc;
+use std::sync::Arc;
 use syntax::codemap::CodeMap;
 use syntax_pos::{BytePos, FileMap};
+use ty::TyCtxt;
 
 #[derive(Clone)]
 struct CacheEntry {
@@ -20,30 +24,37 @@ struct CacheEntry {
     line_start: BytePos,
     line_end: BytePos,
     file: Rc<FileMap>,
+    file_index: usize,
 }
 
 pub struct CachingCodemapView<'tcx> {
     codemap: &'tcx CodeMap,
     line_cache: [CacheEntry; 3],
     time_stamp: usize,
+    dep_graph: DepGraph,
+    dep_tracking_reads: BitVector,
 }
 
 impl<'tcx> CachingCodemapView<'tcx> {
     pub fn new<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CachingCodemapView<'tcx> {
         let codemap = tcx.sess.codemap();
-        let first_file = codemap.files.borrow()[0].clone();
+        let files = codemap.files_untracked();
+        let first_file = files[0].clone();
         let entry = CacheEntry {
             time_stamp: 0,
             line_number: 0,
             line_start: BytePos(0),
             line_end: BytePos(0),
             file: first_file,
+            file_index: 0,
         };
 
         CachingCodemapView {
+            dep_graph: tcx.dep_graph.clone(),
             codemap: codemap,
             line_cache: [entry.clone(), entry.clone(), entry.clone()],
             time_stamp: 0,
+            dep_tracking_reads: BitVector::new(files.len()),
         }
     }
 
@@ -56,6 +67,10 @@ impl<'tcx> CachingCodemapView<'tcx> {
         for cache_entry in self.line_cache.iter_mut() {
             if pos >= cache_entry.line_start && pos < cache_entry.line_end {
                 cache_entry.time_stamp = self.time_stamp;
+                if self.dep_tracking_reads.insert(cache_entry.file_index) {
+                    self.dep_graph.read(dep_node(cache_entry));
+                }
+
                 return Some((cache_entry.file.clone(),
                              cache_entry.line_number,
                              pos - cache_entry.line_start));
@@ -75,7 +90,7 @@ impl<'tcx> CachingCodemapView<'tcx> {
         // If the entry doesn't point to the correct file, fix it up
         if pos < cache_entry.file.start_pos || pos >= cache_entry.file.end_pos {
             let file_valid;
-            let files = self.codemap.files.borrow();
+            let files = self.codemap.files_untracked();
 
             if files.len() > 0 {
                 let file_index = self.codemap.lookup_filemap_idx(pos);
@@ -83,6 +98,7 @@ impl<'tcx> CachingCodemapView<'tcx> {
 
                 if pos >= file.start_pos && pos < file.end_pos {
                     cache_entry.file = file;
+                    cache_entry.file_index = file_index;
                     file_valid = true;
                 } else {
                     file_valid = false;
@@ -104,8 +120,21 @@ impl<'tcx> CachingCodemapView<'tcx> {
         cache_entry.line_end = line_bounds.1;
         cache_entry.time_stamp = self.time_stamp;
 
+        if self.dep_tracking_reads.insert(cache_entry.file_index) {
+            self.dep_graph.read(dep_node(cache_entry));
+        }
+
         return Some((cache_entry.file.clone(),
                      cache_entry.line_number,
                      pos - cache_entry.line_start));
     }
 }
+
+fn dep_node(cache_entry: &CacheEntry) -> DepNode<DefId> {
+    let def_id = DefId {
+        krate: CrateNum::from_u32(cache_entry.file.crate_of_origin),
+        index: CRATE_DEF_INDEX,
+    };
+    let name = Arc::new(cache_entry.file.name.clone());
+    DepNode::FileMap(def_id, name)
+}
diff --git a/src/librustc/ich/impls_cstore.rs b/src/librustc/ich/impls_cstore.rs
new file mode 100644
index 00000000000..e95dbdd15c5
--- /dev/null
+++ b/src/librustc/ich/impls_cstore.rs
@@ -0,0 +1,40 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! This module contains `HashStable` implementations for various data types
+//! from rustc::middle::cstore in no particular order.
+
+use middle;
+
+impl_stable_hash_for!(enum middle::cstore::DepKind {
+    UnexportedMacrosOnly,
+    MacrosOnly,
+    Implicit,
+    Explicit
+});
+
+impl_stable_hash_for!(enum middle::cstore::NativeLibraryKind {
+    NativeStatic,
+    NativeStaticNobundle,
+    NativeFramework,
+    NativeUnknown
+});
+
+impl_stable_hash_for!(struct middle::cstore::NativeLibrary {
+    kind,
+    name,
+    cfg,
+    foreign_items
+});
+
+impl_stable_hash_for!(enum middle::cstore::LinkagePreference {
+    RequireDynamic,
+    RequireStatic
+});
diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs
index 3aeee1c1b98..abc51601b6e 100644
--- a/src/librustc/ich/impls_hir.rs
+++ b/src/librustc/ich/impls_hir.rs
@@ -1120,3 +1120,11 @@ impl_stable_hash_for!(struct hir::def::Export {
     def,
     span
 });
+
+impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ::middle::lang_items::LangItem {
+    fn hash_stable<W: StableHasherResult>(&self,
+                                          _: &mut StableHashingContext<'a, 'tcx>,
+                                          hasher: &mut StableHasher<W>) {
+        ::std::hash::Hash::hash(self, hasher);
+    }
+}
diff --git a/src/librustc/ich/impls_syntax.rs b/src/librustc/ich/impls_syntax.rs
index 26734500001..7138db01339 100644
--- a/src/librustc/ich/impls_syntax.rs
+++ b/src/librustc/ich/impls_syntax.rs
@@ -19,7 +19,9 @@ use std::mem;
 use syntax::ast;
 use syntax::parse::token;
 use syntax::tokenstream;
-use syntax_pos::Span;
+use syntax_pos::{Span, FileMap};
+
+use hir::def_id::{DefId, CrateNum, CRATE_DEF_INDEX};
 
 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
                                            StableHasherResult};
@@ -299,3 +301,79 @@ fn hash_token<'a, 'tcx, W: StableHasherResult>(token: &token::Token,
         token::Token::Shebang(val) => val.hash_stable(hcx, hasher),
     }
 }
+
+impl_stable_hash_for_spanned!(::syntax::ast::NestedMetaItemKind);
+
+impl_stable_hash_for!(enum ::syntax::ast::NestedMetaItemKind {
+    MetaItem(meta_item),
+    Literal(lit)
+});
+
+impl_stable_hash_for!(struct ::syntax::ast::MetaItem {
+    name,
+    node,
+    span
+});
+
+impl_stable_hash_for!(enum ::syntax::ast::MetaItemKind {
+    Word,
+    List(nested_items),
+    NameValue(lit)
+});
+
+impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for FileMap {
+    fn hash_stable<W: StableHasherResult>(&self,
+                                          hcx: &mut StableHashingContext<'a, 'tcx>,
+                                          hasher: &mut StableHasher<W>) {
+        let FileMap {
+            ref name,
+            name_was_remapped,
+            crate_of_origin,
+            // Do not hash the source as it is not encoded
+            src: _,
+            start_pos,
+            end_pos: _,
+            ref lines,
+            ref multibyte_chars,
+        } = *self;
+
+        name.hash_stable(hcx, hasher);
+        name_was_remapped.hash_stable(hcx, hasher);
+
+        DefId {
+            krate: CrateNum::from_u32(crate_of_origin),
+            index: CRATE_DEF_INDEX,
+        }.hash_stable(hcx, hasher);
+
+        // We only hash the relative position within this filemap
+        let lines = lines.borrow();
+        lines.len().hash_stable(hcx, hasher);
+        for &line in lines.iter() {
+            stable_byte_pos(line, start_pos).hash_stable(hcx, hasher);
+        }
+
+        // We only hash the relative position within this filemap
+        let multibyte_chars = multibyte_chars.borrow();
+        multibyte_chars.len().hash_stable(hcx, hasher);
+        for &char_pos in multibyte_chars.iter() {
+            stable_multibyte_char(char_pos, start_pos).hash_stable(hcx, hasher);
+        }
+    }
+}
+
+fn stable_byte_pos(pos: ::syntax_pos::BytePos,
+                   filemap_start: ::syntax_pos::BytePos)
+                   -> u32 {
+    pos.0 - filemap_start.0
+}
+
+fn stable_multibyte_char(mbc: ::syntax_pos::MultiByteChar,
+                         filemap_start: ::syntax_pos::BytePos)
+                         -> (u32, u32) {
+    let ::syntax_pos::MultiByteChar {
+        pos,
+        bytes,
+    } = mbc;
+
+    (pos.0 - filemap_start.0, bytes as u32)
+}
diff --git a/src/librustc/ich/mod.rs b/src/librustc/ich/mod.rs
index d70ed051ac4..d881a1cc45a 100644
--- a/src/librustc/ich/mod.rs
+++ b/src/librustc/ich/mod.rs
@@ -19,6 +19,7 @@ mod caching_codemap_view;
 mod hcx;
 
 mod impls_const_math;
+mod impls_cstore;
 mod impls_hir;
 mod impls_mir;
 mod impls_ty;
diff --git a/src/librustc/infer/error_reporting/mod.rs b/src/librustc/infer/error_reporting/mod.rs
index 8f2bdd4e85c..4c27bade0f7 100644
--- a/src/librustc/infer/error_reporting/mod.rs
+++ b/src/librustc/infer/error_reporting/mod.rs
@@ -668,9 +668,9 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
             }
         }
 
-        diag.span_label(span, &terr);
+        diag.span_label(span, terr.to_string());
         if let Some((sp, msg)) = secondary_span {
-            diag.span_label(sp, &msg);
+            diag.span_label(sp, msg);
         }
 
         self.note_error_origin(diag, &cause);
diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs
index 6947e7c3f40..6f3e84247f7 100644
--- a/src/librustc/lint/context.rs
+++ b/src/librustc/lint/context.rs
@@ -680,12 +680,12 @@ pub trait LintContext<'tcx>: Sized {
                                                             "{}({}) overruled by outer forbid({})",
                                                             level.as_str(), lint_name,
                                                             lint_name);
-                    diag_builder.span_label(span, &format!("overruled by previous forbid"));
+                    diag_builder.span_label(span, "overruled by previous forbid");
                     match now_source {
                         LintSource::Default => &mut diag_builder,
                         LintSource::Node(_, forbid_source_span) => {
                             diag_builder.span_label(forbid_source_span,
-                                                    &format!("`forbid` level set here"))
+                                                    "`forbid` level set here")
                         },
                         LintSource::CommandLine(_) => {
                             diag_builder.note("`forbid` lint level was set on command line")
diff --git a/src/librustc/middle/const_val.rs b/src/librustc/middle/const_val.rs
index 74026abe64d..3bbaf5c9299 100644
--- a/src/librustc/middle/const_val.rs
+++ b/src/librustc/middle/const_val.rs
@@ -197,7 +197,7 @@ impl<'a, 'gcx, 'tcx> ConstEvalErr<'tcx> {
     {
         match self.description() {
             ConstEvalErrDescription::Simple(message) => {
-                diag.span_label(self.span, &message);
+                diag.span_label(self.span, message);
             }
         }
 
diff --git a/src/librustc/middle/cstore.rs b/src/librustc/middle/cstore.rs
index 6f0a990ca41..da899a9130c 100644
--- a/src/librustc/middle/cstore.rs
+++ b/src/librustc/middle/cstore.rs
@@ -23,6 +23,7 @@
 // probably get a better home if someone can find one.
 
 use hir::def;
+use dep_graph::DepNode;
 use hir::def_id::{CrateNum, DefId, DefIndex};
 use hir::map as hir_map;
 use hir::map::definitions::{Definitions, DefKey, DisambiguatedDefPathData};
@@ -161,7 +162,16 @@ pub struct ExternCrate {
 
 pub struct EncodedMetadata {
     pub raw_data: Vec<u8>,
-    pub hashes: Vec<EncodedMetadataHash>,
+    pub hashes: EncodedMetadataHashes,
+}
+
+impl EncodedMetadata {
+    pub fn new() -> EncodedMetadata {
+        EncodedMetadata {
+            raw_data: Vec::new(),
+            hashes: EncodedMetadataHashes::new(),
+        }
+    }
 }
 
 /// The hash for some metadata that (when saving) will be exported
@@ -173,6 +183,24 @@ pub struct EncodedMetadataHash {
     pub hash: ich::Fingerprint,
 }
 
+/// The hash for some metadata that (when saving) will be exported
+/// from this crate, or which (when importing) was exported by an
+/// upstream crate.
+#[derive(Debug, RustcEncodable, RustcDecodable, Clone)]
+pub struct EncodedMetadataHashes {
+    pub entry_hashes: Vec<EncodedMetadataHash>,
+    pub global_hashes: Vec<(DepNode<()>, ich::Fingerprint)>,
+}
+
+impl EncodedMetadataHashes {
+    pub fn new() -> EncodedMetadataHashes {
+        EncodedMetadataHashes {
+            entry_hashes: Vec::new(),
+            global_hashes: Vec::new(),
+        }
+    }
+}
+
 /// A store of Rust crates, through with their metadata
 /// can be accessed.
 pub trait CrateStore {
diff --git a/src/librustc/middle/effect.rs b/src/librustc/middle/effect.rs
index 4bbf37b21ed..5360a86560d 100644
--- a/src/librustc/middle/effect.rs
+++ b/src/librustc/middle/effect.rs
@@ -74,7 +74,7 @@ impl<'a, 'tcx> EffectCheckVisitor<'a, 'tcx> {
                     struct_span_err!(
                         self.tcx.sess, span, E0133,
                         "{} requires unsafe function or block", description)
-                        .span_label(span, &description)
+                        .span_label(span, description)
                         .emit();
                 }
             }
diff --git a/src/librustc/middle/entry.rs b/src/librustc/middle/entry.rs
index 8da7560387f..24748b6cf65 100644
--- a/src/librustc/middle/entry.rs
+++ b/src/librustc/middle/entry.rs
@@ -128,8 +128,8 @@ fn find_item(item: &Item, ctxt: &mut EntryContext, at_root: bool) {
             } else {
                 struct_span_err!(ctxt.session, item.span, E0137,
                           "multiple functions with a #[main] attribute")
-                .span_label(item.span, &format!("additional #[main] function"))
-                .span_label(ctxt.attr_main_fn.unwrap().1, &format!("first #[main] function"))
+                .span_label(item.span, "additional #[main] function")
+                .span_label(ctxt.attr_main_fn.unwrap().1, "first #[main] function")
                 .emit();
             }
         },
@@ -141,8 +141,8 @@ fn find_item(item: &Item, ctxt: &mut EntryContext, at_root: bool) {
                     ctxt.session, item.span, E0138,
                     "multiple 'start' functions")
                     .span_label(ctxt.start_fn.unwrap().1,
-                                &format!("previous `start` function here"))
-                    .span_label(item.span, &format!("multiple `start` functions"))
+                                "previous `start` function here")
+                    .span_label(item.span, "multiple `start` functions")
                     .emit();
             }
         },
diff --git a/src/librustc/middle/intrinsicck.rs b/src/librustc/middle/intrinsicck.rs
index 435dd05358d..a759a9061f8 100644
--- a/src/librustc/middle/intrinsicck.rs
+++ b/src/librustc/middle/intrinsicck.rs
@@ -92,7 +92,7 @@ impl<'a, 'gcx, 'tcx> ExprVisitor<'a, 'gcx, 'tcx> {
                     struct_span_err!(self.infcx.tcx.sess, span, E0591,
                                      "`{}` is zero-sized and can't be transmuted to `{}`",
                                      from, to)
-                        .span_note(span, &format!("cast with `as` to a pointer instead"))
+                        .span_note(span, "cast with `as` to a pointer instead")
                         .emit();
                     return;
                 }
@@ -126,7 +126,7 @@ impl<'a, 'gcx, 'tcx> ExprVisitor<'a, 'gcx, 'tcx> {
                   from, skeleton_string(from, sk_from),
                   to, skeleton_string(to, sk_to))
             .span_label(span,
-                &format!("transmuting between {} and {}",
+                format!("transmuting between {} and {}",
                     skeleton_string(from, sk_from),
                     skeleton_string(to, sk_to)))
             .emit();
diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs
index d1d5e9d6cb1..087ab4b94da 100644
--- a/src/librustc/middle/region.rs
+++ b/src/librustc/middle/region.rs
@@ -24,14 +24,16 @@ use std::mem;
 use std::rc::Rc;
 use serialize;
 use syntax::codemap;
-use syntax::ast::{self, NodeId};
+use syntax::ast;
 use syntax_pos::Span;
 use ty::TyCtxt;
 use ty::maps::Providers;
 
-use hir; use hir::def_id::DefId;
-use hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
-use hir::{Block, Item, FnDecl, Arm, Pat, PatKind, Stmt, Expr, Local};
+use hir;
+use hir::def_id::DefId;
+use hir::intravisit::{self, Visitor, NestedVisitorMap};
+use hir::{Block, Arm, Pat, PatKind, Stmt, Expr, Local};
+use mir::transform::MirSource;
 
 pub type CodeExtent<'tcx> = &'tcx CodeExtentData;
 
@@ -811,7 +813,17 @@ fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr:
         }
     }
 
-    intravisit::walk_expr(visitor, expr);
+    match expr.node {
+        // Manually recurse over closures, because they are the only
+        // case of nested bodies that share the parent environment.
+        hir::ExprClosure(.., body, _) => {
+            let body = visitor.tcx.hir.body(body);
+            visitor.visit_body(body);
+        }
+
+        _ => intravisit::walk_expr(visitor, expr)
+    }
+
     visitor.cx = prev_cx;
 }
 
@@ -1041,74 +1053,6 @@ fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
     }
 }
 
-fn resolve_item_like<'a, 'tcx, F>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, walk: F)
-    where F: FnOnce(&mut RegionResolutionVisitor<'a, 'tcx>)
-{
-    // Items create a new outer block scope as far as we're concerned.
-    let prev_cx = visitor.cx;
-    let prev_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
-    visitor.cx = Context {
-        root_id: None,
-        var_parent: None,
-        parent: None,
-    };
-    walk(visitor);
-    visitor.cx = prev_cx;
-    visitor.terminating_scopes = prev_ts;
-}
-
-fn resolve_fn<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
-                        kind: FnKind<'tcx>,
-                        decl: &'tcx hir::FnDecl,
-                        body_id: hir::BodyId,
-                        sp: Span,
-                        id: ast::NodeId) {
-    visitor.cx.parent = Some(visitor.new_code_extent(
-        CodeExtentData::CallSiteScope { fn_id: id, body_id: body_id.node_id }));
-
-    debug!("region::resolve_fn(id={:?}, \
-            span={:?}, \
-            body.id={:?}, \
-            cx.parent={:?})",
-           id,
-           visitor.tcx.sess.codemap().span_to_string(sp),
-           body_id,
-           visitor.cx.parent);
-
-    let fn_decl_scope = visitor.new_code_extent(
-        CodeExtentData::ParameterScope { fn_id: id, body_id: body_id.node_id });
-
-    if let Some(root_id) = visitor.cx.root_id {
-        visitor.region_maps.record_fn_parent(body_id.node_id, root_id);
-    }
-
-    let outer_cx = visitor.cx;
-    let outer_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
-    visitor.terminating_scopes.insert(body_id.node_id);
-
-    // The arguments and `self` are parented to the fn.
-    visitor.cx = Context {
-        root_id: Some(body_id.node_id),
-        parent: None,
-        var_parent: Some(fn_decl_scope),
-    };
-
-    intravisit::walk_fn_decl(visitor, decl);
-    intravisit::walk_fn_kind(visitor, kind);
-
-    // The body of the every fn is a root scope.
-    visitor.cx = Context {
-        root_id: Some(body_id.node_id),
-        parent: Some(fn_decl_scope),
-        var_parent: Some(fn_decl_scope),
-    };
-    visitor.visit_nested_body(body_id);
-
-    // Restore context we had at the start.
-    visitor.cx = outer_cx;
-    visitor.terminating_scopes = outer_ts;
-}
-
 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
     pub fn intern_code_extent(&mut self,
                               data: CodeExtentData,
@@ -1152,29 +1096,57 @@ impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
 
 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
-        NestedVisitorMap::OnlyBodies(&self.map)
+        NestedVisitorMap::None
     }
 
     fn visit_block(&mut self, b: &'tcx Block) {
         resolve_block(self, b);
     }
 
-    fn visit_item(&mut self, i: &'tcx Item) {
-        resolve_item_like(self, |this| intravisit::walk_item(this, i));
-    }
+    fn visit_body(&mut self, body: &'tcx hir::Body) {
+        let body_id = body.id();
+        let owner_id = self.map.body_owner(body_id);
 
-    fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
-        resolve_item_like(self, |this| intravisit::walk_impl_item(this, ii));
-    }
+        debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
+               owner_id,
+               self.tcx.sess.codemap().span_to_string(body.value.span),
+               body_id,
+               self.cx.parent);
 
-    fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
-        resolve_item_like(self, |this| intravisit::walk_trait_item(this, ti));
-    }
+        let outer_cx = self.cx;
+        let outer_ts = mem::replace(&mut self.terminating_scopes, NodeSet());
 
-    fn visit_fn(&mut self, fk: FnKind<'tcx>, fd: &'tcx FnDecl,
-                b: hir::BodyId, s: Span, n: NodeId) {
-        resolve_fn(self, fk, fd, b, s, n);
+        // Only functions have an outer terminating (drop) scope,
+        // while temporaries in constant initializers are 'static.
+        if let MirSource::Fn(_) = MirSource::from_node(self.tcx, owner_id) {
+            self.terminating_scopes.insert(body_id.node_id);
+        }
+
+        if let Some(root_id) = self.cx.root_id {
+            self.region_maps.record_fn_parent(body_id.node_id, root_id);
+        }
+        self.cx.root_id = Some(body_id.node_id);
+
+        self.cx.parent = Some(self.new_code_extent(
+            CodeExtentData::CallSiteScope { fn_id: owner_id, body_id: body_id.node_id }));
+        self.cx.parent = Some(self.new_code_extent(
+            CodeExtentData::ParameterScope { fn_id: owner_id, body_id: body_id.node_id }));
+
+        // The arguments and `self` are parented to the fn.
+        self.cx.var_parent = self.cx.parent.take();
+        for argument in &body.arguments {
+            self.visit_pat(&argument.pat);
+        }
+
+        // The body of the every fn is a root scope.
+        self.cx.parent = self.cx.var_parent;
+        self.visit_expr(&body.value);
+
+        // Restore context we had at the start.
+        self.cx = outer_cx;
+        self.terminating_scopes = outer_ts;
     }
+
     fn visit_arm(&mut self, a: &'tcx Arm) {
         resolve_arm(self, a);
     }
@@ -1192,21 +1164,18 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
     }
 }
 
-fn region_maps<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn_id: DefId)
+fn region_maps<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
     -> Rc<RegionMaps<'tcx>>
 {
-    let closure_base_def_id = tcx.closure_base_def_id(fn_id);
-    if closure_base_def_id != fn_id {
+    let closure_base_def_id = tcx.closure_base_def_id(def_id);
+    if closure_base_def_id != def_id {
         return tcx.region_maps(closure_base_def_id);
     }
 
     let mut maps = RegionMaps::new();
 
-    let fn_node_id = tcx.hir.as_local_node_id(fn_id)
-                            .expect("fn DefId should be for LOCAL_CRATE");
-    let node = tcx.hir.get(fn_node_id);
-
-    {
+    let id = tcx.hir.as_local_node_id(def_id).unwrap();
+    if let Some(body) = tcx.hir.maybe_body_owned_by(id) {
         let mut visitor = RegionResolutionVisitor {
             tcx: tcx,
             region_maps: &mut maps,
@@ -1218,7 +1187,8 @@ fn region_maps<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn_id: DefId)
             },
             terminating_scopes: NodeSet(),
         };
-        visitor.visit_hir_map_node(node);
+
+        visitor.visit_body(tcx.hir.body(body));
     }
 
     Rc::new(maps)
diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs
index a8ba708cc2c..67b8dfb2d8e 100644
--- a/src/librustc/middle/resolve_lifetime.rs
+++ b/src/librustc/middle/resolve_lifetime.rs
@@ -574,9 +574,9 @@ fn signal_shadowing_problem(sess: &Session, name: ast::Name, orig: Original, sha
                                         {} name that is already in scope",
                                        shadower.kind.desc(), name, orig.kind.desc()))
     };
-    err.span_label(orig.span, &"first declared here");
+    err.span_label(orig.span, "first declared here");
     err.span_label(shadower.span,
-                   &format!("lifetime {} already in scope", name));
+                   format!("lifetime {} already in scope", name));
     err.emit();
 }
 
@@ -919,7 +919,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
         } else {
             struct_span_err!(self.sess, lifetime_ref.span, E0261,
                 "use of undeclared lifetime name `{}`", lifetime_ref.name)
-                .span_label(lifetime_ref.span, &format!("undeclared lifetime"))
+                .span_label(lifetime_ref.span, "undeclared lifetime")
                 .emit();
         }
     }
@@ -1328,7 +1328,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
         } else {
             format!("expected lifetime parameter")
         };
-        err.span_label(span, &msg);
+        err.span_label(span, msg);
 
         if let Some(params) = error {
             if lifetime_refs.len() == 1 {
@@ -1438,7 +1438,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
                     let mut err = struct_span_err!(self.sess, lifetime.span, E0262,
                                   "invalid lifetime parameter name: `{}`", lifetime.name);
                     err.span_label(lifetime.span,
-                                   &format!("{} is a reserved lifetime name", lifetime.name));
+                                   format!("{} is a reserved lifetime name", lifetime.name));
                     err.emit();
                 }
             }
@@ -1452,9 +1452,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
                                      "lifetime name `{}` declared twice in the same scope",
                                      lifetime_j.lifetime.name)
                         .span_label(lifetime_j.lifetime.span,
-                                    &format!("declared twice"))
+                                    "declared twice")
                         .span_label(lifetime_i.lifetime.span,
-                                   &format!("previous declaration here"))
+                                   "previous declaration here")
                         .emit();
                 }
             }
diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs
index fdfcd83d5b4..75bc940625d 100644
--- a/src/librustc/session/config.rs
+++ b/src/librustc/session/config.rs
@@ -1122,14 +1122,6 @@ pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
 pub enum OptionStability {
     Stable,
 
-    // FIXME: historically there were some options which were either `-Z` or
-    //        required the `-Z unstable-options` flag, which were all intended
-    //        to be unstable. Unfortunately we didn't actually gate usage of
-    //        these options on the stable compiler, so we still allow them there
-    //        today. There are some warnings printed out about this in the
-    //        driver.
-    UnstableButNotReally,
-
     Unstable,
 }
 
@@ -1148,17 +1140,9 @@ impl RustcOptGroup {
         RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
     }
 
-    #[allow(dead_code)] // currently we have no "truly unstable" options
     pub fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
         RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
     }
-
-    fn unstable_bnr(g: getopts::OptGroup) -> RustcOptGroup {
-        RustcOptGroup {
-            opt_group: g,
-            stability: OptionStability::UnstableButNotReally,
-        }
-    }
 }
 
 // The `opt` local module holds wrappers around the `getopts` API that
@@ -1180,7 +1164,6 @@ mod opt {
 
     fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
     fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
-    fn unstable_bnr(g: getopts::OptGroup) -> R { RustcOptGroup::unstable_bnr(g) }
 
     pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
         stable(getopts::optopt(a, b, c, d))
@@ -1213,24 +1196,6 @@ mod opt {
     pub fn flagmulti(a: S, b: S, c: S) -> R {
         unstable(getopts::optflagmulti(a, b, c))
     }
-
-    // Do not use these functions for any new options added to the compiler, all
-    // new options should use the `*_u` variants above to be truly unstable.
-    pub fn opt_ubnr(a: S, b: S, c: S, d: S) -> R {
-        unstable_bnr(getopts::optopt(a, b, c, d))
-    }
-    pub fn multi_ubnr(a: S, b: S, c: S, d: S) -> R {
-        unstable_bnr(getopts::optmulti(a, b, c, d))
-    }
-    pub fn flag_ubnr(a: S, b: S, c: S) -> R {
-        unstable_bnr(getopts::optflag(a, b, c))
-    }
-    pub fn flagopt_ubnr(a: S, b: S, c: S, d: S) -> R {
-        unstable_bnr(getopts::optflagopt(a, b, c, d))
-    }
-    pub fn flagmulti_ubnr(a: S, b: S, c: S) -> R {
-        unstable_bnr(getopts::optflagmulti(a, b, c))
-    }
 }
 
 /// Returns the "short" subset of the rustc command line options,
@@ -1296,7 +1261,7 @@ pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
         opt::multi_s("", "extern", "Specify where an external rust library is located",
                      "NAME=PATH"),
         opt::opt_s("", "sysroot", "Override the system root", "PATH"),
-        opt::multi_ubnr("Z", "", "Set internal debugging options", "FLAG"),
+        opt::multi("Z", "", "Set internal debugging options", "FLAG"),
         opt::opt_s("", "error-format",
                       "How errors and other messages are produced",
                       "human|json"),
@@ -1305,28 +1270,20 @@ pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
                                  always = always colorize output;
                                  never  = never colorize output", "auto|always|never"),
 
-        opt::flagopt_ubnr("", "pretty",
-                          "Pretty-print the input instead of compiling;
-                           valid types are: `normal` (un-annotated source),
-                           `expanded` (crates expanded), or
-                           `expanded,identified` (fully parenthesized, AST nodes with IDs).",
-                          "TYPE"),
-        opt::flagopt_ubnr("", "unpretty",
-                          "Present the input source, unstable (and less-pretty) variants;
-                           valid types are any of the types for `--pretty`, as well as:
-                           `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
-                           `everybody_loops` (all function bodies replaced with `loop {}`),
-                           `hir` (the HIR), `hir,identified`, or
-                           `hir,typed` (HIR with types for each node).",
-                          "TYPE"),
-
-        // new options here should **not** use the `_ubnr` functions, all new
-        // unstable options should use the short variants to indicate that they
-        // are truly unstable. All `_ubnr` flags are just that way because they
-        // were so historically.
-        //
-        // You may also wish to keep this comment at the bottom of this list to
-        // ensure that others see it.
+        opt::flagopt("", "pretty",
+                     "Pretty-print the input instead of compiling;
+                      valid types are: `normal` (un-annotated source),
+                      `expanded` (crates expanded), or
+                      `expanded,identified` (fully parenthesized, AST nodes with IDs).",
+                     "TYPE"),
+        opt::flagopt("", "unpretty",
+                     "Present the input source, unstable (and less-pretty) variants;
+                      valid types are any of the types for `--pretty`, as well as:
+                      `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
+                      `everybody_loops` (all function bodies replaced with `loop {}`),
+                      `hir` (the HIR), `hir,identified`, or
+                      `hir,typed` (HIR with types for each node).",
+                     "TYPE"),
     ]);
     opts
 }
@@ -1704,7 +1661,7 @@ pub mod nightly_options {
     use getopts;
     use syntax::feature_gate::UnstableFeatures;
     use super::{ErrorOutputType, OptionStability, RustcOptGroup};
-    use session::{early_error, early_warn};
+    use session::early_error;
 
     pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
         is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options")
@@ -1746,15 +1703,6 @@ pub mod nightly_options {
                                        nightly compiler", opt_name);
                     early_error(ErrorOutputType::default(), &msg);
                 }
-                OptionStability::UnstableButNotReally => {
-                    let msg = format!("the option `{}` is unstable and should \
-                                       only be used on the nightly compiler, but \
-                                       it is currently accepted for backwards \
-                                       compatibility; this will soon change, \
-                                       see issue #31847 for more details",
-                                      opt_name);
-                    early_warn(ErrorOutputType::default(), &msg);
-                }
                 OptionStability::Stable => {}
             }
         }
diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs
index ec3eaa124c3..2e2d5a6bd4d 100644
--- a/src/librustc/session/mod.rs
+++ b/src/librustc/session/mod.rs
@@ -11,8 +11,8 @@
 pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
 pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
 
-use dep_graph::DepGraph;
-use hir::def_id::{CrateNum, DefIndex};
+use dep_graph::{DepGraph, DepNode};
+use hir::def_id::{DefId, CrateNum, DefIndex, CRATE_DEF_INDEX};
 use lint;
 use middle::cstore::CrateStore;
 use middle::dependency_format;
@@ -32,7 +32,7 @@ use syntax::parse::ParseSess;
 use syntax::symbol::Symbol;
 use syntax::{ast, codemap};
 use syntax::feature_gate::AttributeType;
-use syntax_pos::{Span, MultiSpan};
+use syntax_pos::{Span, MultiSpan, FileMap};
 
 use rustc_back::{LinkerFlavor, PanicStrategy};
 use rustc_back::target::Target;
@@ -48,6 +48,7 @@ use std::io::Write;
 use std::rc::Rc;
 use std::fmt;
 use std::time::Duration;
+use std::sync::Arc;
 use libc::c_int;
 
 mod code_stats;
@@ -627,6 +628,22 @@ pub fn build_session_(sopts: config::Options,
         }
     };
     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
+
+    // Hook up the codemap with a callback that allows it to register FileMap
+    // accesses with the dependency graph.
+    let cm_depgraph = dep_graph.clone();
+    let codemap_dep_tracking_callback = Box::new(move |filemap: &FileMap| {
+        let def_id = DefId {
+            krate: CrateNum::from_u32(filemap.crate_of_origin),
+            index: CRATE_DEF_INDEX,
+        };
+        let name = Arc::new(filemap.name.clone());
+        let dep_node = DepNode::FileMap(def_id, name);
+
+        cm_depgraph.read(dep_node);
+    });
+    codemap.set_dep_tracking_callback(codemap_dep_tracking_callback);
+
     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
     let default_sysroot = match sopts.maybe_sysroot {
         Some(_) => None,
diff --git a/src/librustc/traits/error_reporting.rs b/src/librustc/traits/error_reporting.rs
index e846d74febf..152e3353994 100644
--- a/src/librustc/traits/error_reporting.rs
+++ b/src/librustc/traits/error_reporting.rs
@@ -484,12 +484,12 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
 
         if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
             let span = self.tcx.sess.codemap().def_span(trait_item_span);
-            err.span_label(span, &format!("definition of `{}` from trait", item_name));
+            err.span_label(span, format!("definition of `{}` from trait", item_name));
         }
 
         err.span_label(
             error_span,
-            &format!("impl has extra requirement {}", requirement));
+            format!("impl has extra requirement {}", requirement));
 
         if let Some(node_id) = lint_id {
             self.tcx.sess.add_lint_diagnostic(EXTRA_REQUIREMENT_IN_IMPL,
@@ -582,7 +582,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
                         }
 
                         err.span_label(span,
-                                       &format!("{}the trait `{}` is not implemented for `{}`",
+                                       format!("{}the trait `{}` is not implemented for `{}`",
                                                 pre_message,
                                                 trait_ref,
                                                 trait_ref.self_ty()));
@@ -738,11 +738,11 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
             expected_ref,
             found_ref);
 
-        err.span_label(span, &format!("{}", type_error));
+        err.span_label(span, format!("{}", type_error));
 
         if let Some(sp) = found_span {
-            err.span_label(span, &format!("requires `{}`", found_ref));
-            err.span_label(sp, &format!("implements `{}`", expected_ref));
+            err.span_label(span, format!("requires `{}`", found_ref));
+            err.span_label(sp, format!("implements `{}`", expected_ref));
         }
 
         err
@@ -765,12 +765,12 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
             if expected == 1 { "" } else { "s" },
             if expected == 1 { "is" } else { "are" });
 
-        err.span_label(span, &format!("expected {} that takes {} argument{}",
+        err.span_label(span, format!("expected {} that takes {} argument{}",
                                       if is_closure { "closure" } else { "function" },
                                       expected,
                                       if expected == 1 { "" } else { "s" }));
         if let Some(span) = found_span {
-            err.span_label(span, &format!("takes {} argument{}",
+            err.span_label(span, format!("takes {} argument{}",
                                           found,
                                           if found == 1 { "" } else { "s" }));
         }
@@ -789,7 +789,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
         let mut err = struct_span_err!(self.sess, span, E0072,
                                        "recursive type `{}` has infinite size",
                                        self.item_path_str(type_def_id));
-        err.span_label(span, &format!("recursive type has infinite size"));
+        err.span_label(span, "recursive type has infinite size");
         err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
                            at some point to make `{}` representable",
                           self.item_path_str(type_def_id)));
@@ -808,7 +808,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
             self.sess, span, E0038,
             "the trait `{}` cannot be made into an object",
             trait_str);
-        err.span_label(span, &format!("the trait `{}` cannot be made into an object", trait_str));
+        err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
 
         let mut reported_violations = FxHashSet();
         for violation in violations {
@@ -1043,7 +1043,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
                                        "type annotations needed");
 
         for (target_span, label_message) in labels {
-            err.span_label(target_span, &label_message);
+            err.span_label(target_span, label_message);
         }
 
         err.emit();
diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs
index 08807d0ced0..74aac7b788b 100644
--- a/src/librustc/ty/context.rs
+++ b/src/librustc/ty/context.rs
@@ -470,9 +470,6 @@ pub struct GlobalCtxt<'tcx> {
 
     pub lang_items: middle::lang_items::LanguageItems,
 
-    /// True if the variance has been computed yet; false otherwise.
-    pub variance_computed: Cell<bool>,
-
     /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
     /// present in this set can be warned about.
     pub used_unsafe: RefCell<NodeSet>,
@@ -482,14 +479,6 @@ pub struct GlobalCtxt<'tcx> {
     /// about.
     pub used_mut_nodes: RefCell<NodeSet>,
 
-    /// The set of external nominal types whose implementations have been read.
-    /// This is used for lazy resolution of methods.
-    pub populated_external_types: RefCell<DefIdSet>,
-
-    /// The set of external primitive types whose implementations have been read.
-    /// FIXME(arielb1): why is this separate from populated_external_types?
-    pub populated_external_primitive_impls: RefCell<DefIdSet>,
-
     /// Maps any item's def-id to its stability index.
     pub stability: RefCell<stability::Index<'tcx>>,
 
@@ -566,9 +555,6 @@ pub struct GlobalCtxt<'tcx> {
     /// error reporting, and so is lazily initialised and generally
     /// shouldn't taint the common path (hence the RefCell).
     pub all_traits: RefCell<Option<Vec<DefId>>>,
-
-    /// HIR Ty -> Ty lowering cache.
-    pub ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
 }
 
 impl<'tcx> GlobalCtxt<'tcx> {
@@ -755,7 +741,6 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
             dep_graph: dep_graph.clone(),
             types: common_types,
             named_region_map: named_region_map,
-            variance_computed: Cell::new(false),
             trait_map: resolutions.trait_map,
             export_map: resolutions.export_map,
             fulfilled_predicates: RefCell::new(fulfilled_predicates),
@@ -770,8 +755,6 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
             lang_items: lang_items,
             used_unsafe: RefCell::new(NodeSet()),
             used_mut_nodes: RefCell::new(NodeSet()),
-            populated_external_types: RefCell::new(DefIdSet()),
-            populated_external_primitive_impls: RefCell::new(DefIdSet()),
             stability: RefCell::new(stability),
             selection_cache: traits::SelectionCache::new(),
             evaluation_cache: traits::EvaluationCache::new(),
@@ -786,7 +769,6 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
             derive_macros: RefCell::new(NodeMap()),
             stability_interner: RefCell::new(FxHashSet()),
             all_traits: RefCell::new(None),
-            ast_ty_to_ty_cache: RefCell::new(NodeMap()),
        }, f)
     }
 
diff --git a/src/librustc/ty/maps.rs b/src/librustc/ty/maps.rs
index 80783a547bf..3b5dc2ae164 100644
--- a/src/librustc/ty/maps.rs
+++ b/src/librustc/ty/maps.rs
@@ -182,7 +182,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
             let mut err =
                 struct_span_err!(self.sess, span, E0391,
                                  "unsupported cyclic reference between types/traits detected");
-            err.span_label(span, &format!("cyclic reference"));
+            err.span_label(span, "cyclic reference");
 
             err.span_note(stack[0].0, &format!("the cycle begins when {}...",
                                                stack[0].1.describe(self)));
@@ -267,6 +267,12 @@ impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx
     }
 }
 
+impl<'tcx> QueryDescription for queries::crate_variances<'tcx> {
+    fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
+        format!("computing the variances for items in this crate")
+    }
+}
+
 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
     fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
         format!("generating MIR shim for `{}`",
@@ -580,18 +586,6 @@ macro_rules! define_map_struct {
         }
     };
 
-    // Detect things with the `pub` modifier
-    (tcx: $tcx:tt,
-     input: (([pub $($other_modifiers:tt)*] $attrs:tt $name:tt) $($input:tt)*),
-     output: $output:tt) => {
-        define_map_struct! {
-            tcx: $tcx,
-            ready: ([pub] $attrs $name),
-            input: ($($input)*),
-            output: $output
-        }
-    };
-
     // No modifiers left? This is a private item.
     (tcx: $tcx:tt,
      input: (([] $attrs:tt $name:tt) $($input:tt)*),
@@ -718,9 +712,13 @@ define_maps! { <'tcx>
     /// True if this is a foreign item (i.e., linked via `extern { ... }`).
     [] is_foreign_item: IsForeignItem(DefId) -> bool,
 
+    /// Get a map with the variance of every item; use `item_variance`
+    /// instead.
+    [] crate_variances: crate_variances(CrateNum) -> Rc<ty::CrateVariancesMap>,
+
     /// Maps from def-id of a type or region parameter to its
     /// (inferred) variance.
-    [pub] variances_of: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
+    [] variances_of: ItemVariances(DefId) -> Rc<Vec<ty::Variance>>,
 
     /// Maps from an impl/trait def-id to a list of the def-ids of its items
     [] associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
@@ -857,3 +855,7 @@ fn const_eval_dep_node((def_id, _): (DefId, &Substs)) -> DepNode<DefId> {
 fn mir_keys(_: CrateNum) -> DepNode<DefId> {
     DepNode::MirKeys
 }
+
+fn crate_variances(_: CrateNum) -> DepNode<DefId> {
+    DepNode::CrateVariances
+}
diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs
index a065dd6a592..51cdba56cf1 100644
--- a/src/librustc/ty/mod.rs
+++ b/src/librustc/ty/mod.rs
@@ -15,7 +15,7 @@ pub use self::IntVarValue::*;
 pub use self::LvaluePreference::*;
 pub use self::fold::TypeFoldable;
 
-use dep_graph::{self, DepNode};
+use dep_graph::DepNode;
 use hir::{map as hir_map, FreevarMap, TraitMap};
 use hir::def::{Def, CtorKind, ExportMap};
 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
@@ -55,9 +55,9 @@ use rustc_const_math::ConstInt;
 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
                                            HashStable};
+use rustc_data_structures::transitive_relation::TransitiveRelation;
 
 use hir;
-use hir::itemlikevisit::ItemLikeVisitor;
 
 pub use self::sty::{Binder, DebruijnIndex};
 pub use self::sty::{FnSig, PolyFnSig};
@@ -309,6 +309,27 @@ pub enum Variance {
     Bivariant,      // T<A> <: T<B>            -- e.g., unused type parameter
 }
 
+/// The crate variances map is computed during typeck and contains the
+/// variance of every item in the local crate. You should not use it
+/// directly, because to do so will make your pass dependent on the
+/// HIR of every item in the local crate. Instead, use
+/// `tcx.variances_of()` to get the variance for a *particular*
+/// item.
+pub struct CrateVariancesMap {
+    /// This relation tracks the dependencies between the variance of
+    /// various items. In particular, if `a < b`, then the variance of
+    /// `a` depends on the sources of `b`.
+    pub dependencies: TransitiveRelation<DefId>,
+
+    /// For each item with generics, maps to a vector of the variance
+    /// of its generics.  If an item has no generics, it will have no
+    /// entry.
+    pub variances: FxHashMap<DefId, Rc<Vec<ty::Variance>>>,
+
+    /// An empty vector, useful for cloning.
+    pub empty_variance: Rc<Vec<ty::Variance>>,
+}
+
 #[derive(Clone, Copy, Debug, RustcDecodable, RustcEncodable)]
 pub struct MethodCallee<'tcx> {
     /// Impl method ID, for inherent methods, or trait method ID, otherwise.
@@ -1217,7 +1238,7 @@ impl<'a, 'tcx> ParameterEnvironment<'tcx> {
         match tcx.hir.find(id) {
             Some(hir_map::NodeImplItem(ref impl_item)) => {
                 match impl_item.node {
-                    hir::ImplItemKind::Type(_) | hir::ImplItemKind::Const(..) => {
+                    hir::ImplItemKind::Type(_) => {
                         // associated types don't have their own entry (for some reason),
                         // so for now just grab environment for the impl
                         let impl_id = tcx.hir.get_parent(id);
@@ -1226,7 +1247,8 @@ impl<'a, 'tcx> ParameterEnvironment<'tcx> {
                                                             impl_def_id,
                                                             Some(tcx.item_extent(id)))
                     }
-                    hir::ImplItemKind::Method(_, ref body) => {
+                    hir::ImplItemKind::Const(_, body) |
+                    hir::ImplItemKind::Method(_, body) => {
                         tcx.construct_parameter_environment(
                             impl_item.span,
                             tcx.hir.local_def_id(id),
@@ -1236,56 +1258,37 @@ impl<'a, 'tcx> ParameterEnvironment<'tcx> {
             }
             Some(hir_map::NodeTraitItem(trait_item)) => {
                 match trait_item.node {
-                    hir::TraitItemKind::Type(..) | hir::TraitItemKind::Const(..) => {
-                        // associated types don't have their own entry (for some reason),
-                        // so for now just grab environment for the trait
-                        let trait_id = tcx.hir.get_parent(id);
-                        let trait_def_id = tcx.hir.local_def_id(trait_id);
+                    hir::TraitItemKind::Type(..) |
+                    hir::TraitItemKind::Const(_, None) |
+                    hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_))=> {
                         tcx.construct_parameter_environment(trait_item.span,
-                                                            trait_def_id,
+                                                            tcx.hir.local_def_id(id),
                                                             Some(tcx.item_extent(id)))
                     }
-                    hir::TraitItemKind::Method(_, ref body) => {
-                        // Use call-site for extent (unless this is a
-                        // trait method with no default; then fallback
-                        // to the method id).
-                        let extent = if let hir::TraitMethod::Provided(body_id) = *body {
-                            // default impl: use call_site extent as free_id_outlive bound.
-                            tcx.call_site_extent(id, body_id.node_id)
-                        } else {
-                            // no default impl: use item extent as free_id_outlive bound.
-                            tcx.item_extent(id)
-                        };
+                    hir::TraitItemKind::Const(_, Some(body)) |
+                    hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body)) => {
                         tcx.construct_parameter_environment(
                             trait_item.span,
                             tcx.hir.local_def_id(id),
-                            Some(extent))
+                            Some(tcx.call_site_extent(id, body.node_id)))
                     }
                 }
             }
             Some(hir_map::NodeItem(item)) => {
                 match item.node {
-                    hir::ItemFn(.., body_id) => {
-                        // We assume this is a function.
-                        let fn_def_id = tcx.hir.local_def_id(id);
-
+                    hir::ItemConst(_, body) |
+                    hir::ItemStatic(.., body) |
+                    hir::ItemFn(.., body) => {
                         tcx.construct_parameter_environment(
                             item.span,
-                            fn_def_id,
-                            Some(tcx.call_site_extent(id, body_id.node_id)))
+                            tcx.hir.local_def_id(id),
+                            Some(tcx.call_site_extent(id, body.node_id)))
                     }
                     hir::ItemEnum(..) |
                     hir::ItemStruct(..) |
                     hir::ItemUnion(..) |
                     hir::ItemTy(..) |
                     hir::ItemImpl(..) |
-                    hir::ItemConst(..) |
-                    hir::ItemStatic(..) => {
-                        let def_id = tcx.hir.local_def_id(id);
-                        tcx.construct_parameter_environment(item.span,
-                                                            def_id,
-                                                            Some(tcx.item_extent(id)))
-                    }
                     hir::ItemTrait(..) => {
                         let def_id = tcx.hir.local_def_id(id);
                         tcx.construct_parameter_environment(item.span,
@@ -2527,14 +2530,6 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
         self.mk_region(ty::ReScope(self.node_extent(id)))
     }
 
-    pub fn visit_all_item_likes_in_krate<V,F>(self,
-                                              dep_node_fn: F,
-                                              visitor: &mut V)
-        where F: FnMut(DefId) -> DepNode<DefId>, V: ItemLikeVisitor<'gcx>
-    {
-        dep_graph::visit_all_item_likes_in_krate(self.global_tcx(), dep_node_fn, visitor);
-    }
-
     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
     /// with the name of the crate containing the impl.
     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
diff --git a/src/librustc/ty/relate.rs b/src/librustc/ty/relate.rs
index ac434c01c6a..dfa11b9c71a 100644
--- a/src/librustc/ty/relate.rs
+++ b/src/librustc/ty/relate.rs
@@ -124,14 +124,8 @@ fn relate_item_substs<'a, 'gcx, 'tcx, R>(relation: &mut R,
            a_subst,
            b_subst);
 
-    let variances;
-    let opt_variances = if relation.tcx().variance_computed.get() {
-        variances = relation.tcx().variances_of(item_def_id);
-        Some(&*variances)
-    } else {
-        None
-    };
-    relate_substs(relation, opt_variances, a_subst, b_subst)
+    let opt_variances = relation.tcx().variances_of(item_def_id);
+    relate_substs(relation, Some(&opt_variances), a_subst, b_subst)
 }
 
 pub fn relate_substs<'a, 'gcx, 'tcx, R>(relation: &mut R,
diff --git a/src/librustc/ty/subst.rs b/src/librustc/ty/subst.rs
index c591845dd63..e23003bf772 100644
--- a/src/librustc/ty/subst.rs
+++ b/src/librustc/ty/subst.rs
@@ -72,7 +72,7 @@ impl<'tcx> From<ty::Region<'tcx>> for Kind<'tcx> {
 impl<'tcx> Kind<'tcx> {
     #[inline]
     unsafe fn downcast<T>(self, tag: usize) -> Option<&'tcx T> {
-        let ptr = *self.ptr;
+        let ptr = self.ptr.get();
         if ptr & TAG_MASK == tag {
             Some(&*((ptr & !TAG_MASK) as *const _))
         } else {
@@ -102,7 +102,7 @@ impl<'tcx> fmt::Debug for Kind<'tcx> {
         } else if let Some(r) = self.as_region() {
             write!(f, "{:?}", r)
         } else {
-            write!(f, "<unknwon @ {:p}>", *self.ptr as *const ())
+            write!(f, "<unknown @ {:p}>", self.ptr.get() as *const ())
         }
     }
 }
diff --git a/src/librustc/ty/util.rs b/src/librustc/ty/util.rs
index 24dfae3c540..06d09bd350a 100644
--- a/src/librustc/ty/util.rs
+++ b/src/librustc/ty/util.rs
@@ -145,11 +145,11 @@ pub enum CopyImplementationError<'tcx> {
 ///
 /// The ordering of the cases is significant. They are sorted so that cmp::max
 /// will keep the "more erroneous" of two values.
-#[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
+#[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
 pub enum Representability {
     Representable,
     ContainsRecursive,
-    SelfRecursive,
+    SelfRecursive(Vec<Span>),
 }
 
 impl<'tcx> ParameterEnvironment<'tcx> {
@@ -1006,18 +1006,22 @@ impl<'a, 'tcx> ty::TyS<'tcx> {
 
     /// Check whether a type is representable. This means it cannot contain unboxed
     /// structural recursion. This check is needed for structs and enums.
-    pub fn is_representable(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span)
+    pub fn is_representable(&'tcx self,
+                            tcx: TyCtxt<'a, 'tcx, 'tcx>,
+                            sp: Span)
                             -> Representability {
 
         // Iterate until something non-representable is found
-        fn find_nonrepresentable<'a, 'tcx, It>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                                               sp: Span,
-                                               seen: &mut Vec<Ty<'tcx>>,
-                                               iter: It)
-                                               -> Representability
-        where It: Iterator<Item=Ty<'tcx>> {
-            iter.fold(Representability::Representable,
-                      |r, ty| cmp::max(r, is_type_structurally_recursive(tcx, sp, seen, ty)))
+        fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
+            iter.fold(Representability::Representable, |r1, r2| {
+                match (r1, r2) {
+                    (Representability::SelfRecursive(v1),
+                     Representability::SelfRecursive(v2)) => {
+                        Representability::SelfRecursive(v1.iter().map(|s| *s).chain(v2).collect())
+                    }
+                    (r1, r2) => cmp::max(r1, r2)
+                }
+            })
         }
 
         fn are_inner_types_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
@@ -1025,7 +1029,10 @@ impl<'a, 'tcx> ty::TyS<'tcx> {
                                                -> Representability {
             match ty.sty {
                 TyTuple(ref ts, _) => {
-                    find_nonrepresentable(tcx, sp, seen, ts.iter().cloned())
+                    // Find non representable
+                    fold_repr(ts.iter().map(|ty| {
+                        is_type_structurally_recursive(tcx, sp, seen, ty)
+                    }))
                 }
                 // Fixed-length vectors.
                 // FIXME(#11924) Behavior undecided for zero-length vectors.
@@ -1033,10 +1040,17 @@ impl<'a, 'tcx> ty::TyS<'tcx> {
                     is_type_structurally_recursive(tcx, sp, seen, ty)
                 }
                 TyAdt(def, substs) => {
-                    find_nonrepresentable(tcx,
-                                          sp,
-                                          seen,
-                                          def.all_fields().map(|f| f.ty(tcx, substs)))
+                    // Find non representable fields with their spans
+                    fold_repr(def.all_fields().map(|field| {
+                        let ty = field.ty(tcx, substs);
+                        let span = tcx.hir.span_if_local(field.did).unwrap_or(sp);
+                        match is_type_structurally_recursive(tcx, span, seen, ty) {
+                            Representability::SelfRecursive(_) => {
+                                Representability::SelfRecursive(vec![span])
+                            }
+                            x => x,
+                        }
+                    }))
                 }
                 TyClosure(..) => {
                     // this check is run on type definitions, so we don't expect
@@ -1075,7 +1089,7 @@ impl<'a, 'tcx> ty::TyS<'tcx> {
                                                     sp: Span,
                                                     seen: &mut Vec<Ty<'tcx>>,
                                                     ty: Ty<'tcx>) -> Representability {
-            debug!("is_type_structurally_recursive: {:?}", ty);
+            debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
 
             match ty.sty {
                 TyAdt(def, _) => {
@@ -1096,7 +1110,7 @@ impl<'a, 'tcx> ty::TyS<'tcx> {
                                 debug!("SelfRecursive: {:?} contains {:?}",
                                        seen_type,
                                        ty);
-                                return Representability::SelfRecursive;
+                                return Representability::SelfRecursive(vec![sp]);
                             }
                         }
 
diff --git a/src/librustc_borrowck/borrowck/check_loans.rs b/src/librustc_borrowck/borrowck/check_loans.rs
index 1c5a6c3985c..adabbe11f5e 100644
--- a/src/librustc_borrowck/borrowck/check_loans.rs
+++ b/src/librustc_borrowck/borrowck/check_loans.rs
@@ -469,13 +469,13 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                                                   nl, new_loan_msg);
                     err.span_label(
                             old_loan.span,
-                            &format!("first mutable borrow occurs here{}", old_loan_msg));
+                            format!("first mutable borrow occurs here{}", old_loan_msg));
                     err.span_label(
                             new_loan.span,
-                            &format!("second mutable borrow occurs here{}", new_loan_msg));
+                            format!("second mutable borrow occurs here{}", new_loan_msg));
                     err.span_label(
                             previous_end_span,
-                            &format!("first borrow ends here"));
+                            "first borrow ends here");
                     err
                 }
 
@@ -486,13 +486,13 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                                      nl);
                     err.span_label(
                             old_loan.span,
-                            &format!("first closure is constructed here"));
+                            "first closure is constructed here");
                     err.span_label(
                             new_loan.span,
-                            &format!("second closure is constructed here"));
+                            "second closure is constructed here");
                     err.span_label(
                             previous_end_span,
-                            &format!("borrow from first closure ends here"));
+                            "borrow from first closure ends here");
                     err
                 }
 
@@ -503,13 +503,13 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                                                    nl, ol_pronoun, old_loan_msg);
                     err.span_label(
                             new_loan.span,
-                            &format!("closure construction occurs here{}", new_loan_msg));
+                            format!("closure construction occurs here{}", new_loan_msg));
                     err.span_label(
                             old_loan.span,
-                            &format!("borrow occurs here{}", old_loan_msg));
+                            format!("borrow occurs here{}", old_loan_msg));
                     err.span_label(
                             previous_end_span,
-                            &format!("borrow ends here"));
+                            "borrow ends here");
                     err
                 }
 
@@ -520,13 +520,13 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                                                    nl, new_loan_msg, new_loan.kind.to_user_str());
                     err.span_label(
                             new_loan.span,
-                            &format!("borrow occurs here{}", new_loan_msg));
+                            format!("borrow occurs here{}", new_loan_msg));
                     err.span_label(
                             old_loan.span,
-                            &format!("closure construction occurs here{}", old_loan_msg));
+                            format!("closure construction occurs here{}", old_loan_msg));
                     err.span_label(
                             previous_end_span,
-                            &format!("borrow from closure ends here"));
+                            "borrow from closure ends here");
                     err
                 }
 
@@ -542,17 +542,17 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                                                    old_loan_msg);
                     err.span_label(
                             new_loan.span,
-                            &format!("{} borrow occurs here{}",
+                            format!("{} borrow occurs here{}",
                                      new_loan.kind.to_user_str(),
                                      new_loan_msg));
                     err.span_label(
                             old_loan.span,
-                            &format!("{} borrow occurs here{}",
+                            format!("{} borrow occurs here{}",
                                      old_loan.kind.to_user_str(),
                                      old_loan_msg));
                     err.span_label(
                             previous_end_span,
-                            &format!("{} borrow ends here",
+                            format!("{} borrow ends here",
                                      old_loan.kind.to_user_str()));
                     err
                 }
@@ -562,7 +562,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                 euv::ClosureCapture(span) => {
                     err.span_label(
                         span,
-                        &format!("borrow occurs due to use of `{}` in closure", nl));
+                        format!("borrow occurs due to use of `{}` in closure", nl));
                 }
                 _ => { }
             }
@@ -571,7 +571,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                 euv::ClosureCapture(span) => {
                     err.span_label(
                         span,
-                        &format!("previous borrow occurs due to use of `{}` in closure",
+                        format!("previous borrow occurs due to use of `{}` in closure",
                                  ol));
                 }
                 _ => { }
@@ -633,11 +633,11 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                                  "cannot use `{}` because it was mutably borrowed",
                                  &self.bccx.loan_path_to_string(copy_path))
                     .span_label(loan_span,
-                               &format!("borrow of `{}` occurs here",
+                               format!("borrow of `{}` occurs here",
                                        &self.bccx.loan_path_to_string(&loan_path))
                                )
                     .span_label(span,
-                               &format!("use of borrowed `{}`",
+                               format!("use of borrowed `{}`",
                                         &self.bccx.loan_path_to_string(&loan_path)))
                     .emit();
             }
@@ -662,12 +662,12 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                                          &self.bccx.loan_path_to_string(move_path));
                         err.span_label(
                             loan_span,
-                            &format!("borrow of `{}` occurs here",
+                            format!("borrow of `{}` occurs here",
                                     &self.bccx.loan_path_to_string(&loan_path))
                             );
                         err.span_label(
                             span,
-                            &format!("move into closure occurs here")
+                            "move into closure occurs here"
                             );
                         err
                     }
@@ -679,12 +679,12 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                                          &self.bccx.loan_path_to_string(move_path));
                         err.span_label(
                             loan_span,
-                            &format!("borrow of `{}` occurs here",
+                            format!("borrow of `{}` occurs here",
                                     &self.bccx.loan_path_to_string(&loan_path))
                             );
                         err.span_label(
                             span,
-                            &format!("move out of `{}` occurs here",
+                            format!("move out of `{}` occurs here",
                                 &self.bccx.loan_path_to_string(move_path))
                             );
                         err
@@ -857,10 +857,10 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
                          "cannot assign to `{}` because it is borrowed",
                          self.bccx.loan_path_to_string(loan_path))
             .span_label(loan.span,
-                       &format!("borrow of `{}` occurs here",
+                       format!("borrow of `{}` occurs here",
                                self.bccx.loan_path_to_string(loan_path)))
             .span_label(span,
-                       &format!("assignment to borrowed `{}` occurs here",
+                       format!("assignment to borrowed `{}` occurs here",
                                self.bccx.loan_path_to_string(loan_path)))
             .emit();
     }
diff --git a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs
index b7ce9d98233..1ee6d565d0d 100644
--- a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs
+++ b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs
@@ -94,7 +94,7 @@ fn report_move_errors<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, errors: &Vec<Move
         }
         if let NoteClosureEnv(upvar_id) = error.move_from.note {
             err.span_label(bccx.tcx.hir.span(upvar_id.var_id),
-                           &"captured outer variable");
+                           "captured outer variable");
         }
         err.emit();
 
@@ -147,7 +147,7 @@ fn report_cannot_move_out_of<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
                              move_from.descriptive_string(bccx.tcx));
             err.span_label(
                 move_from.span,
-                &format!("cannot move out of {}", move_from.descriptive_string(bccx.tcx))
+                format!("cannot move out of {}", move_from.descriptive_string(bccx.tcx))
                 );
             err
         }
@@ -160,7 +160,7 @@ fn report_cannot_move_out_of<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
                                                    "cannot move out of type `{}`, \
                                                     a non-copy array",
                                                    b.ty);
-                    err.span_label(move_from.span, &format!("cannot move out of here"));
+                    err.span_label(move_from.span, "cannot move out of here");
                     err
                 }
                 (_, Kind::Pattern) => {
@@ -177,7 +177,7 @@ fn report_cannot_move_out_of<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
                                                    "cannot move out of type `{}`, \
                                                    which implements the `Drop` trait",
                                                    b.ty);
-                    err.span_label(move_from.span, &format!("cannot move out of here"));
+                    err.span_label(move_from.span, "cannot move out of here");
                     err
                 },
                 _ => {
@@ -198,12 +198,12 @@ fn note_move_destination(mut err: DiagnosticBuilder,
     if is_first_note {
         err.span_label(
             move_to_span,
-            &format!("hint: to prevent move, use `ref {0}` or `ref mut {0}`",
+            format!("hint: to prevent move, use `ref {0}` or `ref mut {0}`",
                      pat_name));
         err
     } else {
         err.span_label(move_to_span,
-                      &format!("...and here (use `ref {0}` or `ref mut {0}`)",
+                      format!("...and here (use `ref {0}` or `ref mut {0}`)",
                                pat_name));
         err
     }
diff --git a/src/librustc_borrowck/borrowck/mir/gather_moves.rs b/src/librustc_borrowck/borrowck/mir/gather_moves.rs
index 81037fe40d9..ed5e539f245 100644
--- a/src/librustc_borrowck/borrowck/mir/gather_moves.rs
+++ b/src/librustc_borrowck/borrowck/mir/gather_moves.rs
@@ -43,7 +43,7 @@ mod indexes {
                     unsafe { $Index(NonZero::new(idx + 1)) }
                 }
                 fn index(self) -> usize {
-                    *self.0 - 1
+                    self.0.get() - 1
                 }
             }
 
diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs
index f8073455bd0..7eb73a87532 100644
--- a/src/librustc_borrowck/borrowck/mod.rs
+++ b/src/librustc_borrowck/borrowck/mod.rs
@@ -546,7 +546,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                     "{} of possibly uninitialized variable: `{}`",
                     verb,
                     self.loan_path_to_string(lp))
-                .span_label(use_span, &format!("use of possibly uninitialized `{}`",
+                .span_label(use_span, format!("use of possibly uninitialized `{}`",
                     self.loan_path_to_string(lp)))
                 .emit();
                 return;
@@ -616,12 +616,12 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
         err = if use_span == move_span {
             err.span_label(
                 use_span,
-                &format!("value moved{} here in previous iteration of loop",
+                format!("value moved{} here in previous iteration of loop",
                          move_note));
             err
         } else {
-            err.span_label(use_span, &format!("value {} here after move", verb_participle))
-               .span_label(move_span, &format!("value moved{} here", move_note));
+            err.span_label(use_span, format!("value {} here after move", verb_participle))
+               .span_label(move_span, format!("value moved{} here", move_note));
             err
         };
 
@@ -657,9 +657,9 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
             self.tcx.sess, span, E0384,
             "re-assignment of immutable variable `{}`",
             self.loan_path_to_string(lp));
-        err.span_label(span, &format!("re-assignment of immutable variable"));
+        err.span_label(span, "re-assignment of immutable variable");
         if span != assign.span {
-            err.span_label(assign.span, &format!("first assignment to `{}`",
+            err.span_label(assign.span, format!("first assignment to `{}`",
                                               self.loan_path_to_string(lp)));
         }
         err.emit();
@@ -821,7 +821,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                 let mut err = struct_span_err!(
                     self.tcx.sess, span, E0389,
                     "{} in a `&` reference", prefix);
-                err.span_label(span, &"assignment into an immutable reference");
+                err.span_label(span, "assignment into an immutable reference");
                 err
             }
         };
@@ -914,7 +914,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                         }
                         db.span_label(
                             let_span,
-                            &format!("consider changing this to `mut {}`", snippet)
+                            format!("consider changing this to `mut {}`", snippet)
                         );
                     }
                 }
@@ -927,7 +927,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                         if let Ok(snippet) = snippet {
                             db.span_label(
                                 let_span,
-                                &format!("consider changing this to `{}`",
+                                format!("consider changing this to `{}`",
                                          snippet.replace("ref ", "ref mut "))
                             );
                         }
@@ -936,7 +936,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                         if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
                             if let Some(msg) =
                                  self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
-                                db.span_label(local_ty.span, &msg);
+                                db.span_label(local_ty.span, msg);
                             }
                         }
                     }
@@ -950,7 +950,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
 
                 if let hir_map::Node::NodeField(ref field) = self.tcx.hir.get(node_id) {
                     if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
-                        db.span_label(field.ty.span, &msg);
+                        db.span_label(field.ty.span, msg);
                     }
                 }
             }
@@ -975,10 +975,10 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                           which is owned by the current function",
                          cmt_path_or_string)
             .span_label(capture_span,
-                       &format!("{} is borrowed here",
+                       format!("{} is borrowed here",
                                 cmt_path_or_string))
             .span_label(err.span,
-                       &format!("may outlive borrowed value {}",
+                       format!("may outlive borrowed value {}",
                                 cmt_path_or_string))
             .span_suggestion(err.span,
                              &format!("to force the closure to take ownership of {} \
@@ -1029,15 +1029,15 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                         match db.span.primary_span() {
                             Some(primary) => {
                                 db.span = MultiSpan::from_span(s);
-                                db.span_label(primary, &format!("capture occurs here"));
-                                db.span_label(s, &"does not live long enough");
+                                db.span_label(primary, "capture occurs here");
+                                db.span_label(s, "does not live long enough");
                                 true
                             }
                             None => false
                         }
                     }
                     _ => {
-                        db.span_label(error_span, &"does not live long enough");
+                        db.span_label(error_span, "does not live long enough");
                         false
                     }
                 };
@@ -1049,7 +1049,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                     (Some(s1), Some(s2)) if s1 == s2 => {
                         if !is_closure {
                             db.span = MultiSpan::from_span(s1);
-                            db.span_label(error_span, &value_msg);
+                            db.span_label(error_span, value_msg);
                             let msg = match opt_loan_path(&err.cmt) {
                                 None => value_kind.to_string(),
                                 Some(lp) => {
@@ -1057,29 +1057,29 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                                 }
                             };
                             db.span_label(s1,
-                                          &format!("{} dropped here while still borrowed", msg));
+                                          format!("{} dropped here while still borrowed", msg));
                         } else {
-                            db.span_label(s1, &format!("{} dropped before borrower", value_kind));
+                            db.span_label(s1, format!("{} dropped before borrower", value_kind));
                         }
                         db.note("values in a scope are dropped in the opposite order \
                                 they are created");
                     }
                     (Some(s1), Some(s2)) if !is_closure => {
                         db.span = MultiSpan::from_span(s2);
-                        db.span_label(error_span, &value_msg);
+                        db.span_label(error_span, value_msg);
                         let msg = match opt_loan_path(&err.cmt) {
                             None => value_kind.to_string(),
                             Some(lp) => {
                                 format!("`{}`", self.loan_path_to_string(&lp))
                             }
                         };
-                        db.span_label(s2, &format!("{} dropped here while still borrowed", msg));
-                        db.span_label(s1, &format!("{} needs to live until here", value_kind));
+                        db.span_label(s2, format!("{} dropped here while still borrowed", msg));
+                        db.span_label(s1, format!("{} needs to live until here", value_kind));
                     }
                     _ => {
                         match sub_span {
                             Some(s) => {
-                                db.span_label(s, &format!("{} needs to live until here",
+                                db.span_label(s, format!("{} needs to live until here",
                                                           value_kind));
                             }
                             None => {
@@ -1092,7 +1092,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
                         }
                         match super_span {
                             Some(s) => {
-                                db.span_label(s, &format!("{} only lives until here", value_kind));
+                                db.span_label(s, format!("{} only lives until here", value_kind));
                             }
                             None => {
                                 self.tcx.note_and_explain_region(
@@ -1162,23 +1162,23 @@ before rustc 1.16, this temporary lived longer - see issue #39283 \
             }
             _ => {
                 if let Categorization::Deref(..) = err.cmt.cat {
-                    db.span_label(*error_span, &"cannot borrow as mutable");
+                    db.span_label(*error_span, "cannot borrow as mutable");
                 } else if let Categorization::Local(local_id) = err.cmt.cat {
                     let span = self.tcx.hir.span(local_id);
                     if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
                         if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
-                            db.span_label(*error_span, &format!("cannot reborrow mutably"));
-                            db.span_label(*error_span, &format!("try removing `&mut` here"));
+                            db.span_label(*error_span, "cannot reborrow mutably");
+                            db.span_label(*error_span, "try removing `&mut` here");
                         } else {
-                            db.span_label(*error_span, &format!("cannot borrow mutably"));
+                            db.span_label(*error_span, "cannot borrow mutably");
                         }
                     } else {
-                        db.span_label(*error_span, &format!("cannot borrow mutably"));
+                        db.span_label(*error_span, "cannot borrow mutably");
                     }
                 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
                     if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
                         db.span_label(*error_span,
-                                      &"cannot mutably borrow immutable field");
+                                      "cannot mutably borrow immutable field");
                     }
                 }
             }
diff --git a/src/librustc_const_eval/check_match.rs b/src/librustc_const_eval/check_match.rs
index 6ec5f38aa5b..cd31290eb55 100644
--- a/src/librustc_const_eval/check_match.rs
+++ b/src/librustc_const_eval/check_match.rs
@@ -258,7 +258,7 @@ impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
                 "refutable pattern in {}: `{}` not covered",
                 origin, pattern_string
             );
-            diag.span_label(pat.span, &format!("pattern `{}` not covered", pattern_string));
+            diag.span_label(pat.span, format!("pattern `{}` not covered", pattern_string));
             diag.emit();
         });
     }
@@ -328,7 +328,7 @@ fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
                                 let span = first_pat.0.span;
                                 struct_span_err!(cx.tcx.sess, span, E0162,
                                                 "irrefutable if-let pattern")
-                                    .span_label(span, &format!("irrefutable pattern"))
+                                    .span_label(span, "irrefutable pattern")
                                     .emit();
                                 printed_if_let_err = true;
                             }
@@ -355,7 +355,7 @@ fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
                                 1 => {
                                     struct_span_err!(cx.tcx.sess, span, E0165,
                                                      "irrefutable while-let pattern")
-                                        .span_label(span, &format!("irrefutable pattern"))
+                                        .span_label(span, "irrefutable pattern")
                                         .emit();
                                 },
                                 _ => bug!(),
@@ -369,7 +369,7 @@ fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
                             diagnostic.set_span(pat.span);
                             // if we had a catchall pattern, hint at that
                             if let Some(catchall) = catchall {
-                                diagnostic.span_label(pat.span, &"this is an unreachable pattern");
+                                diagnostic.span_label(pat.span, "this is an unreachable pattern");
                                 diagnostic.span_note(catchall, "this pattern matches any value");
                             }
                             cx.tcx.sess.add_lint_diagnostic(lint::builtin::UNREACHABLE_PATTERNS,
@@ -426,7 +426,7 @@ fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
                         "refutable pattern in `for` loop binding: \
                                 `{}` not covered",
                                 pattern_string)
-                        .span_label(sp, &format!("pattern `{}` not covered", pattern_string))
+                        .span_label(sp, format!("pattern `{}` not covered", pattern_string))
                         .emit();
                 },
                 _ => {
@@ -453,7 +453,7 @@ fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
                     create_e0004(cx.tcx.sess, sp,
                                  format!("non-exhaustive patterns: {} not covered",
                                          joined_patterns))
-                        .span_label(sp, &label_text)
+                        .span_label(sp, label_text)
                         .emit();
                 },
             }
@@ -485,18 +485,18 @@ fn check_legality_of_move_bindings(cx: &MatchVisitor,
         if sub.map_or(false, |p| p.contains_bindings()) {
             struct_span_err!(cx.tcx.sess, p.span, E0007,
                              "cannot bind by-move with sub-bindings")
-                .span_label(p.span, &format!("binds an already bound by-move value by moving it"))
+                .span_label(p.span, "binds an already bound by-move value by moving it")
                 .emit();
         } else if has_guard {
             struct_span_err!(cx.tcx.sess, p.span, E0008,
                       "cannot bind by-move into a pattern guard")
-                .span_label(p.span, &format!("moves value into pattern guard"))
+                .span_label(p.span, "moves value into pattern guard")
                 .emit();
         } else if by_ref_span.is_some() {
             struct_span_err!(cx.tcx.sess, p.span, E0009,
                             "cannot bind by-move and by-ref in the same pattern")
-                    .span_label(p.span, &format!("by-move pattern here"))
-                    .span_label(by_ref_span.unwrap(), &format!("both by-ref and by-move used"))
+                    .span_label(p.span, "by-move pattern here")
+                    .span_label(by_ref_span.unwrap(), "both by-ref and by-move used")
                     .emit();
         }
     };
@@ -546,7 +546,7 @@ impl<'a, 'gcx, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'gcx> {
             ty::MutBorrow => {
                 struct_span_err!(self.cx.tcx.sess, span, E0301,
                           "cannot mutably borrow in a pattern guard")
-                    .span_label(span, &format!("borrowed mutably in pattern guard"))
+                    .span_label(span, "borrowed mutably in pattern guard")
                     .emit();
             }
             ty::ImmBorrow | ty::UniqueImmBorrow => {}
@@ -557,7 +557,7 @@ impl<'a, 'gcx, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'gcx> {
         match mode {
             MutateMode::JustWrite | MutateMode::WriteAndRead => {
                 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
-                    .span_label(span, &format!("assignment in pattern guard"))
+                    .span_label(span, "assignment in pattern guard")
                     .emit();
             }
             MutateMode::Init => {}
@@ -588,7 +588,7 @@ impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
                 if !self.bindings_allowed {
                     struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
                                      "pattern bindings are not allowed after an `@`")
-                        .span_label(pat.span,  &format!("not allowed after `@`"))
+                        .span_label(pat.span,  "not allowed after `@`")
                         .emit();
                 }
 
diff --git a/src/librustc_data_structures/array_vec.rs b/src/librustc_data_structures/array_vec.rs
index 848e5a076bb..078bb801751 100644
--- a/src/librustc_data_structures/array_vec.rs
+++ b/src/librustc_data_structures/array_vec.rs
@@ -255,7 +255,7 @@ impl<'a, A: Array> Drop for Drain<'a, A> {
 
         if self.tail_len > 0 {
             unsafe {
-                let source_array_vec = &mut *self.array_vec.as_mut_ptr();
+                let source_array_vec = self.array_vec.as_mut();
                 // memmove back untouched tail, update to new length
                 let start = source_array_vec.len();
                 let tail = self.tail_start;
diff --git a/src/librustc_data_structures/flock.rs b/src/librustc_data_structures/flock.rs
index 32f0fd41997..ff1ebb11b72 100644
--- a/src/librustc_data_structures/flock.rs
+++ b/src/librustc_data_structures/flock.rs
@@ -247,11 +247,11 @@ mod imp {
     use std::os::windows::raw::HANDLE;
     use std::path::Path;
     use std::fs::{File, OpenOptions};
-    use std::os::raw::{c_ulong, c_ulonglong, c_int};
+    use std::os::raw::{c_ulong, c_int};
 
     type DWORD = c_ulong;
     type BOOL = c_int;
-    type ULONG_PTR = c_ulonglong;
+    type ULONG_PTR = usize;
 
     type LPOVERLAPPED = *mut OVERLAPPED;
     const LOCKFILE_EXCLUSIVE_LOCK: DWORD = 0x00000002;
diff --git a/src/librustc_data_structures/obligation_forest/node_index.rs b/src/librustc_data_structures/obligation_forest/node_index.rs
index 1063bb3611e..023c56ca59b 100644
--- a/src/librustc_data_structures/obligation_forest/node_index.rs
+++ b/src/librustc_data_structures/obligation_forest/node_index.rs
@@ -23,6 +23,6 @@ impl NodeIndex {
     }
 
     pub fn get(self) -> usize {
-        (*self.index - 1) as usize
+        (self.index.get() - 1) as usize
     }
 }
diff --git a/src/librustc_data_structures/stable_hasher.rs b/src/librustc_data_structures/stable_hasher.rs
index 95f063976d4..635b95d861d 100644
--- a/src/librustc_data_structures/stable_hasher.rs
+++ b/src/librustc_data_structures/stable_hasher.rs
@@ -283,6 +283,16 @@ impl<CTX> HashStable<CTX> for str {
     }
 }
 
+
+impl<CTX> HashStable<CTX> for String {
+    #[inline]
+    fn hash_stable<W: StableHasherResult>(&self,
+                                          hcx: &mut CTX,
+                                          hasher: &mut StableHasher<W>) {
+        (&self[..]).hash_stable(hcx, hasher);
+    }
+}
+
 impl<CTX> HashStable<CTX> for bool {
     #[inline]
     fn hash_stable<W: StableHasherResult>(&self,
diff --git a/src/librustc_data_structures/transitive_relation.rs b/src/librustc_data_structures/transitive_relation.rs
index b0fca5c0ff3..46463944043 100644
--- a/src/librustc_data_structures/transitive_relation.rs
+++ b/src/librustc_data_structures/transitive_relation.rs
@@ -9,21 +9,23 @@
 // except according to those terms.
 
 use bitvec::BitMatrix;
-use stable_hasher::{HashStable, StableHasher, StableHasherResult};
+use fx::FxHashMap;
 use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
+use stable_hasher::{HashStable, StableHasher, StableHasherResult};
 use std::cell::RefCell;
 use std::fmt::Debug;
+use std::hash::Hash;
 use std::mem;
 
 
-
 #[derive(Clone)]
-pub struct TransitiveRelation<T: Debug + PartialEq> {
-    // List of elements. This is used to map from a T to a usize.  We
-    // expect domain to be small so just use a linear list versus a
-    // hashmap or something.
+pub struct TransitiveRelation<T: Clone + Debug + Eq + Hash + Clone> {
+    // List of elements. This is used to map from a T to a usize.
     elements: Vec<T>,
 
+    // Maps each element to an index.
+    map: FxHashMap<T, Index>,
+
     // List of base edges in the graph. Require to compute transitive
     // closure.
     edges: Vec<Edge>,
@@ -40,19 +42,20 @@ pub struct TransitiveRelation<T: Debug + PartialEq> {
     closure: RefCell<Option<BitMatrix>>,
 }
 
-#[derive(Clone, PartialEq, PartialOrd, RustcEncodable, RustcDecodable)]
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
 struct Index(usize);
 
-#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
 struct Edge {
     source: Index,
     target: Index,
 }
 
-impl<T: Debug + PartialEq> TransitiveRelation<T> {
+impl<T: Clone + Debug + Eq + Hash + Clone> TransitiveRelation<T> {
     pub fn new() -> TransitiveRelation<T> {
         TransitiveRelation {
             elements: vec![],
+            map: FxHashMap(),
             edges: vec![],
             closure: RefCell::new(None),
         }
@@ -63,21 +66,27 @@ impl<T: Debug + PartialEq> TransitiveRelation<T> {
     }
 
     fn index(&self, a: &T) -> Option<Index> {
-        self.elements.iter().position(|e| *e == *a).map(Index)
+        self.map.get(a).cloned()
     }
 
     fn add_index(&mut self, a: T) -> Index {
-        match self.index(&a) {
-            Some(i) => i,
-            None => {
-                self.elements.push(a);
-
-                // if we changed the dimensions, clear the cache
-                *self.closure.borrow_mut() = None;
-
-                Index(self.elements.len() - 1)
-            }
-        }
+        let &mut TransitiveRelation {
+            ref mut elements,
+            ref closure,
+            ref mut map,
+            ..
+        } = self;
+
+        map.entry(a.clone())
+           .or_insert_with(|| {
+               elements.push(a);
+
+               // if we changed the dimensions, clear the cache
+               *closure.borrow_mut() = None;
+
+               Index(elements.len() - 1)
+           })
+           .clone()
     }
 
     /// Applies the (partial) function to each edge and returns a new
@@ -85,7 +94,7 @@ impl<T: Debug + PartialEq> TransitiveRelation<T> {
     /// `None`.
     pub fn maybe_map<F, U>(&self, mut f: F) -> Option<TransitiveRelation<U>>
         where F: FnMut(&T) -> Option<U>,
-              U: Debug + PartialEq,
+              U: Clone + Debug + Eq + Hash + Clone,
     {
         let mut result = TransitiveRelation::new();
         for edge in &self.edges {
@@ -125,6 +134,20 @@ impl<T: Debug + PartialEq> TransitiveRelation<T> {
         }
     }
 
+    /// Returns a vector of all things less than `a`.
+    ///
+    /// Really this probably ought to be `impl Iterator<Item=&T>`, but
+    /// I'm too lazy to make that work, and -- given the caching
+    /// strategy -- it'd be a touch tricky anyhow.
+    pub fn less_than(&self, a: &T) -> Vec<&T> {
+        match self.index(a) {
+            Some(a) => self.with_closure(|closure| {
+                closure.iter(a.0).map(|i| &self.elements[i]).collect()
+            }),
+            None => vec![],
+        }
+    }
+
     /// Picks what I am referring to as the "postdominating"
     /// upper-bound for `a` and `b`. This is usually the least upper
     /// bound, but in cases where there is no single least upper
@@ -335,7 +358,7 @@ fn pare_down(candidates: &mut Vec<usize>, closure: &BitMatrix) {
 }
 
 impl<T> Encodable for TransitiveRelation<T>
-    where T: Encodable + Debug + PartialEq
+    where T: Clone + Encodable + Debug + Eq + Hash + Clone
 {
     fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> {
         s.emit_struct("TransitiveRelation", 2, |s| {
@@ -347,19 +370,23 @@ impl<T> Encodable for TransitiveRelation<T>
 }
 
 impl<T> Decodable for TransitiveRelation<T>
-    where T: Decodable + Debug + PartialEq
+    where T: Clone + Decodable + Debug + Eq + Hash + Clone
 {
     fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
         d.read_struct("TransitiveRelation", 2, |d| {
-            let elements = d.read_struct_field("elements", 0, |d| Decodable::decode(d))?;
+            let elements: Vec<T> = d.read_struct_field("elements", 0, |d| Decodable::decode(d))?;
             let edges = d.read_struct_field("edges", 1, |d| Decodable::decode(d))?;
-            Ok(TransitiveRelation { elements, edges, closure: RefCell::new(None) })
+            let map = elements.iter()
+                              .enumerate()
+                              .map(|(index, elem)| (elem.clone(), Index(index)))
+                              .collect();
+            Ok(TransitiveRelation { elements, edges, map, closure: RefCell::new(None) })
         })
     }
 }
 
 impl<CTX, T> HashStable<CTX> for TransitiveRelation<T>
-    where T: HashStable<CTX> + PartialEq + Debug
+    where T: HashStable<CTX> + Eq + Debug + Clone + Hash
 {
     fn hash_stable<W: StableHasherResult>(&self,
                                           hcx: &mut CTX,
@@ -369,6 +396,8 @@ impl<CTX, T> HashStable<CTX> for TransitiveRelation<T>
         let TransitiveRelation {
             ref elements,
             ref edges,
+            // "map" is just a copy of elements vec
+            map: _,
             // "closure" is just a copy of the data above
             closure: _
         } = *self;
diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs
index 9f0f567b6ce..5f14890665c 100644
--- a/src/librustc_driver/driver.rs
+++ b/src/librustc_driver/driver.rs
@@ -1155,8 +1155,7 @@ fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
             // Build a list of files used to compile the output and
             // write Makefile-compatible dependency rules
             let files: Vec<String> = sess.codemap()
-                                         .files
-                                         .borrow()
+                                         .files()
                                          .iter()
                                          .filter(|fmap| fmap.is_real_file())
                                          .filter(|fmap| !fmap.is_imported())
diff --git a/src/librustc_driver/target_features.rs b/src/librustc_driver/target_features.rs
index 4f3abbb362f..718f2b51506 100644
--- a/src/librustc_driver/target_features.rs
+++ b/src/librustc_driver/target_features.rs
@@ -27,6 +27,8 @@ const X86_WHITELIST: &'static [&'static str] = &["avx\0", "avx2\0", "bmi\0", "bm
                                                  "ssse3\0", "tbm\0", "lzcnt\0", "popcnt\0",
                                                  "sse4a\0", "rdrnd\0", "rdseed\0", "fma\0"];
 
+const HEXAGON_WHITELIST: &'static [&'static str] = &["hvx\0", "hvx-double\0"];
+
 /// Add `target_feature = "..."` cfgs for a variety of platform
 /// specific features (SSE, NEON etc.).
 ///
@@ -38,6 +40,7 @@ pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session) {
     let whitelist = match &*sess.target.target.arch {
         "arm" => ARM_WHITELIST,
         "x86" | "x86_64" => X86_WHITELIST,
+        "hexagon" => HEXAGON_WHITELIST,
         _ => &[],
     };
 
diff --git a/src/librustc_errors/diagnostic.rs b/src/librustc_errors/diagnostic.rs
index 38fa35ecb12..0822f713499 100644
--- a/src/librustc_errors/diagnostic.rs
+++ b/src/librustc_errors/diagnostic.rs
@@ -114,9 +114,8 @@ impl Diagnostic {
     /// all, and you just supplied a `Span` to create the diagnostic,
     /// then the snippet will just include that `Span`, which is
     /// called the primary span.
-    pub fn span_label(&mut self, span: Span, label: &fmt::Display)
-                      -> &mut Self {
-        self.span.push_span_label(span, format!("{}", label));
+    pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
+        self.span.push_span_label(span, label.into());
         self
     }
 
diff --git a/src/librustc_errors/diagnostic_builder.rs b/src/librustc_errors/diagnostic_builder.rs
index 9dfd47b8464..a9c2bbeba2a 100644
--- a/src/librustc_errors/diagnostic_builder.rs
+++ b/src/librustc_errors/diagnostic_builder.rs
@@ -112,8 +112,10 @@ impl<'a> DiagnosticBuilder<'a> {
     /// all, and you just supplied a `Span` to create the diagnostic,
     /// then the snippet will just include that `Span`, which is
     /// called the primary span.
-    forward!(pub fn span_label(&mut self, span: Span, label: &fmt::Display)
-                               -> &mut Self);
+    pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
+        self.diagnostic.span_label(span, label);
+        self
+    }
 
     forward!(pub fn note_expected_found(&mut self,
                                         label: &fmt::Display,
diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs
index 1a38018e1b3..53999eb9138 100644
--- a/src/librustc_errors/emitter.rs
+++ b/src/librustc_errors/emitter.rs
@@ -270,8 +270,10 @@ impl EmitterWriter {
                           line: &Line,
                           width_offset: usize,
                           code_offset: usize) -> Vec<(usize, Style)> {
-        let source_string = file.get_line(line.line_index - 1)
-            .unwrap_or("");
+        let source_string = match file.get_line(line.line_index - 1) {
+            Some(s) => s,
+            None => return Vec::new(),
+        };
 
         let line_offset = buffer.num_lines();
 
@@ -909,6 +911,11 @@ impl EmitterWriter {
 
         // Print out the annotate source lines that correspond with the error
         for annotated_file in annotated_files {
+            // we can't annotate anything if the source is unavailable.
+            if annotated_file.file.src.is_none() {
+                continue;
+            }
+
             // print out the span location and spacer before we print the annotated source
             // to do this, we need to know if this span will be primary
             let is_primary = primary_lo.file.name == annotated_file.file.name;
diff --git a/src/librustc_errors/lib.rs b/src/librustc_errors/lib.rs
index 02d8297dd46..db8c9ac306b 100644
--- a/src/librustc_errors/lib.rs
+++ b/src/librustc_errors/lib.rs
@@ -388,6 +388,14 @@ impl Handler {
     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
         self.emit(&sp.into(), msg, Note);
     }
+    pub fn span_note_diag<'a>(&'a self,
+                              sp: Span,
+                              msg: &str)
+                              -> DiagnosticBuilder<'a> {
+        let mut db = DiagnosticBuilder::new(self, Note, msg);
+        db.set_span(sp);
+        db
+    }
     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
         self.span_bug(sp, &format!("unimplemented {}", msg));
     }
diff --git a/src/librustc_incremental/assert_dep_graph.rs b/src/librustc_incremental/assert_dep_graph.rs
index 897ca0f2957..39fe2188f68 100644
--- a/src/librustc_incremental/assert_dep_graph.rs
+++ b/src/librustc_incremental/assert_dep_graph.rs
@@ -51,7 +51,7 @@ use rustc::ty::TyCtxt;
 use rustc_data_structures::fx::FxHashSet;
 use rustc_data_structures::graph::{Direction, INCOMING, OUTGOING, NodeIndex};
 use rustc::hir;
-use rustc::hir::itemlikevisit::ItemLikeVisitor;
+use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
 use rustc::ich::{ATTR_IF_THIS_CHANGED, ATTR_THEN_THIS_WOULD_NEED};
 use graphviz::IntoCow;
 use std::env;
@@ -80,7 +80,7 @@ pub fn assert_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
                                           if_this_changed: vec![],
                                           then_this_would_need: vec![] };
         visitor.process_attrs(ast::CRATE_NODE_ID, &tcx.hir.krate().attrs);
-        tcx.hir.krate().visit_all_item_likes(&mut visitor);
+        tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
         (visitor.if_this_changed, visitor.then_this_would_need)
     };
 
@@ -154,7 +154,7 @@ impl<'a, 'tcx> IfThisChanged<'a, 'tcx> {
                     None => {
                         self.tcx.sess.span_fatal(
                             attr.span,
-                            &format!("missing DepNode variant"));
+                            "missing DepNode variant");
                     }
                 };
                 self.then_this_would_need.push((attr.span,
@@ -166,17 +166,29 @@ impl<'a, 'tcx> IfThisChanged<'a, 'tcx> {
     }
 }
 
-impl<'a, 'tcx> ItemLikeVisitor<'tcx> for IfThisChanged<'a, 'tcx> {
+impl<'a, 'tcx> Visitor<'tcx> for IfThisChanged<'a, 'tcx> {
+    fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
+        NestedVisitorMap::OnlyBodies(&self.tcx.hir)
+    }
+
     fn visit_item(&mut self, item: &'tcx hir::Item) {
         self.process_attrs(item.id, &item.attrs);
+        intravisit::walk_item(self, item);
     }
 
     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
         self.process_attrs(trait_item.id, &trait_item.attrs);
+        intravisit::walk_trait_item(self, trait_item);
     }
 
     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
         self.process_attrs(impl_item.id, &impl_item.attrs);
+        intravisit::walk_impl_item(self, impl_item);
+    }
+
+    fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
+        self.process_attrs(s.id, &s.attrs);
+        intravisit::walk_struct_field(self, s);
     }
 }
 
@@ -189,7 +201,7 @@ fn check_paths<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
         for &(target_span, _, _, _) in then_this_would_need {
             tcx.sess.span_err(
                 target_span,
-                &format!("no #[rustc_if_this_changed] annotation detected"));
+                "no #[rustc_if_this_changed] annotation detected");
 
         }
         return;
@@ -207,7 +219,7 @@ fn check_paths<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             } else {
                 tcx.sess.span_err(
                     target_span,
-                    &format!("OK"));
+                    "OK");
             }
         }
     }
diff --git a/src/librustc_incremental/calculate_svh/mod.rs b/src/librustc_incremental/calculate_svh/mod.rs
index c67866971e1..6f5cc1f3f45 100644
--- a/src/librustc_incremental/calculate_svh/mod.rs
+++ b/src/librustc_incremental/calculate_svh/mod.rs
@@ -29,9 +29,10 @@
 
 use std::cell::RefCell;
 use std::hash::Hash;
+use std::sync::Arc;
 use rustc::dep_graph::DepNode;
 use rustc::hir;
-use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
+use rustc::hir::def_id::{LOCAL_CRATE, CRATE_DEF_INDEX, DefId};
 use rustc::hir::itemlikevisit::ItemLikeVisitor;
 use rustc::ich::{Fingerprint, StableHashingContext};
 use rustc::ty::TyCtxt;
@@ -60,6 +61,10 @@ impl IncrementalHashesMap {
         }
     }
 
+    pub fn get(&self, k: &DepNode<DefId>) -> Option<&Fingerprint> {
+        self.hashes.get(k)
+    }
+
     pub fn insert(&mut self, k: DepNode<DefId>, v: Fingerprint) -> Option<Fingerprint> {
         self.hashes.insert(k, v)
     }
@@ -140,14 +145,34 @@ impl<'a, 'tcx: 'a> ComputeItemHashesVisitor<'a, 'tcx> {
             let hcx = &mut self.hcx;
             let mut item_hashes: Vec<_> =
                 self.hashes.iter()
-                           .map(|(item_dep_node, &item_hash)| {
-                               // convert from a DepNode<DefId> tp a
-                               // DepNode<u64> where the u64 is the
-                               // hash of the def-id's def-path:
-                               let item_dep_node =
-                                   item_dep_node.map_def(|&did| Some(hcx.def_path_hash(did)))
-                                                .unwrap();
-                               (item_dep_node, item_hash)
+                           .filter_map(|(item_dep_node, &item_hash)| {
+                                // This `match` determines what kinds of nodes
+                                // go into the SVH:
+                                match *item_dep_node {
+                                    DepNode::Hir(_) |
+                                    DepNode::HirBody(_) => {
+                                        // We want to incoporate these into the
+                                        // SVH.
+                                    }
+                                    DepNode::FileMap(..) => {
+                                        // These don't make a semantic
+                                        // difference, filter them out.
+                                        return None
+                                    }
+                                    ref other => {
+                                        bug!("Found unexpected DepNode during \
+                                              SVH computation: {:?}",
+                                             other)
+                                    }
+                                }
+
+                                // Convert from a DepNode<DefId> to a
+                                // DepNode<u64> where the u64 is the hash of
+                                // the def-id's def-path:
+                                let item_dep_node =
+                                    item_dep_node.map_def(|&did| Some(hcx.def_path_hash(did)))
+                                                 .unwrap();
+                                Some((item_dep_node, item_hash))
                            })
                            .collect();
             item_hashes.sort_unstable(); // avoid artificial dependencies on item ordering
@@ -229,6 +254,24 @@ pub fn compute_incremental_hashes_map<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
             visitor.compute_and_store_ich_for_item_like(DepNode::Hir(def_id), false, macro_def);
             visitor.compute_and_store_ich_for_item_like(DepNode::HirBody(def_id), true, macro_def);
         }
+
+        for filemap in tcx.sess
+                          .codemap()
+                          .files_untracked()
+                          .iter()
+                          .filter(|fm| !fm.is_imported()) {
+            assert_eq!(LOCAL_CRATE.as_u32(), filemap.crate_of_origin);
+            let def_id = DefId {
+                krate: LOCAL_CRATE,
+                index: CRATE_DEF_INDEX,
+            };
+            let name = Arc::new(filemap.name.clone());
+            let dep_node = DepNode::FileMap(def_id, name);
+            let mut hasher = IchHasher::new();
+            filemap.hash_stable(&mut visitor.hcx, &mut hasher);
+            let fingerprint = hasher.finish();
+            visitor.hashes.insert(dep_node, fingerprint);
+        }
     });
 
     tcx.sess.perf_stats.incr_comp_hashes_count.set(visitor.hashes.len() as u64);
diff --git a/src/librustc_incremental/persist/data.rs b/src/librustc_incremental/persist/data.rs
index 8a1af5dd08d..b016ff34bc5 100644
--- a/src/librustc_incremental/persist/data.rs
+++ b/src/librustc_incremental/persist/data.rs
@@ -99,7 +99,11 @@ pub struct SerializedMetadataHashes {
     /// where `X` refers to some item in this crate. That `X` will be
     /// a `DefPathIndex` that gets retracted to the current `DefId`
     /// (matching the one found in this structure).
-    pub hashes: Vec<EncodedMetadataHash>,
+    pub entry_hashes: Vec<EncodedMetadataHash>,
+
+    /// This map contains fingerprints that are not specific to some DefId but
+    /// describe something global to the whole crate.
+    pub global_hashes: Vec<(DepNode<()>, Fingerprint)>,
 
     /// For each DefIndex (as it occurs in SerializedMetadataHash), this
     /// map stores the DefPathIndex (as it occurs in DefIdDirectory), so
diff --git a/src/librustc_incremental/persist/dirty_clean.rs b/src/librustc_incremental/persist/dirty_clean.rs
index b73b3e161f9..5facfe36efd 100644
--- a/src/librustc_incremental/persist/dirty_clean.rs
+++ b/src/librustc_incremental/persist/dirty_clean.rs
@@ -383,7 +383,7 @@ fn check_config(tcx: TyCtxt, attr: &Attribute) -> bool {
 
     tcx.sess.span_fatal(
         attr.span,
-        &format!("no cfg attribute"));
+        "no cfg attribute");
 }
 
 fn expect_associated_value(tcx: TyCtxt, item: &NestedMetaItem) -> ast::Name {
diff --git a/src/librustc_incremental/persist/hash.rs b/src/librustc_incremental/persist/hash.rs
index 9d8ff57e03b..5bc442deafa 100644
--- a/src/librustc_incremental/persist/hash.rs
+++ b/src/librustc_incremental/persist/hash.rs
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 use rustc::dep_graph::DepNode;
-use rustc::hir::def_id::{CrateNum, DefId};
+use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
 use rustc::hir::svh::Svh;
 use rustc::ich::Fingerprint;
 use rustc::ty::TyCtxt;
@@ -23,11 +23,15 @@ use super::data::*;
 use super::fs::*;
 use super::file_format;
 
+use std::hash::Hash;
+use std::fmt::Debug;
+
 pub struct HashContext<'a, 'tcx: 'a> {
     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
     incremental_hashes_map: &'a IncrementalHashesMap,
     item_metadata_hashes: FxHashMap<DefId, Fingerprint>,
     crate_hashes: FxHashMap<CrateNum, Svh>,
+    global_metadata_hashes: FxHashMap<DepNode<DefId>, Fingerprint>,
 }
 
 impl<'a, 'tcx> HashContext<'a, 'tcx> {
@@ -39,6 +43,7 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> {
             incremental_hashes_map: incremental_hashes_map,
             item_metadata_hashes: FxHashMap(),
             crate_hashes: FxHashMap(),
+            global_metadata_hashes: FxHashMap(),
         }
     }
 
@@ -46,9 +51,11 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> {
         match *dep_node {
             DepNode::Krate |
             DepNode::Hir(_) |
-            DepNode::HirBody(_) =>
+            DepNode::HirBody(_) |
+            DepNode::FileMap(..) =>
                 true,
-            DepNode::MetaData(def_id) => !def_id.is_local(),
+            DepNode::MetaData(def_id) |
+            DepNode::GlobalMetaData(def_id, _) => !def_id.is_local(),
             _ => false,
         }
     }
@@ -60,7 +67,8 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> {
             }
 
             // HIR nodes (which always come from our crate) are an input:
-            DepNode::Hir(def_id) | DepNode::HirBody(def_id) => {
+            DepNode::Hir(def_id) |
+            DepNode::HirBody(def_id) => {
                 assert!(def_id.is_local(),
                         "cannot hash HIR for non-local def-id {:?} => {:?}",
                         def_id,
@@ -69,12 +77,30 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> {
                 Some(self.incremental_hashes_map[dep_node])
             }
 
+            DepNode::FileMap(def_id, ref name) => {
+                if def_id.is_local() {
+                    Some(self.incremental_hashes_map[dep_node])
+                } else {
+                    Some(self.metadata_hash(DepNode::FileMap(def_id, name.clone()),
+                                            def_id.krate,
+                                            |this| &mut this.global_metadata_hashes))
+                }
+            }
+
             // MetaData from other crates is an *input* to us.
             // MetaData nodes from *our* crates are an *output*; we
             // don't hash them, but we do compute a hash for them and
             // save it for others to use.
             DepNode::MetaData(def_id) if !def_id.is_local() => {
-                Some(self.metadata_hash(def_id))
+                Some(self.metadata_hash(def_id,
+                                        def_id.krate,
+                                        |this| &mut this.item_metadata_hashes))
+            }
+
+            DepNode::GlobalMetaData(def_id, kind) => {
+                Some(self.metadata_hash(DepNode::GlobalMetaData(def_id, kind),
+                                        def_id.krate,
+                                        |this| &mut this.global_metadata_hashes))
             }
 
             _ => {
@@ -87,33 +113,37 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> {
         }
     }
 
-    fn metadata_hash(&mut self, def_id: DefId) -> Fingerprint {
-        debug!("metadata_hash(def_id={:?})", def_id);
+    fn metadata_hash<K, C>(&mut self,
+                           key: K,
+                           cnum: CrateNum,
+                           cache: C)
+                           -> Fingerprint
+        where K: Hash + Eq + Debug,
+              C: Fn(&mut Self) -> &mut FxHashMap<K, Fingerprint>,
+    {
+        debug!("metadata_hash(key={:?})", key);
 
-        assert!(!def_id.is_local());
+        debug_assert!(cnum != LOCAL_CRATE);
         loop {
             // check whether we have a result cached for this def-id
-            if let Some(&hash) = self.item_metadata_hashes.get(&def_id) {
-                debug!("metadata_hash: def_id={:?} hash={:?}", def_id, hash);
+            if let Some(&hash) = cache(self).get(&key) {
                 return hash;
             }
 
             // check whether we did not find detailed metadata for this
             // krate; in that case, we just use the krate's overall hash
-            if let Some(&svh) = self.crate_hashes.get(&def_id.krate) {
-                debug!("metadata_hash: def_id={:?} crate_hash={:?}", def_id, svh);
-
+            if let Some(&svh) = self.crate_hashes.get(&cnum) {
                 // micro-"optimization": avoid a cache miss if we ask
                 // for metadata from this particular def-id again.
                 let fingerprint = svh_to_fingerprint(svh);
-                self.item_metadata_hashes.insert(def_id, fingerprint);
+                cache(self).insert(key, fingerprint);
 
                 return fingerprint;
             }
 
             // otherwise, load the data and repeat.
-            self.load_data(def_id.krate);
-            assert!(self.crate_hashes.contains_key(&def_id.krate));
+            self.load_data(cnum);
+            assert!(self.crate_hashes.contains_key(&cnum));
         }
     }
 
@@ -191,7 +221,7 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> {
         }
 
         let serialized_hashes = SerializedMetadataHashes::decode(&mut decoder)?;
-        for serialized_hash in serialized_hashes.hashes {
+        for serialized_hash in serialized_hashes.entry_hashes {
             // the hashes are stored with just a def-index, which is
             // always relative to the old crate; convert that to use
             // our internal crate number
@@ -202,6 +232,24 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> {
             debug!("load_from_data: def_id={:?} hash={}", def_id, serialized_hash.hash);
             assert!(old.is_none(), "already have hash for {:?}", def_id);
         }
+
+        for (dep_node, fingerprint) in serialized_hashes.global_hashes {
+            // Here we need to remap the CrateNum in the DepNode.
+            let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
+            let dep_node = match dep_node {
+                DepNode::GlobalMetaData(_, kind) => DepNode::GlobalMetaData(def_id, kind),
+                DepNode::FileMap(_, name) => DepNode::FileMap(def_id, name),
+                other => {
+                    bug!("unexpected DepNode variant: {:?}", other)
+                }
+            };
+
+            // record the hash for this dep-node
+            debug!("load_from_data: def_node={:?} hash={}", dep_node, fingerprint);
+            let old = self.global_metadata_hashes.insert(dep_node.clone(), fingerprint);
+            assert!(old.is_none(), "already have hash for {:?}", dep_node);
+        }
+
         Ok(())
     }
 }
diff --git a/src/librustc_incremental/persist/load.rs b/src/librustc_incremental/persist/load.rs
index ed2e2e72ee7..7fad600d105 100644
--- a/src/librustc_incremental/persist/load.rs
+++ b/src/librustc_incremental/persist/load.rs
@@ -240,35 +240,40 @@ fn initial_dirty_nodes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
     let mut hcx = HashContext::new(tcx, incremental_hashes_map);
     let mut dirty_nodes = FxHashMap();
 
+    let print_removed_message = |dep_node: &DepNode<_>| {
+        if tcx.sess.opts.debugging_opts.incremental_dump_hash {
+            println!("node {:?} is dirty as it was removed", dep_node);
+        }
+
+        debug!("initial_dirty_nodes: {:?} is dirty as it was removed", dep_node);
+    };
+
     for hash in serialized_hashes {
         if let Some(dep_node) = retraced.map(&hash.dep_node) {
-            let current_hash = hcx.hash(&dep_node).unwrap();
-            if current_hash == hash.hash {
-                debug!("initial_dirty_nodes: {:?} is clean (hash={:?})",
-                   dep_node.map_def(|&def_id| Some(tcx.def_path(def_id))).unwrap(),
-                   current_hash);
-                continue;
-            }
+            if let Some(current_hash) = hcx.hash(&dep_node) {
+                if current_hash == hash.hash {
+                    debug!("initial_dirty_nodes: {:?} is clean (hash={:?})",
+                       dep_node.map_def(|&def_id| Some(tcx.def_path(def_id))).unwrap(),
+                       current_hash);
+                    continue;
+                }
 
-            if tcx.sess.opts.debugging_opts.incremental_dump_hash {
-                println!("node {:?} is dirty as hash is {:?} was {:?}",
-                         dep_node.map_def(|&def_id| Some(tcx.def_path(def_id))).unwrap(),
-                         current_hash,
-                         hash.hash);
-            }
+                if tcx.sess.opts.debugging_opts.incremental_dump_hash {
+                    println!("node {:?} is dirty as hash is {:?} was {:?}",
+                             dep_node.map_def(|&def_id| Some(tcx.def_path(def_id))).unwrap(),
+                             current_hash,
+                             hash.hash);
+                }
 
-            debug!("initial_dirty_nodes: {:?} is dirty as hash is {:?}, was {:?}",
-                   dep_node.map_def(|&def_id| Some(tcx.def_path(def_id))).unwrap(),
-                   current_hash,
-                   hash.hash);
-        } else {
-            if tcx.sess.opts.debugging_opts.incremental_dump_hash {
-                println!("node {:?} is dirty as it was removed",
-                         hash.dep_node);
+                debug!("initial_dirty_nodes: {:?} is dirty as hash is {:?}, was {:?}",
+                       dep_node.map_def(|&def_id| Some(tcx.def_path(def_id))).unwrap(),
+                       current_hash,
+                       hash.hash);
+            } else {
+                print_removed_message(&hash.dep_node);
             }
-
-            debug!("initial_dirty_nodes: {:?} is dirty as it was removed",
-                   hash.dep_node);
+        } else {
+            print_removed_message(&hash.dep_node);
         }
 
         dirty_nodes.insert(hash.dep_node.clone(), hash.dep_node.clone());
@@ -382,8 +387,8 @@ fn load_prev_metadata_hashes(tcx: TyCtxt,
 
     debug!("load_prev_metadata_hashes() - Mapping DefIds");
 
-    assert_eq!(serialized_hashes.index_map.len(), serialized_hashes.hashes.len());
-    for serialized_hash in serialized_hashes.hashes {
+    assert_eq!(serialized_hashes.index_map.len(), serialized_hashes.entry_hashes.len());
+    for serialized_hash in serialized_hashes.entry_hashes {
         let def_path_index = serialized_hashes.index_map[&serialized_hash.def_index];
         if let Some(def_id) = retraced.def_id(def_path_index) {
             let old = output.insert(def_id, serialized_hash.hash);
diff --git a/src/librustc_incremental/persist/save.rs b/src/librustc_incremental/persist/save.rs
index 1864009fbdf..06e49e9d37c 100644
--- a/src/librustc_incremental/persist/save.rs
+++ b/src/librustc_incremental/persist/save.rs
@@ -12,7 +12,7 @@ use rustc::dep_graph::DepNode;
 use rustc::hir::def_id::DefId;
 use rustc::hir::svh::Svh;
 use rustc::ich::Fingerprint;
-use rustc::middle::cstore::EncodedMetadataHash;
+use rustc::middle::cstore::EncodedMetadataHashes;
 use rustc::session::Session;
 use rustc::ty::TyCtxt;
 use rustc_data_structures::fx::FxHashMap;
@@ -34,7 +34,7 @@ use super::work_product;
 
 pub fn save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                 incremental_hashes_map: &IncrementalHashesMap,
-                                metadata_hashes: &[EncodedMetadataHash],
+                                metadata_hashes: &EncodedMetadataHashes,
                                 svh: Svh) {
     debug!("save_dep_graph()");
     let _ignore = tcx.dep_graph.in_ignore();
@@ -240,18 +240,19 @@ pub fn encode_dep_graph(preds: &Predecessors,
 
 pub fn encode_metadata_hashes(tcx: TyCtxt,
                               svh: Svh,
-                              metadata_hashes: &[EncodedMetadataHash],
+                              metadata_hashes: &EncodedMetadataHashes,
                               builder: &mut DefIdDirectoryBuilder,
                               current_metadata_hashes: &mut FxHashMap<DefId, Fingerprint>,
                               encoder: &mut Encoder)
                               -> io::Result<()> {
     let mut serialized_hashes = SerializedMetadataHashes {
-        hashes: metadata_hashes.to_vec(),
+        entry_hashes: metadata_hashes.entry_hashes.to_vec(),
+        global_hashes: metadata_hashes.global_hashes.to_vec(),
         index_map: FxHashMap()
     };
 
     if tcx.sess.opts.debugging_opts.query_dep_graph {
-        for serialized_hash in &serialized_hashes.hashes {
+        for serialized_hash in &serialized_hashes.entry_hashes {
             let def_id = DefId::local(serialized_hash.def_index);
 
             // Store entry in the index_map
diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs
index c9ec152841b..715a769158b 100644
--- a/src/librustc_lint/builtin.rs
+++ b/src/librustc_lint/builtin.rs
@@ -693,6 +693,82 @@ impl EarlyLintPass for DeprecatedAttr {
 }
 
 declare_lint! {
+    pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
+    Warn,
+    "floating-point literals cannot be used in patterns"
+}
+
+/// Checks for floating point literals in patterns.
+#[derive(Clone)]
+pub struct IllegalFloatLiteralPattern;
+
+impl LintPass for IllegalFloatLiteralPattern {
+    fn get_lints(&self) -> LintArray {
+        lint_array!(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN)
+    }
+}
+
+fn fl_lit_check_expr(cx: &EarlyContext, expr: &ast::Expr) {
+    use self::ast::{ExprKind, LitKind};
+    match expr.node {
+        ExprKind::Lit(ref l) => {
+            match l.node {
+                LitKind::FloatUnsuffixed(..) |
+                LitKind::Float(..) => {
+                    cx.span_lint(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
+                                 l.span,
+                                 "floating-point literals cannot be used in patterns");
+                    error!("span mc spanspam");
+                    },
+                _ => (),
+            }
+        }
+        // These may occur in patterns
+        // and can maybe contain float literals
+        ExprKind::Unary(_, ref f) => fl_lit_check_expr(cx, f),
+        // These may occur in patterns
+        // and can't contain float literals
+        ExprKind::Path(..) => (),
+        // If something unhandled is encountered, we need to expand the
+        // search or ignore more ExprKinds.
+        _ => span_bug!(expr.span, "Unhandled expression {:?} in float lit pattern lint",
+                       expr.node),
+    }
+}
+
+impl EarlyLintPass for IllegalFloatLiteralPattern {
+    fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
+        use self::ast::PatKind;
+        pat.walk(&mut |p| {
+            match p.node {
+                // Wildcard patterns and paths are uninteresting for the lint
+                PatKind::Wild |
+                PatKind::Path(..) => (),
+
+                // The walk logic recurses inside these
+                PatKind::Ident(..) |
+                PatKind::Struct(..) |
+                PatKind::Tuple(..) |
+                PatKind::TupleStruct(..) |
+                PatKind::Ref(..) |
+                PatKind::Box(..) |
+                PatKind::Slice(..) => (),
+
+                // Extract the expressions and check them
+                PatKind::Lit(ref e) => fl_lit_check_expr(cx, e),
+                PatKind::Range(ref st, ref en, _) => {
+                    fl_lit_check_expr(cx, st);
+                    fl_lit_check_expr(cx, en);
+                },
+
+                PatKind::Mac(_) => bug!("lint must run post-expansion"),
+            }
+            true
+        });
+    }
+}
+
+declare_lint! {
     pub UNCONDITIONAL_RECURSION,
     Warn,
     "functions that cannot return without calling themselves"
diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs
index c1c14cb1fd2..53ea3a8333f 100644
--- a/src/librustc_lint/lib.rs
+++ b/src/librustc_lint/lib.rs
@@ -113,6 +113,7 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
                        UnusedParens,
                        UnusedImportBraces,
                        AnonymousParameters,
+                       IllegalFloatLiteralPattern,
                        );
 
     add_early_builtin_with_new!(sess,
@@ -202,6 +203,10 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
             reference: "issue #36890 <https://github.com/rust-lang/rust/issues/36890>",
         },
         FutureIncompatibleInfo {
+            id: LintId::of(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN),
+            reference: "issue #41620 <https://github.com/rust-lang/rust/issues/41620>",
+        },
+        FutureIncompatibleInfo {
             id: LintId::of(ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN),
             reference: "issue #36891 <https://github.com/rust-lang/rust/issues/36891>",
         },
diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs
index 86bf209ccf8..93ff609a280 100644
--- a/src/librustc_lint/unused.rs
+++ b/src/librustc_lint/unused.rs
@@ -215,7 +215,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedUnsafe {
                 let mut db = cx.struct_span_lint(UNUSED_UNSAFE, blk.span,
                                                  "unnecessary `unsafe` block");
 
-                db.span_label(blk.span, &"unnecessary `unsafe` block");
+                db.span_label(blk.span, "unnecessary `unsafe` block");
                 if let Some((kind, id)) = is_enclosed(cx, blk.id) {
                     db.span_note(cx.tcx.hir.span(id),
                                  &format!("because it's nested under this `unsafe` {}", kind));
diff --git a/src/librustc_metadata/astencode.rs b/src/librustc_metadata/astencode.rs
index d9008ce555c..6c02ac7eafe 100644
--- a/src/librustc_metadata/astencode.rs
+++ b/src/librustc_metadata/astencode.rs
@@ -10,7 +10,7 @@
 
 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
 
-use index_builder::EntryBuilder;
+use isolated_encoder::IsolatedEncoder;
 use schema::*;
 
 use rustc::hir;
@@ -31,7 +31,7 @@ impl_stable_hash_for!(struct Ast<'tcx> {
     rvalue_promotable_to_static
 });
 
-impl<'a, 'b, 'tcx> EntryBuilder<'a, 'b, 'tcx> {
+impl<'a, 'b, 'tcx> IsolatedEncoder<'a, 'b, 'tcx> {
     pub fn encode_body(&mut self, body_id: hir::BodyId) -> Lazy<Ast<'tcx>> {
         let body = self.tcx.hir.body(body_id);
         let lazy_body = self.lazy(body);
diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs
index 966e814e337..d2874f16289 100644
--- a/src/librustc_metadata/creader.rs
+++ b/src/librustc_metadata/creader.rs
@@ -12,9 +12,10 @@
 
 use cstore::{self, CStore, CrateSource, MetadataBlob};
 use locator::{self, CratePaths};
-use schema::CrateRoot;
+use schema::{CrateRoot, Tracked};
 
-use rustc::hir::def_id::{CrateNum, DefIndex};
+use rustc::dep_graph::{DepNode, GlobalMetaDataKind};
+use rustc::hir::def_id::{DefId, CrateNum, DefIndex, CRATE_DEF_INDEX};
 use rustc::hir::svh::Svh;
 use rustc::middle::cstore::DepKind;
 use rustc::session::Session;
@@ -88,7 +89,7 @@ fn register_native_lib(sess: &Session,
             Some(span) => {
                 struct_span_err!(sess, span, E0454,
                                  "#[link(name = \"\")] given with empty name")
-                    .span_label(span, &format!("empty name given"))
+                    .span_label(span, "empty name given")
                     .emit();
             }
             None => {
@@ -311,7 +312,8 @@ impl<'a> CrateLoader<'a> {
             crate_root.def_path_table.decode(&metadata)
         });
 
-        let exported_symbols = crate_root.exported_symbols.decode(&metadata).collect();
+        let exported_symbols = crate_root.exported_symbols
+                                         .map(|x| x.decode(&metadata).collect());
 
         let mut cmeta = cstore::CrateMetadata {
             name: name,
@@ -333,16 +335,27 @@ impl<'a> CrateLoader<'a> {
                 rlib: rlib,
                 rmeta: rmeta,
             },
-            dllimport_foreign_items: FxHashSet(),
+            // Initialize this with an empty set. The field is populated below
+            // after we were able to deserialize its contents.
+            dllimport_foreign_items: Tracked::new(FxHashSet()),
         };
 
-        let dllimports: Vec<_> = cmeta.get_native_libraries().iter()
-                            .filter(|lib| relevant_lib(self.sess, lib) &&
-                                          lib.kind == cstore::NativeLibraryKind::NativeUnknown)
-                            .flat_map(|lib| &lib.foreign_items)
-                            .map(|id| *id)
-                            .collect();
-        cmeta.dllimport_foreign_items.extend(dllimports);
+        let dllimports: Tracked<FxHashSet<_>> = cmeta
+            .root
+            .native_libraries
+            .map(|native_libraries| {
+                let native_libraries: Vec<_> = native_libraries.decode(&cmeta)
+                                                               .collect();
+                native_libraries
+                    .iter()
+                    .filter(|lib| relevant_lib(self.sess, lib) &&
+                                  lib.kind == cstore::NativeLibraryKind::NativeUnknown)
+                    .flat_map(|lib| lib.foreign_items.iter())
+                    .map(|id| *id)
+                    .collect()
+            });
+
+        cmeta.dllimport_foreign_items = dllimports;
 
         let cmeta = Rc::new(cmeta);
         self.cstore.set_crate_data(cnum, cmeta.clone());
@@ -493,10 +506,16 @@ impl<'a> CrateLoader<'a> {
             return cstore::CrateNumMap::new();
         }
 
+        let dep_node = DepNode::GlobalMetaData(DefId { krate, index: CRATE_DEF_INDEX },
+                                               GlobalMetaDataKind::CrateDeps);
+
         // The map from crate numbers in the crate we're resolving to local crate numbers.
         // We map 0 and all other holes in the map to our parent crate. The "additional"
         // self-dependencies should be harmless.
-        ::std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| {
+        ::std::iter::once(krate).chain(crate_root.crate_deps
+                                                 .get(&self.sess.dep_graph, dep_node)
+                                                 .decode(metadata)
+                                                 .map(|dep| {
             debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
             if dep.kind == DepKind::UnexportedMacrosOnly {
                 return krate;
@@ -654,7 +673,9 @@ impl<'a> CrateLoader<'a> {
 
     /// Look for a plugin registrar. Returns library path, crate
     /// SVH and DefIndex of the registrar function.
-    pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
+    pub fn find_plugin_registrar(&mut self,
+                                 span: Span,
+                                 name: &str)
                                  -> Option<(PathBuf, Symbol, DefIndex)> {
         let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
              name: Symbol::intern(name),
@@ -740,13 +761,17 @@ impl<'a> CrateLoader<'a> {
         let mut runtime_found = false;
         let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
                                                           "needs_panic_runtime");
+
+        let dep_graph = &self.sess.dep_graph;
+
         self.cstore.iter_crate_data(|cnum, data| {
-            needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
-            if data.is_panic_runtime() {
+            needs_panic_runtime = needs_panic_runtime ||
+                                  data.needs_panic_runtime(dep_graph);
+            if data.is_panic_runtime(dep_graph) {
                 // Inject a dependency from all #![needs_panic_runtime] to this
                 // #![panic_runtime] crate.
                 self.inject_dependency_if(cnum, "a panic runtime",
-                                          &|data| data.needs_panic_runtime());
+                                          &|data| data.needs_panic_runtime(dep_graph));
                 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
             }
         });
@@ -782,11 +807,11 @@ impl<'a> CrateLoader<'a> {
 
         // Sanity check the loaded crate to ensure it is indeed a panic runtime
         // and the panic strategy is indeed what we thought it was.
-        if !data.is_panic_runtime() {
+        if !data.is_panic_runtime(dep_graph) {
             self.sess.err(&format!("the crate `{}` is not a panic runtime",
                                    name));
         }
-        if data.panic_strategy() != desired_strategy {
+        if data.panic_strategy(dep_graph) != desired_strategy {
             self.sess.err(&format!("the crate `{}` does not have the panic \
                                     strategy `{}`",
                                    name, desired_strategy.desc()));
@@ -794,7 +819,7 @@ impl<'a> CrateLoader<'a> {
 
         self.sess.injected_panic_runtime.set(Some(cnum));
         self.inject_dependency_if(cnum, "a panic runtime",
-                                  &|data| data.needs_panic_runtime());
+                                  &|data| data.needs_panic_runtime(dep_graph));
     }
 
     fn inject_sanitizer_runtime(&mut self) {
@@ -862,7 +887,7 @@ impl<'a> CrateLoader<'a> {
                                        PathKind::Crate, dep_kind);
 
                 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
-                if !data.is_sanitizer_runtime() {
+                if !data.is_sanitizer_runtime(&self.sess.dep_graph) {
                     self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
                                            name));
                 }
@@ -878,12 +903,13 @@ impl<'a> CrateLoader<'a> {
         // also bail out as we don't need to implicitly inject one.
         let mut needs_allocator = false;
         let mut found_required_allocator = false;
+        let dep_graph = &self.sess.dep_graph;
         self.cstore.iter_crate_data(|cnum, data| {
-            needs_allocator = needs_allocator || data.needs_allocator();
-            if data.is_allocator() {
+            needs_allocator = needs_allocator || data.needs_allocator(dep_graph);
+            if data.is_allocator(dep_graph) {
                 info!("{} required by rlib and is an allocator", data.name());
                 self.inject_dependency_if(cnum, "an allocator",
-                                          &|data| data.needs_allocator());
+                                          &|data| data.needs_allocator(dep_graph));
                 found_required_allocator = found_required_allocator ||
                     data.dep_kind.get() == DepKind::Explicit;
             }
@@ -937,14 +963,14 @@ impl<'a> CrateLoader<'a> {
 
         // Sanity check the crate we loaded to ensure that it is indeed an
         // allocator.
-        if !data.is_allocator() {
+        if !data.is_allocator(dep_graph) {
             self.sess.err(&format!("the allocator crate `{}` is not tagged \
                                     with #![allocator]", data.name()));
         }
 
         self.sess.injected_allocator.set(Some(cnum));
         self.inject_dependency_if(cnum, "an allocator",
-                                  &|data| data.needs_allocator());
+                                  &|data| data.needs_allocator(dep_graph));
     }
 
     fn inject_dependency_if(&self,
@@ -1029,7 +1055,7 @@ impl<'a> CrateLoader<'a> {
                 Some(k) => {
                     struct_span_err!(self.sess, m.span, E0458,
                               "unknown kind: `{}`", k)
-                        .span_label(m.span, &format!("unknown kind")).emit();
+                        .span_label(m.span, "unknown kind").emit();
                     cstore::NativeUnknown
                 }
                 None => cstore::NativeUnknown
@@ -1042,7 +1068,7 @@ impl<'a> CrateLoader<'a> {
                 None => {
                     struct_span_err!(self.sess, m.span, E0459,
                                      "#[link(...)] specified without `name = \"foo\"`")
-                        .span_label(m.span, &format!("missing `name` argument")).emit();
+                        .span_label(m.span, "missing `name` argument").emit();
                     Symbol::intern("foo")
                 }
             };
diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs
index 72ad1d75a56..8d53e7d49ee 100644
--- a/src/librustc_metadata/cstore.rs
+++ b/src/librustc_metadata/cstore.rs
@@ -12,9 +12,9 @@
 // crates and libraries
 
 use locator;
-use schema;
+use schema::{self, Tracked};
 
-use rustc::dep_graph::DepGraph;
+use rustc::dep_graph::{DepGraph, DepNode, GlobalMetaDataKind};
 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefIndex, DefId};
 use rustc::hir::map::definitions::DefPathTable;
 use rustc::hir::svh::Svh;
@@ -83,14 +83,14 @@ pub struct CrateMetadata {
     /// compilation support.
     pub def_path_table: DefPathTable,
 
-    pub exported_symbols: FxHashSet<DefIndex>,
+    pub exported_symbols: Tracked<FxHashSet<DefIndex>>,
 
     pub dep_kind: Cell<DepKind>,
     pub source: CrateSource,
 
     pub proc_macros: Option<Vec<(ast::Name, Rc<SyntaxExtension>)>>,
     // Foreign items imported from a dylib (Windows only)
-    pub dllimport_foreign_items: FxHashSet<DefIndex>,
+    pub dllimport_foreign_items: Tracked<FxHashSet<DefIndex>>,
 }
 
 pub struct CStore {
@@ -269,8 +269,8 @@ impl CrateMetadata {
         self.root.disambiguator
     }
 
-    pub fn is_staged_api(&self) -> bool {
-        for attr in self.get_item_attrs(CRATE_DEF_INDEX).iter() {
+    pub fn is_staged_api(&self, dep_graph: &DepGraph) -> bool {
+        for attr in self.get_item_attrs(CRATE_DEF_INDEX, dep_graph).iter() {
             if attr.path == "stable" || attr.path == "unstable" {
                 return true;
             }
@@ -278,42 +278,51 @@ impl CrateMetadata {
         false
     }
 
-    pub fn is_allocator(&self) -> bool {
-        let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
+    pub fn is_allocator(&self, dep_graph: &DepGraph) -> bool {
+        let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph);
         attr::contains_name(&attrs, "allocator")
     }
 
-    pub fn needs_allocator(&self) -> bool {
-        let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
+    pub fn needs_allocator(&self, dep_graph: &DepGraph) -> bool {
+        let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph);
         attr::contains_name(&attrs, "needs_allocator")
     }
 
-    pub fn is_panic_runtime(&self) -> bool {
-        let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
+    pub fn is_panic_runtime(&self, dep_graph: &DepGraph) -> bool {
+        let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph);
         attr::contains_name(&attrs, "panic_runtime")
     }
 
-    pub fn needs_panic_runtime(&self) -> bool {
-        let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
+    pub fn needs_panic_runtime(&self, dep_graph: &DepGraph) -> bool {
+        let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph);
         attr::contains_name(&attrs, "needs_panic_runtime")
     }
 
-    pub fn is_compiler_builtins(&self) -> bool {
-        let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
+    pub fn is_compiler_builtins(&self, dep_graph: &DepGraph) -> bool {
+        let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph);
         attr::contains_name(&attrs, "compiler_builtins")
     }
 
-    pub fn is_sanitizer_runtime(&self) -> bool {
-        let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
+    pub fn is_sanitizer_runtime(&self, dep_graph: &DepGraph) -> bool {
+        let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph);
         attr::contains_name(&attrs, "sanitizer_runtime")
     }
 
-    pub fn is_no_builtins(&self) -> bool {
-        let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
+    pub fn is_no_builtins(&self, dep_graph: &DepGraph) -> bool {
+        let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph);
         attr::contains_name(&attrs, "no_builtins")
     }
 
-    pub fn panic_strategy(&self) -> PanicStrategy {
-        self.root.panic_strategy.clone()
+    pub fn panic_strategy(&self, dep_graph: &DepGraph) -> PanicStrategy {
+        let def_id = DefId {
+            krate: self.cnum,
+            index: CRATE_DEF_INDEX,
+        };
+        let dep_node = DepNode::GlobalMetaData(def_id, GlobalMetaDataKind::Krate);
+
+        self.root
+            .panic_strategy
+            .get(dep_graph, dep_node)
+            .clone()
     }
 }
diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs
index d29fa8f0814..f3fb427fed6 100644
--- a/src/librustc_metadata/cstore_impl.rs
+++ b/src/librustc_metadata/cstore_impl.rs
@@ -24,7 +24,7 @@ use rustc::ty::{self, TyCtxt};
 use rustc::ty::maps::Providers;
 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
 
-use rustc::dep_graph::DepNode;
+use rustc::dep_graph::{DepNode, GlobalMetaDataKind};
 use rustc::hir::map::{DefKey, DefPath, DisambiguatedDefPathData};
 use rustc::util::nodemap::{NodeSet, DefIdMap};
 use rustc_back::PanicStrategy;
@@ -111,7 +111,7 @@ provide! { <'tcx> tcx, def_id, cdata
     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
     stability => { cdata.get_stability(def_id.index) }
     deprecation => { cdata.get_deprecation(def_id.index) }
-    item_attrs => { cdata.get_item_attrs(def_id.index) }
+    item_attrs => { cdata.get_item_attrs(def_id.index, &tcx.dep_graph) }
     // FIXME(#38501) We've skipped a `read` on the `HirBody` of
     // a `fn` when encoding, so the dep-tracking wouldn't work.
     // This is only used by rustdoc anyway, which shouldn't have
@@ -119,7 +119,10 @@ provide! { <'tcx> tcx, def_id, cdata
     fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
     impl_parent => { cdata.get_parent_impl(def_id.index) }
     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
-    is_exported_symbol => { cdata.exported_symbols.contains(&def_id.index) }
+    is_exported_symbol => {
+        let dep_node = cdata.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
+        cdata.exported_symbols.get(&tcx.dep_graph, dep_node).contains(&def_id.index)
+    }
     item_body_nested_bodies => { Rc::new(cdata.item_body_nested_bodies(def_id.index)) }
     const_is_rvalue_promotable_to_static => {
         cdata.const_is_rvalue_promotable_to_static(def_id.index)
@@ -149,7 +152,7 @@ impl CrateStore for cstore::CStore {
         }
         let mut result = vec![];
         self.iter_crate_data(|_, cdata| {
-            cdata.get_implementations_for_trait(filter, &mut result)
+            cdata.get_implementations_for_trait(filter, &self.dep_graph, &mut result)
         });
         result
     }
@@ -186,63 +189,71 @@ impl CrateStore for cstore::CStore {
         if def_id.krate == LOCAL_CRATE {
             self.dllimport_foreign_items.borrow().contains(&def_id.index)
         } else {
-            self.get_crate_data(def_id.krate).is_dllimport_foreign_item(def_id.index)
+            self.get_crate_data(def_id.krate)
+                .is_dllimport_foreign_item(def_id.index, &self.dep_graph)
         }
     }
 
     fn dylib_dependency_formats(&self, cnum: CrateNum)
                                 -> Vec<(CrateNum, LinkagePreference)>
     {
-        self.get_crate_data(cnum).get_dylib_dependency_formats()
+        self.get_crate_data(cnum).get_dylib_dependency_formats(&self.dep_graph)
     }
 
     fn dep_kind(&self, cnum: CrateNum) -> DepKind
     {
-        self.get_crate_data(cnum).dep_kind.get()
+        let data = self.get_crate_data(cnum);
+        let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
+        self.dep_graph.read(dep_node);
+        data.dep_kind.get()
     }
 
     fn export_macros(&self, cnum: CrateNum) {
-        if self.get_crate_data(cnum).dep_kind.get() == DepKind::UnexportedMacrosOnly {
-            self.get_crate_data(cnum).dep_kind.set(DepKind::MacrosOnly)
+        let data = self.get_crate_data(cnum);
+        let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
+
+        self.dep_graph.read(dep_node);
+        if data.dep_kind.get() == DepKind::UnexportedMacrosOnly {
+            data.dep_kind.set(DepKind::MacrosOnly)
         }
     }
 
     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
     {
-        self.get_crate_data(cnum).get_lang_items()
+        self.get_crate_data(cnum).get_lang_items(&self.dep_graph)
     }
 
     fn missing_lang_items(&self, cnum: CrateNum)
                           -> Vec<lang_items::LangItem>
     {
-        self.get_crate_data(cnum).get_missing_lang_items()
+        self.get_crate_data(cnum).get_missing_lang_items(&self.dep_graph)
     }
 
     fn is_staged_api(&self, cnum: CrateNum) -> bool
     {
-        self.get_crate_data(cnum).is_staged_api()
+        self.get_crate_data(cnum).is_staged_api(&self.dep_graph)
     }
 
     fn is_allocator(&self, cnum: CrateNum) -> bool
     {
-        self.get_crate_data(cnum).is_allocator()
+        self.get_crate_data(cnum).is_allocator(&self.dep_graph)
     }
 
     fn is_panic_runtime(&self, cnum: CrateNum) -> bool
     {
-        self.get_crate_data(cnum).is_panic_runtime()
+        self.get_crate_data(cnum).is_panic_runtime(&self.dep_graph)
     }
 
     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool {
-        self.get_crate_data(cnum).is_compiler_builtins()
+        self.get_crate_data(cnum).is_compiler_builtins(&self.dep_graph)
     }
 
     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool {
-        self.get_crate_data(cnum).is_sanitizer_runtime()
+        self.get_crate_data(cnum).is_sanitizer_runtime(&self.dep_graph)
     }
 
     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
-        self.get_crate_data(cnum).panic_strategy()
+        self.get_crate_data(cnum).panic_strategy(&self.dep_graph)
     }
 
     fn crate_name(&self, cnum: CrateNum) -> Symbol
@@ -288,16 +299,16 @@ impl CrateStore for cstore::CStore {
 
     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>
     {
-        self.get_crate_data(cnum).get_native_libraries()
+        self.get_crate_data(cnum).get_native_libraries(&self.dep_graph)
     }
 
     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId>
     {
-        self.get_crate_data(cnum).get_exported_symbols()
+        self.get_crate_data(cnum).get_exported_symbols(&self.dep_graph)
     }
 
     fn is_no_builtins(&self, cnum: CrateNum) -> bool {
-        self.get_crate_data(cnum).is_no_builtins()
+        self.get_crate_data(cnum).is_no_builtins(&self.dep_graph)
     }
 
     fn retrace_path(&self,
@@ -364,7 +375,7 @@ impl CrateStore for cstore::CStore {
         let body = filemap_to_stream(&sess.parse_sess, filemap);
 
         // Mark the attrs as used
-        let attrs = data.get_item_attrs(id.index);
+        let attrs = data.get_item_attrs(id.index, &self.dep_graph);
         for attr in attrs.iter() {
             attr::mark_used(attr);
         }
@@ -446,7 +457,7 @@ impl CrateStore for cstore::CStore {
                                  reachable: &NodeSet)
                                  -> EncodedMetadata
     {
-        encoder::encode_metadata(tcx, self, link_meta, reachable)
+        encoder::encode_metadata(tcx, link_meta, reachable)
     }
 
     fn metadata_encoding_version(&self) -> &[u8]
diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs
index b89b5181e7b..ea845f722c3 100644
--- a/src/librustc_metadata/decoder.rs
+++ b/src/librustc_metadata/decoder.rs
@@ -13,6 +13,7 @@
 use cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary};
 use schema::*;
 
+use rustc::dep_graph::{DepGraph, DepNode, GlobalMetaDataKind};
 use rustc::hir::map::{DefKey, DefPath, DefPathData};
 use rustc::hir;
 
@@ -405,10 +406,14 @@ impl<'a, 'tcx> MetadataBlob {
         Lazy::with_position(pos).decode(self)
     }
 
-    pub fn list_crate_metadata(&self, out: &mut io::Write) -> io::Result<()> {
+    pub fn list_crate_metadata(&self,
+                               out: &mut io::Write) -> io::Result<()> {
         write!(out, "=External Dependencies=\n")?;
         let root = self.get_root();
-        for (i, dep) in root.crate_deps.decode(self).enumerate() {
+        for (i, dep) in root.crate_deps
+                            .get_untracked()
+                            .decode(self)
+                            .enumerate() {
             write!(out, "{} {}-{}\n", i + 1, dep.name, dep.hash)?;
         }
         write!(out, "\n")?;
@@ -654,8 +659,13 @@ impl<'a, 'tcx> CrateMetadata {
     }
 
     /// Iterates over the language items in the given crate.
-    pub fn get_lang_items(&self) -> Vec<(DefIndex, usize)> {
-        self.root.lang_items.decode(self).collect()
+    pub fn get_lang_items(&self, dep_graph: &DepGraph) -> Vec<(DefIndex, usize)> {
+        let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItems);
+        self.root
+            .lang_items
+            .get(dep_graph, dep_node)
+            .decode(self)
+            .collect()
     }
 
     /// Iterates over each child of the given item.
@@ -870,13 +880,17 @@ impl<'a, 'tcx> CrateMetadata {
         }
     }
 
-    pub fn get_item_attrs(&self, node_id: DefIndex) -> Rc<[ast::Attribute]> {
+    pub fn get_item_attrs(&self,
+                          node_id: DefIndex,
+                          dep_graph: &DepGraph) -> Rc<[ast::Attribute]> {
         let (node_as, node_index) =
             (node_id.address_space().index(), node_id.as_array_index());
         if self.is_proc_macro(node_id) {
             return Rc::new([]);
         }
 
+        dep_graph.read(DepNode::MetaData(self.local_def_id(node_id)));
+
         if let Some(&Some(ref val)) =
             self.attribute_cache.borrow()[node_as].get(node_index) {
             return val.clone();
@@ -941,7 +955,10 @@ impl<'a, 'tcx> CrateMetadata {
             .collect()
     }
 
-    pub fn get_implementations_for_trait(&self, filter: Option<DefId>, result: &mut Vec<DefId>) {
+    pub fn get_implementations_for_trait(&self,
+                                         filter: Option<DefId>,
+                                         dep_graph: &DepGraph,
+                                         result: &mut Vec<DefId>) {
         // Do a reverse lookup beforehand to avoid touching the crate_num
         // hash map in the loop below.
         let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
@@ -952,7 +969,8 @@ impl<'a, 'tcx> CrateMetadata {
         };
 
         // FIXME(eddyb) Make this O(1) instead of O(n).
-        for trait_impls in self.root.impls.decode(self) {
+        let dep_node = self.metadata_dep_node(GlobalMetaDataKind::Impls);
+        for trait_impls in self.root.impls.get(dep_graph, dep_node).decode(self) {
             if filter.is_some() && filter != Some(trait_impls.trait_id) {
                 continue;
             }
@@ -975,13 +993,29 @@ impl<'a, 'tcx> CrateMetadata {
     }
 
 
-    pub fn get_native_libraries(&self) -> Vec<NativeLibrary> {
-        self.root.native_libraries.decode(self).collect()
+    pub fn get_native_libraries(&self,
+                                dep_graph: &DepGraph)
+                                -> Vec<NativeLibrary> {
+        let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
+        self.root
+            .native_libraries
+            .get(dep_graph, dep_node)
+            .decode(self)
+            .collect()
     }
 
-    pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
+    pub fn get_dylib_dependency_formats(&self,
+                                        dep_graph: &DepGraph)
+                                        -> Vec<(CrateNum, LinkagePreference)> {
+        let def_id = DefId {
+            krate: self.cnum,
+            index: CRATE_DEF_INDEX,
+        };
+        let dep_node = DepNode::GlobalMetaData(def_id,
+                                               GlobalMetaDataKind::DylibDependencyFormats);
         self.root
             .dylib_dependency_formats
+            .get(dep_graph, dep_node)
             .decode(self)
             .enumerate()
             .flat_map(|(i, link)| {
@@ -991,8 +1025,13 @@ impl<'a, 'tcx> CrateMetadata {
             .collect()
     }
 
-    pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
-        self.root.lang_items_missing.decode(self).collect()
+    pub fn get_missing_lang_items(&self, dep_graph: &DepGraph) -> Vec<lang_items::LangItem> {
+        let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItemsMissing);
+        self.root
+            .lang_items_missing
+            .get(dep_graph, dep_node)
+            .decode(self)
+            .collect()
     }
 
     pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
@@ -1005,8 +1044,13 @@ impl<'a, 'tcx> CrateMetadata {
         arg_names.decode(self).collect()
     }
 
-    pub fn get_exported_symbols(&self) -> Vec<DefId> {
-        self.exported_symbols.iter().map(|&index| self.local_def_id(index)).collect()
+    pub fn get_exported_symbols(&self, dep_graph: &DepGraph) -> Vec<DefId> {
+        let dep_node = self.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
+        self.exported_symbols
+            .get(dep_graph, dep_node)
+            .iter()
+            .map(|&index| self.local_def_id(index))
+            .collect()
     }
 
     pub fn get_macro(&self, id: DefIndex) -> (ast::Name, MacroDef) {
@@ -1035,8 +1079,11 @@ impl<'a, 'tcx> CrateMetadata {
         }
     }
 
-    pub fn is_dllimport_foreign_item(&self, id: DefIndex) -> bool {
-        self.dllimport_foreign_items.contains(&id)
+    pub fn is_dllimport_foreign_item(&self, id: DefIndex, dep_graph: &DepGraph) -> bool {
+        let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
+        self.dllimport_foreign_items
+            .get(dep_graph, dep_node)
+            .contains(&id)
     }
 
     pub fn is_default_impl(&self, impl_id: DefIndex) -> bool {
@@ -1114,121 +1161,62 @@ impl<'a, 'tcx> CrateMetadata {
         let external_codemap = self.root.codemap.decode(self);
 
         let imported_filemaps = external_codemap.map(|filemap_to_import| {
-                // Try to find an existing FileMap that can be reused for the filemap to
-                // be imported. A FileMap is reusable if it is exactly the same, just
-                // positioned at a different offset within the codemap.
-                let reusable_filemap = {
-                    local_codemap.files
-                        .borrow()
-                        .iter()
-                        .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
-                        .map(|rc| rc.clone())
-                };
-
-                match reusable_filemap {
-                    Some(fm) => {
-
-                        debug!("CrateMetaData::imported_filemaps reuse \
-                                filemap {:?} original (start_pos {:?} end_pos {:?}) \
-                                translated (start_pos {:?} end_pos {:?})",
-                               filemap_to_import.name,
-                               filemap_to_import.start_pos, filemap_to_import.end_pos,
-                               fm.start_pos, fm.end_pos);
-
-                        cstore::ImportedFileMap {
-                            original_start_pos: filemap_to_import.start_pos,
-                            original_end_pos: filemap_to_import.end_pos,
-                            translated_filemap: fm,
-                        }
-                    }
-                    None => {
-                        // We can't reuse an existing FileMap, so allocate a new one
-                        // containing the information we need.
-                        let syntax_pos::FileMap { name,
-                                                  name_was_remapped,
-                                                  start_pos,
-                                                  end_pos,
-                                                  lines,
-                                                  multibyte_chars,
-                                                  .. } = filemap_to_import;
-
-                        let source_length = (end_pos - start_pos).to_usize();
-
-                        // Translate line-start positions and multibyte character
-                        // position into frame of reference local to file.
-                        // `CodeMap::new_imported_filemap()` will then translate those
-                        // coordinates to their new global frame of reference when the
-                        // offset of the FileMap is known.
-                        let mut lines = lines.into_inner();
-                        for pos in &mut lines {
-                            *pos = *pos - start_pos;
-                        }
-                        let mut multibyte_chars = multibyte_chars.into_inner();
-                        for mbc in &mut multibyte_chars {
-                            mbc.pos = mbc.pos - start_pos;
-                        }
+            // We can't reuse an existing FileMap, so allocate a new one
+            // containing the information we need.
+            let syntax_pos::FileMap { name,
+                                      name_was_remapped,
+                                      start_pos,
+                                      end_pos,
+                                      lines,
+                                      multibyte_chars,
+                                      .. } = filemap_to_import;
+
+            let source_length = (end_pos - start_pos).to_usize();
+
+            // Translate line-start positions and multibyte character
+            // position into frame of reference local to file.
+            // `CodeMap::new_imported_filemap()` will then translate those
+            // coordinates to their new global frame of reference when the
+            // offset of the FileMap is known.
+            let mut lines = lines.into_inner();
+            for pos in &mut lines {
+                *pos = *pos - start_pos;
+            }
+            let mut multibyte_chars = multibyte_chars.into_inner();
+            for mbc in &mut multibyte_chars {
+                mbc.pos = mbc.pos - start_pos;
+            }
 
-                        let local_version = local_codemap.new_imported_filemap(name,
-                                                                               name_was_remapped,
-                                                                               source_length,
-                                                                               lines,
-                                                                               multibyte_chars);
-                        debug!("CrateMetaData::imported_filemaps alloc \
-                                filemap {:?} original (start_pos {:?} end_pos {:?}) \
-                                translated (start_pos {:?} end_pos {:?})",
-                               local_version.name, start_pos, end_pos,
-                               local_version.start_pos, local_version.end_pos);
-
-                        cstore::ImportedFileMap {
-                            original_start_pos: start_pos,
-                            original_end_pos: end_pos,
-                            translated_filemap: local_version,
-                        }
-                    }
-                }
-            })
-            .collect();
+            let local_version = local_codemap.new_imported_filemap(name,
+                                                                   name_was_remapped,
+                                                                   self.cnum.as_u32(),
+                                                                   source_length,
+                                                                   lines,
+                                                                   multibyte_chars);
+            debug!("CrateMetaData::imported_filemaps alloc \
+                    filemap {:?} original (start_pos {:?} end_pos {:?}) \
+                    translated (start_pos {:?} end_pos {:?})",
+                   local_version.name, start_pos, end_pos,
+                   local_version.start_pos, local_version.end_pos);
+
+            cstore::ImportedFileMap {
+                original_start_pos: start_pos,
+                original_end_pos: end_pos,
+                translated_filemap: local_version,
+            }
+        }).collect();
 
         // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
         *self.codemap_import_info.borrow_mut() = imported_filemaps;
         self.codemap_import_info.borrow()
     }
-}
-
-fn are_equal_modulo_startpos(fm1: &syntax_pos::FileMap, fm2: &syntax_pos::FileMap) -> bool {
-    if fm1.byte_length() != fm2.byte_length() {
-        return false;
-    }
-
-    if fm1.name != fm2.name {
-        return false;
-    }
-
-    let lines1 = fm1.lines.borrow();
-    let lines2 = fm2.lines.borrow();
-
-    if lines1.len() != lines2.len() {
-        return false;
-    }
-
-    for (&line1, &line2) in lines1.iter().zip(lines2.iter()) {
-        if (line1 - fm1.start_pos) != (line2 - fm2.start_pos) {
-            return false;
-        }
-    }
-
-    let multibytes1 = fm1.multibyte_chars.borrow();
-    let multibytes2 = fm2.multibyte_chars.borrow();
 
-    if multibytes1.len() != multibytes2.len() {
-        return false;
-    }
+    pub fn metadata_dep_node(&self, kind: GlobalMetaDataKind) -> DepNode<DefId> {
+        let def_id = DefId {
+            krate: self.cnum,
+            index: CRATE_DEF_INDEX,
+        };
 
-    for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
-        if (mb1.bytes != mb2.bytes) || ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {
-            return false;
-        }
+        DepNode::GlobalMetaData(def_id, kind)
     }
-
-    true
 }
diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs
index 125026b799c..fa4ebed1618 100644
--- a/src/librustc_metadata/encoder.rs
+++ b/src/librustc_metadata/encoder.rs
@@ -8,14 +8,17 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use cstore;
 use index::Index;
+use index_builder::{FromId, IndexBuilder, Untracked};
+use isolated_encoder::IsolatedEncoder;
 use schema::*;
 
 use rustc::middle::cstore::{LinkMeta, LinkagePreference, NativeLibrary,
-                            EncodedMetadata, EncodedMetadataHash};
+                            EncodedMetadata, EncodedMetadataHashes};
 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LOCAL_CRATE};
 use rustc::hir::map::definitions::DefPathTable;
+use rustc::dep_graph::{DepNode, GlobalMetaDataKind};
+use rustc::ich::{StableHashingContext, Fingerprint};
 use rustc::middle::dependency_format::Linkage;
 use rustc::middle::lang_items;
 use rustc::mir;
@@ -26,12 +29,15 @@ use rustc::session::config::{self, CrateTypeProcMacro};
 use rustc::util::nodemap::{FxHashMap, NodeSet};
 
 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
+use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
+
 use std::hash::Hash;
 use std::intrinsics;
 use std::io::prelude::*;
 use std::io::Cursor;
 use std::path::Path;
 use std::rc::Rc;
+use std::sync::Arc;
 use std::u32;
 use syntax::ast::{self, CRATE_NODE_ID};
 use syntax::codemap::Spanned;
@@ -44,20 +50,18 @@ use rustc::hir::itemlikevisit::ItemLikeVisitor;
 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
 use rustc::hir::intravisit;
 
-use super::index_builder::{FromId, IndexBuilder, Untracked, EntryBuilder};
-
 pub struct EncodeContext<'a, 'tcx: 'a> {
     opaque: opaque::Encoder<'a>,
     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
     link_meta: &'a LinkMeta,
-    cstore: &'a cstore::CStore,
     exported_symbols: &'a NodeSet,
 
     lazy_state: LazyState,
     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
     predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
 
-    pub metadata_hashes: Vec<EncodedMetadataHash>,
+    pub metadata_hashes: EncodedMetadataHashes,
+    pub compute_ich: bool,
 }
 
 macro_rules! encoder_methods {
@@ -134,6 +138,7 @@ impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext
 }
 
 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
+
     pub fn position(&self) -> usize {
         self.opaque.position()
     }
@@ -237,11 +242,240 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
 
         Ok(())
     }
+
+    // Encodes something that corresponds to a single DepNode::GlobalMetaData
+    // and registers the Fingerprint in the `metadata_hashes` map.
+    pub fn tracked<'x, DATA, R>(&'x mut self,
+                                dep_node: DepNode<()>,
+                                op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
+                                data: DATA)
+                                -> Tracked<R> {
+        let mut entry_builder = IsolatedEncoder::new(self);
+        let ret = op(&mut entry_builder, data);
+        let (fingerprint, this) = entry_builder.finish();
+
+        if let Some(fingerprint) = fingerprint {
+            this.metadata_hashes.global_hashes.push((dep_node, fingerprint));
+        }
+
+        Tracked::new(ret)
+    }
+
+    fn encode_info_for_items(&mut self) -> Index {
+        let krate = self.tcx.hir.krate();
+        let mut index = IndexBuilder::new(self);
+        index.record(DefId::local(CRATE_DEF_INDEX),
+                     IsolatedEncoder::encode_info_for_mod,
+                     FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
+        let mut visitor = EncodeVisitor { index: index };
+        krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
+        for macro_def in &krate.exported_macros {
+            visitor.visit_macro_def(macro_def);
+        }
+        visitor.index.into_items()
+    }
+
+    fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
+        let definitions = self.tcx.hir.definitions();
+        self.lazy(definitions.def_path_table())
+    }
+
+    fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
+        let codemap = self.tcx.sess.codemap();
+        let all_filemaps = codemap.files();
+
+        let hcx = &mut StableHashingContext::new(self.tcx);
+        let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
+
+        let adapted = all_filemaps.iter()
+            .filter(|filemap| {
+                // No need to re-export imported filemaps, as any downstream
+                // crate will import them from their original source.
+                !filemap.is_imported()
+            })
+            .map(|filemap| {
+                // When exporting FileMaps, we expand all paths to absolute
+                // paths because any relative paths are potentially relative to
+                // a wrong directory.
+                // However, if a path has been modified via
+                // `-Zremap-path-prefix` we assume the user has already set
+                // things up the way they want and don't touch the path values
+                // anymore.
+                let name = Path::new(&filemap.name);
+                if filemap.name_was_remapped ||
+                   (name.is_relative() && working_dir_was_remapped) {
+                    // This path of this FileMap has been modified by
+                    // path-remapping, so we use it verbatim (and avoid cloning
+                    // the whole map in the process).
+                    filemap.clone()
+                } else {
+                    let mut adapted = (**filemap).clone();
+                    let abs_path = Path::new(&working_dir).join(name)
+                                                         .to_string_lossy()
+                                                         .into_owned();
+                    adapted.name = abs_path;
+                    Rc::new(adapted)
+                }
+            });
+
+        let filemaps: Vec<_> = if self.compute_ich {
+            adapted.inspect(|filemap| {
+                let mut hasher = StableHasher::new();
+                filemap.hash_stable(hcx, &mut hasher);
+                let fingerprint = hasher.finish();
+                let dep_node = DepNode::FileMap((), Arc::new(filemap.name.clone()));
+                self.metadata_hashes.global_hashes.push((dep_node, fingerprint));
+            }).collect()
+        } else {
+            adapted.collect()
+        };
+
+        self.lazy_seq_ref(filemaps.iter().map(|fm| &**fm))
+    }
+
+    fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
+        let mut i = self.position();
+
+        let crate_deps = self.tracked(
+            DepNode::GlobalMetaData((), GlobalMetaDataKind::CrateDeps),
+            IsolatedEncoder::encode_crate_deps,
+            ());
+        let dylib_dependency_formats = self.tracked(
+            DepNode::GlobalMetaData((), GlobalMetaDataKind::DylibDependencyFormats),
+            IsolatedEncoder::encode_dylib_dependency_formats,
+            ());
+        let dep_bytes = self.position() - i;
+
+        // Encode the language items.
+        i = self.position();
+        let lang_items = self.tracked(
+            DepNode::GlobalMetaData((), GlobalMetaDataKind::LangItems),
+            IsolatedEncoder::encode_lang_items,
+            ());
+
+        let lang_items_missing = self.tracked(
+            DepNode::GlobalMetaData((), GlobalMetaDataKind::LangItemsMissing),
+            IsolatedEncoder::encode_lang_items_missing,
+            ());
+        let lang_item_bytes = self.position() - i;
+
+        // Encode the native libraries used
+        i = self.position();
+        let native_libraries = self.tracked(
+            DepNode::GlobalMetaData((), GlobalMetaDataKind::NativeLibraries),
+            IsolatedEncoder::encode_native_libraries,
+            ());
+        let native_lib_bytes = self.position() - i;
+
+        // Encode codemap
+        i = self.position();
+        let codemap = self.encode_codemap();
+        let codemap_bytes = self.position() - i;
+
+        // Encode DefPathTable
+        i = self.position();
+        let def_path_table = self.encode_def_path_table();
+        let def_path_table_bytes = self.position() - i;
+
+        // Encode the def IDs of impls, for coherence checking.
+        i = self.position();
+        let impls = self.tracked(
+            DepNode::GlobalMetaData((), GlobalMetaDataKind::Impls),
+            IsolatedEncoder::encode_impls,
+            ());
+        let impl_bytes = self.position() - i;
+
+        // Encode exported symbols info.
+        i = self.position();
+        let exported_symbols = self.tracked(
+            DepNode::GlobalMetaData((), GlobalMetaDataKind::ExportedSymbols),
+            IsolatedEncoder::encode_exported_symbols,
+            self.exported_symbols);
+        let exported_symbols_bytes = self.position() - i;
+
+        // Encode and index the items.
+        i = self.position();
+        let items = self.encode_info_for_items();
+        let item_bytes = self.position() - i;
+
+        i = self.position();
+        let index = items.write_index(&mut self.opaque.cursor);
+        let index_bytes = self.position() - i;
+
+        let tcx = self.tcx;
+        let link_meta = self.link_meta;
+        let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
+        let root = self.lazy(&CrateRoot {
+            name: tcx.crate_name(LOCAL_CRATE),
+            triple: tcx.sess.opts.target_triple.clone(),
+            hash: link_meta.crate_hash,
+            disambiguator: tcx.sess.local_crate_disambiguator(),
+            panic_strategy: Tracked::new(tcx.sess.panic_strategy()),
+            plugin_registrar_fn: tcx.sess
+                .plugin_registrar_fn
+                .get()
+                .map(|id| tcx.hir.local_def_id(id).index),
+            macro_derive_registrar: if is_proc_macro {
+                let id = tcx.sess.derive_registrar_fn.get().unwrap();
+                Some(tcx.hir.local_def_id(id).index)
+            } else {
+                None
+            },
+
+            crate_deps: crate_deps,
+            dylib_dependency_formats: dylib_dependency_formats,
+            lang_items: lang_items,
+            lang_items_missing: lang_items_missing,
+            native_libraries: native_libraries,
+            codemap: codemap,
+            def_path_table: def_path_table,
+            impls: impls,
+            exported_symbols: exported_symbols,
+            index: index,
+        });
+
+        let total_bytes = self.position();
+
+        self.metadata_hashes.global_hashes.push((
+            DepNode::GlobalMetaData((), GlobalMetaDataKind::Krate),
+            Fingerprint::from_smaller_hash(link_meta.crate_hash.as_u64())
+        ));
+
+        if self.tcx.sess.meta_stats() {
+            let mut zero_bytes = 0;
+            for e in self.opaque.cursor.get_ref() {
+                if *e == 0 {
+                    zero_bytes += 1;
+                }
+            }
+
+            println!("metadata stats:");
+            println!("             dep bytes: {}", dep_bytes);
+            println!("       lang item bytes: {}", lang_item_bytes);
+            println!("          native bytes: {}", native_lib_bytes);
+            println!("         codemap bytes: {}", codemap_bytes);
+            println!("            impl bytes: {}", impl_bytes);
+            println!("    exp. symbols bytes: {}", exported_symbols_bytes);
+            println!("  def-path table bytes: {}", def_path_table_bytes);
+            println!("            item bytes: {}", item_bytes);
+            println!("           index bytes: {}", index_bytes);
+            println!("            zero bytes: {}", zero_bytes);
+            println!("           total bytes: {}", total_bytes);
+        }
+
+        root
+    }
 }
 
-impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
-    fn encode_item_variances(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
-        debug!("EntryBuilder::encode_item_variances({:?})", def_id);
+// These are methods for encoding various things. They are meant to be used with
+// IndexBuilder::record() and EncodeContext::tracked(). They actually
+// would not have to be methods of IsolatedEncoder (free standing functions
+// taking IsolatedEncoder as first argument would be just fine) but by making
+// them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
+// clause again and again.
+impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
+    fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
+        debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
         let tcx = self.tcx;
         self.lazy_seq_from_slice(&tcx.variances_of(def_id))
     }
@@ -249,7 +483,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
         let tcx = self.tcx;
         let ty = tcx.type_of(def_id);
-        debug!("EntryBuilder::encode_item_type({:?}) => {:?}", def_id, ty);
+        debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
         self.lazy(&ty)
     }
 
@@ -265,7 +499,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
         let def = tcx.adt_def(enum_did);
         let variant = &def.variants[index];
         let def_id = variant.did;
-        debug!("EntryBuilder::encode_enum_variant_info({:?})", def_id);
+        debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
 
         let data = VariantData {
             ctor_kind: variant.ctor_kind,
@@ -306,7 +540,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
                            -> Entry<'tcx> {
         let tcx = self.tcx;
         let def_id = tcx.hir.local_def_id(id);
-        debug!("EntryBuilder::encode_info_for_mod({:?})", def_id);
+        debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
 
         let data = ModData {
             reexports: match tcx.export_map.get(&id) {
@@ -338,22 +572,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
             mir: None
         }
     }
-}
-
-impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
-    fn encode_fields(&mut self, adt_def_id: DefId) {
-        let def = self.tcx.adt_def(adt_def_id);
-        for (variant_index, variant) in def.variants.iter().enumerate() {
-            for (field_index, field) in variant.fields.iter().enumerate() {
-                self.record(field.did,
-                            EntryBuilder::encode_field,
-                            (adt_def_id, Untracked((variant_index, field_index))));
-            }
-        }
-    }
-}
 
-impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     /// Encode data for the given field of the given variant of the
     /// given ADT. The indices of the variant/field are untracked:
     /// this is ok because we will have to lookup the adt-def by its
@@ -370,7 +589,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
         let field = &variant.fields[field_index];
 
         let def_id = field.did;
-        debug!("EntryBuilder::encode_field({:?})", def_id);
+        debug!("IsolatedEncoder::encode_field({:?})", def_id);
 
         let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
         let variant_data = tcx.hir.expect_variant_data(variant_id);
@@ -396,7 +615,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     }
 
     fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
-        debug!("EntryBuilder::encode_struct_ctor({:?})", def_id);
+        debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
         let tcx = self.tcx;
         let variant = tcx.adt_def(adt_def_id).struct_variant();
 
@@ -438,19 +657,19 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     }
 
     fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
-        debug!("EntryBuilder::encode_generics({:?})", def_id);
+        debug!("IsolatedEncoder::encode_generics({:?})", def_id);
         let tcx = self.tcx;
         self.lazy(tcx.generics_of(def_id))
     }
 
     fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
-        debug!("EntryBuilder::encode_predicates({:?})", def_id);
+        debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
         let tcx = self.tcx;
         self.lazy(&tcx.predicates_of(def_id))
     }
 
     fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
-        debug!("EntryBuilder::encode_info_for_trait_item({:?})", def_id);
+        debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
         let tcx = self.tcx;
 
         let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
@@ -533,7 +752,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     }
 
     fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
-        debug!("EntryBuilder::encode_info_for_impl_item({:?})", def_id);
+        debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
         let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
         let ast_item = self.tcx.hir.expect_impl_item(node_id);
         let impl_item = self.tcx.associated_item(def_id);
@@ -631,7 +850,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
 
     // Encodes the inherent implementations of a structure, enumeration, or trait.
     fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
-        debug!("EntryBuilder::encode_inherent_implementations({:?})", def_id);
+        debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
         let implementations = self.tcx.inherent_impls(def_id);
         if implementations.is_empty() {
             LazySeq::empty()
@@ -644,19 +863,19 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     }
 
     fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
-        debug!("EntryBuilder::encode_stability({:?})", def_id);
+        debug!("IsolatedEncoder::encode_stability({:?})", def_id);
         self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
     }
 
     fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
-        debug!("EntryBuilder::encode_deprecation({:?})", def_id);
+        debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
         self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
     }
 
     fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
         let tcx = self.tcx;
 
-        debug!("EntryBuilder::encode_info_for_item({:?})", def_id);
+        debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
 
         let kind = match item.node {
             hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
@@ -824,7 +1043,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
                 hir::ItemEnum(..) |
                 hir::ItemStruct(..) |
                 hir::ItemUnion(..) |
-                hir::ItemTrait(..) => self.encode_item_variances(def_id),
+                hir::ItemTrait(..) => self.encode_variances_of(def_id),
                 _ => LazySeq::empty(),
             },
             generics: match item.node {
@@ -902,197 +1121,11 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
             mir: None,
         }
     }
-}
 
-impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
-    /// In some cases, along with the item itself, we also
-    /// encode some sub-items. Usually we want some info from the item
-    /// so it's easier to do that here then to wait until we would encounter
-    /// normally in the visitor walk.
-    fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
-        let def_id = self.tcx.hir.local_def_id(item.id);
-        match item.node {
-            hir::ItemStatic(..) |
-            hir::ItemConst(..) |
-            hir::ItemFn(..) |
-            hir::ItemMod(..) |
-            hir::ItemForeignMod(..) |
-            hir::ItemGlobalAsm(..) |
-            hir::ItemExternCrate(..) |
-            hir::ItemUse(..) |
-            hir::ItemDefaultImpl(..) |
-            hir::ItemTy(..) => {
-                // no sub-item recording needed in these cases
-            }
-            hir::ItemEnum(..) => {
-                self.encode_fields(def_id);
-
-                let def = self.tcx.adt_def(def_id);
-                for (i, variant) in def.variants.iter().enumerate() {
-                    self.record(variant.did,
-                                EntryBuilder::encode_enum_variant_info,
-                                (def_id, Untracked(i)));
-                }
-            }
-            hir::ItemStruct(ref struct_def, _) => {
-                self.encode_fields(def_id);
-
-                // If the struct has a constructor, encode it.
-                if !struct_def.is_struct() {
-                    let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
-                    self.record(ctor_def_id,
-                                EntryBuilder::encode_struct_ctor,
-                                (def_id, ctor_def_id));
-                }
-            }
-            hir::ItemUnion(..) => {
-                self.encode_fields(def_id);
-            }
-            hir::ItemImpl(..) => {
-                for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
-                    self.record(trait_item_def_id,
-                                EntryBuilder::encode_info_for_impl_item,
-                                trait_item_def_id);
-                }
-            }
-            hir::ItemTrait(..) => {
-                for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
-                    self.record(item_def_id,
-                                EntryBuilder::encode_info_for_trait_item,
-                                item_def_id);
-                }
-            }
-        }
-    }
-}
-
-impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
-    fn encode_info_for_foreign_item(&mut self,
-                                    (def_id, nitem): (DefId, &hir::ForeignItem))
-                                    -> Entry<'tcx> {
-        let tcx = self.tcx;
-
-        debug!("EntryBuilder::encode_info_for_foreign_item({:?})", def_id);
-
-        let kind = match nitem.node {
-            hir::ForeignItemFn(_, ref names, _) => {
-                let data = FnData {
-                    constness: hir::Constness::NotConst,
-                    arg_names: self.encode_fn_arg_names(names),
-                };
-                EntryKind::ForeignFn(self.lazy(&data))
-            }
-            hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
-            hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
-        };
-
-        Entry {
-            kind: kind,
-            visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
-            span: self.lazy(&nitem.span),
-            attributes: self.encode_attributes(&nitem.attrs),
-            children: LazySeq::empty(),
-            stability: self.encode_stability(def_id),
-            deprecation: self.encode_deprecation(def_id),
-
-            ty: Some(self.encode_item_type(def_id)),
-            inherent_impls: LazySeq::empty(),
-            variances: LazySeq::empty(),
-            generics: Some(self.encode_generics(def_id)),
-            predicates: Some(self.encode_predicates(def_id)),
-
-            ast: None,
-            mir: None,
-        }
-    }
-}
-
-struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
-    index: IndexBuilder<'a, 'b, 'tcx>,
-}
-
-impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
-    fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
-        NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
-    }
-    fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
-        intravisit::walk_expr(self, ex);
-        self.index.encode_info_for_expr(ex);
-    }
-    fn visit_item(&mut self, item: &'tcx hir::Item) {
-        intravisit::walk_item(self, item);
-        let def_id = self.index.tcx.hir.local_def_id(item.id);
-        match item.node {
-            hir::ItemExternCrate(_) |
-            hir::ItemUse(..) => (), // ignore these
-            _ => self.index.record(def_id, EntryBuilder::encode_info_for_item, (def_id, item)),
-        }
-        self.index.encode_addl_info_for_item(item);
-    }
-    fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
-        intravisit::walk_foreign_item(self, ni);
-        let def_id = self.index.tcx.hir.local_def_id(ni.id);
-        self.index.record(def_id,
-                          EntryBuilder::encode_info_for_foreign_item,
-                          (def_id, ni));
-    }
-    fn visit_variant(&mut self,
-                     v: &'tcx hir::Variant,
-                     g: &'tcx hir::Generics,
-                     id: ast::NodeId) {
-        intravisit::walk_variant(self, v, g, id);
-
-        if let Some(discr) = v.node.disr_expr {
-            let def_id = self.index.tcx.hir.body_owner_def_id(discr);
-            self.index.record(def_id, EntryBuilder::encode_info_for_embedded_const, def_id);
-        }
-    }
-    fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
-        intravisit::walk_generics(self, generics);
-        self.index.encode_info_for_generics(generics);
-    }
-    fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
-        intravisit::walk_ty(self, ty);
-        self.index.encode_info_for_ty(ty);
-    }
-    fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
-        let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
-        self.index.record(def_id, EntryBuilder::encode_info_for_macro_def, macro_def);
-    }
-}
-
-impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
-    fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
-        for ty_param in &generics.ty_params {
-            let def_id = self.tcx.hir.local_def_id(ty_param.id);
-            let has_default = Untracked(ty_param.default.is_some());
-            self.record(def_id, EntryBuilder::encode_info_for_ty_param, (def_id, has_default));
-        }
-    }
-
-    fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
-        if let hir::TyImplTrait(_) = ty.node {
-            let def_id = self.tcx.hir.local_def_id(ty.id);
-            self.record(def_id, EntryBuilder::encode_info_for_anon_ty, def_id);
-        }
-    }
-
-    fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
-        match expr.node {
-            hir::ExprClosure(..) => {
-                let def_id = self.tcx.hir.local_def_id(expr.id);
-                self.record(def_id, EntryBuilder::encode_info_for_closure, def_id);
-            }
-            _ => {}
-        }
-    }
-}
-
-impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     fn encode_info_for_ty_param(&mut self,
                                 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
                                 -> Entry<'tcx> {
-        debug!("EntryBuilder::encode_info_for_ty_param({:?})", def_id);
+        debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
         let tcx = self.tcx;
         Entry {
             kind: EntryKind::Type,
@@ -1119,7 +1152,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     }
 
     fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
-        debug!("EntryBuilder::encode_info_for_anon_ty({:?})", def_id);
+        debug!("IsolatedEncoder::encode_info_for_anon_ty({:?})", def_id);
         let tcx = self.tcx;
         Entry {
             kind: EntryKind::Type,
@@ -1142,7 +1175,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     }
 
     fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
-        debug!("EntryBuilder::encode_info_for_closure({:?})", def_id);
+        debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
         let tcx = self.tcx;
 
         let data = ClosureData {
@@ -1171,7 +1204,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
     }
 
     fn encode_info_for_embedded_const(&mut self, def_id: DefId) -> Entry<'tcx> {
-        debug!("EntryBuilder::encode_info_for_embedded_const({:?})", def_id);
+        debug!("IsolatedEncoder::encode_info_for_embedded_const({:?})", def_id);
         let tcx = self.tcx;
         let id = tcx.hir.as_local_node_id(def_id).unwrap();
         let body = tcx.hir.body_owned_by(id);
@@ -1198,154 +1231,70 @@ impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
 
     fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
         // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
-        //       we really on the HashStable specialization for [Attribute]
+        //       we rely on the HashStable specialization for [Attribute]
         //       to properly filter things out.
         self.lazy_seq_from_slice(attrs)
     }
-}
 
-impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
-    fn encode_info_for_items(&mut self) -> Index {
-        let krate = self.tcx.hir.krate();
-        let mut index = IndexBuilder::new(self);
-        index.record(DefId::local(CRATE_DEF_INDEX),
-                     EntryBuilder::encode_info_for_mod,
-                     FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
-        let mut visitor = EncodeVisitor { index: index };
-        krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
-        for macro_def in &krate.exported_macros {
-            visitor.visit_macro_def(macro_def);
-        }
-        visitor.index.into_items()
+    fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
+        let used_libraries = self.tcx.sess.cstore.used_libraries();
+        self.lazy_seq(used_libraries)
     }
 
-    fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
-        fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<(CrateNum, Rc<cstore::CrateMetadata>)> {
-            // Pull the cnums and name,vers,hash out of cstore
-            let mut deps = Vec::new();
-            cstore.iter_crate_data(|cnum, val| {
-                deps.push((cnum, val.clone()));
-            });
+    fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
+        let cstore = &*self.tcx.sess.cstore;
+        let crates = cstore.crates();
 
-            // Sort by cnum
-            deps.sort_by(|kv1, kv2| kv1.0.cmp(&kv2.0));
+        let mut deps = crates
+            .iter()
+            .map(|&cnum| {
+                let dep = CrateDep {
+                    name: cstore.original_crate_name(cnum),
+                    hash: cstore.crate_hash(cnum),
+                    kind: cstore.dep_kind(cnum),
+                };
+                (cnum, dep)
+            })
+            .collect::<Vec<_>>();
+
+        deps.sort_by_key(|&(cnum, _)| cnum);
 
+        {
             // Sanity-check the crate numbers
             let mut expected_cnum = 1;
             for &(n, _) in &deps {
                 assert_eq!(n, CrateNum::new(expected_cnum));
                 expected_cnum += 1;
             }
-
-            deps
         }
 
         // We're just going to write a list of crate 'name-hash-version's, with
         // the assumption that they are numbered 1 to n.
         // FIXME (#2166): This is not nearly enough to support correct versioning
         // but is enough to get transitive crate dependencies working.
-        let deps = get_ordered_deps(self.cstore);
-        self.lazy_seq(deps.iter().map(|&(_, ref dep)| {
-            CrateDep {
-                name: dep.name(),
-                hash: dep.hash(),
-                kind: dep.dep_kind.get(),
-            }
-        }))
+        self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
     }
 
-    fn encode_lang_items(&mut self) -> (LazySeq<(DefIndex, usize)>, LazySeq<lang_items::LangItem>) {
+    fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
         let tcx = self.tcx;
         let lang_items = tcx.lang_items.items().iter();
-        (self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
+        self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
             if let Some(def_id) = opt_def_id {
                 if def_id.is_local() {
                     return Some((def_id.index, i));
                 }
             }
             None
-        })),
-         self.lazy_seq_ref(&tcx.lang_items.missing))
-    }
-
-    fn encode_native_libraries(&mut self) -> LazySeq<NativeLibrary> {
-        let used_libraries = self.tcx.sess.cstore.used_libraries();
-        self.lazy_seq(used_libraries)
-    }
-
-    fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
-        let codemap = self.tcx.sess.codemap();
-        let all_filemaps = codemap.files.borrow();
-        let adapted = all_filemaps.iter()
-            .filter(|filemap| {
-                // No need to re-export imported filemaps, as any downstream
-                // crate will import them from their original source.
-                !filemap.is_imported()
-            })
-            .map(|filemap| {
-                // When exporting FileMaps, we expand all paths to absolute
-                // paths because any relative paths are potentially relative to
-                // a wrong directory.
-                // However, if a path has been modified via
-                // `-Zremap-path-prefix` we assume the user has already set
-                // things up the way they want and don't touch the path values
-                // anymore.
-                let name = Path::new(&filemap.name);
-                let (ref working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir;
-                if filemap.name_was_remapped ||
-                   (name.is_relative() && working_dir_was_remapped) {
-                    // This path of this FileMap has been modified by
-                    // path-remapping, so we use it verbatim (and avoid cloning
-                    // the whole map in the process).
-                    filemap.clone()
-                } else {
-                    let mut adapted = (**filemap).clone();
-                    let abs_path = Path::new(working_dir).join(name)
-                                                         .to_string_lossy()
-                                                         .into_owned();
-                    adapted.name = abs_path;
-                    Rc::new(adapted)
-                }
-            })
-            .collect::<Vec<_>>();
-
-        self.lazy_seq_ref(adapted.iter().map(|fm| &**fm))
-    }
-
-    fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
-        let definitions = self.tcx.hir.definitions();
-        self.lazy(definitions.def_path_table())
-    }
-}
-
-struct ImplVisitor<'a, 'tcx: 'a> {
-    tcx: TyCtxt<'a, 'tcx, 'tcx>,
-    impls: FxHashMap<DefId, Vec<DefIndex>>,
-}
-
-impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, item: &hir::Item) {
-        if let hir::ItemImpl(..) = item.node {
-            let impl_id = self.tcx.hir.local_def_id(item.id);
-            if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
-                self.impls
-                    .entry(trait_ref.def_id)
-                    .or_insert(vec![])
-                    .push(impl_id.index);
-            }
-        }
+        }))
     }
 
-    fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
-
-    fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
-        // handled in `visit_item` above
+    fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
+        let tcx = self.tcx;
+        self.lazy_seq_ref(&tcx.lang_items.missing)
     }
-}
 
-impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
     /// Encodes an index, mapping each trait to its (local) implementations.
-    fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
+    fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
         let mut visitor = ImplVisitor {
             tcx: self.tcx,
             impls: FxHashMap(),
@@ -1371,13 +1320,12 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
     // middle::reachable module but filters out items that either don't have a
     // symbol associated with them (they weren't translated) or if they're an FFI
     // definition (as that's not defined in this crate).
-    fn encode_exported_symbols(&mut self) -> LazySeq<DefIndex> {
-        let exported_symbols = self.exported_symbols;
+    fn encode_exported_symbols(&mut self, exported_symbols: &NodeSet) -> LazySeq<DefIndex> {
         let tcx = self.tcx;
         self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
     }
 
-    fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
+    fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
         match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
             Some(arr) => {
                 self.lazy_seq(arr.iter().map(|slot| {
@@ -1393,111 +1341,221 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
             None => LazySeq::empty(),
         }
     }
-}
 
-impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
-    fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
-        let mut i = self.position();
-        let crate_deps = self.encode_crate_deps();
-        let dylib_dependency_formats = self.encode_dylib_dependency_formats();
-        let dep_bytes = self.position() - i;
+    fn encode_info_for_foreign_item(&mut self,
+                                    (def_id, nitem): (DefId, &hir::ForeignItem))
+                                    -> Entry<'tcx> {
+        let tcx = self.tcx;
 
-        // Encode the language items.
-        i = self.position();
-        let (lang_items, lang_items_missing) = self.encode_lang_items();
-        let lang_item_bytes = self.position() - i;
+        debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
 
-        // Encode the native libraries used
-        i = self.position();
-        let native_libraries = self.encode_native_libraries();
-        let native_lib_bytes = self.position() - i;
+        let kind = match nitem.node {
+            hir::ForeignItemFn(_, ref names, _) => {
+                let data = FnData {
+                    constness: hir::Constness::NotConst,
+                    arg_names: self.encode_fn_arg_names(names),
+                };
+                EntryKind::ForeignFn(self.lazy(&data))
+            }
+            hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
+            hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
+        };
 
-        // Encode codemap
-        i = self.position();
-        let codemap = self.encode_codemap();
-        let codemap_bytes = self.position() - i;
+        Entry {
+            kind: kind,
+            visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
+            span: self.lazy(&nitem.span),
+            attributes: self.encode_attributes(&nitem.attrs),
+            children: LazySeq::empty(),
+            stability: self.encode_stability(def_id),
+            deprecation: self.encode_deprecation(def_id),
 
-        // Encode DefPathTable
-        i = self.position();
-        let def_path_table = self.encode_def_path_table();
-        let def_path_table_bytes = self.position() - i;
+            ty: Some(self.encode_item_type(def_id)),
+            inherent_impls: LazySeq::empty(),
+            variances: LazySeq::empty(),
+            generics: Some(self.encode_generics(def_id)),
+            predicates: Some(self.encode_predicates(def_id)),
 
-        // Encode the def IDs of impls, for coherence checking.
-        i = self.position();
-        let impls = self.encode_impls();
-        let impl_bytes = self.position() - i;
+            ast: None,
+            mir: None,
+        }
+    }
+}
 
-        // Encode exported symbols info.
-        i = self.position();
-        let exported_symbols = self.encode_exported_symbols();
-        let exported_symbols_bytes = self.position() - i;
+struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
+    index: IndexBuilder<'a, 'b, 'tcx>,
+}
 
-        // Encode and index the items.
-        i = self.position();
-        let items = self.encode_info_for_items();
-        let item_bytes = self.position() - i;
+impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
+    fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
+        NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
+    }
+    fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
+        intravisit::walk_expr(self, ex);
+        self.index.encode_info_for_expr(ex);
+    }
+    fn visit_item(&mut self, item: &'tcx hir::Item) {
+        intravisit::walk_item(self, item);
+        let def_id = self.index.tcx.hir.local_def_id(item.id);
+        match item.node {
+            hir::ItemExternCrate(_) |
+            hir::ItemUse(..) => (), // ignore these
+            _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
+        }
+        self.index.encode_addl_info_for_item(item);
+    }
+    fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
+        intravisit::walk_foreign_item(self, ni);
+        let def_id = self.index.tcx.hir.local_def_id(ni.id);
+        self.index.record(def_id,
+                          IsolatedEncoder::encode_info_for_foreign_item,
+                          (def_id, ni));
+    }
+    fn visit_variant(&mut self,
+                     v: &'tcx hir::Variant,
+                     g: &'tcx hir::Generics,
+                     id: ast::NodeId) {
+        intravisit::walk_variant(self, v, g, id);
 
-        i = self.position();
-        let index = items.write_index(&mut self.opaque.cursor);
-        let index_bytes = self.position() - i;
+        if let Some(discr) = v.node.disr_expr {
+            let def_id = self.index.tcx.hir.body_owner_def_id(discr);
+            self.index.record(def_id, IsolatedEncoder::encode_info_for_embedded_const, def_id);
+        }
+    }
+    fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
+        intravisit::walk_generics(self, generics);
+        self.index.encode_info_for_generics(generics);
+    }
+    fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
+        intravisit::walk_ty(self, ty);
+        self.index.encode_info_for_ty(ty);
+    }
+    fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
+        let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
+        self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
+    }
+}
 
-        let tcx = self.tcx;
-        let link_meta = self.link_meta;
-        let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
-        let root = self.lazy(&CrateRoot {
-            name: tcx.crate_name(LOCAL_CRATE),
-            triple: tcx.sess.opts.target_triple.clone(),
-            hash: link_meta.crate_hash,
-            disambiguator: tcx.sess.local_crate_disambiguator(),
-            panic_strategy: tcx.sess.panic_strategy(),
-            plugin_registrar_fn: tcx.sess
-                .plugin_registrar_fn
-                .get()
-                .map(|id| tcx.hir.local_def_id(id).index),
-            macro_derive_registrar: if is_proc_macro {
-                let id = tcx.sess.derive_registrar_fn.get().unwrap();
-                Some(tcx.hir.local_def_id(id).index)
-            } else {
-                None
-            },
+impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
+    fn encode_fields(&mut self, adt_def_id: DefId) {
+        let def = self.tcx.adt_def(adt_def_id);
+        for (variant_index, variant) in def.variants.iter().enumerate() {
+            for (field_index, field) in variant.fields.iter().enumerate() {
+                self.record(field.did,
+                            IsolatedEncoder::encode_field,
+                            (adt_def_id, Untracked((variant_index, field_index))));
+            }
+        }
+    }
 
-            crate_deps: crate_deps,
-            dylib_dependency_formats: dylib_dependency_formats,
-            lang_items: lang_items,
-            lang_items_missing: lang_items_missing,
-            native_libraries: native_libraries,
-            codemap: codemap,
-            def_path_table: def_path_table,
-            impls: impls,
-            exported_symbols: exported_symbols,
-            index: index,
-        });
+    fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
+        for ty_param in &generics.ty_params {
+            let def_id = self.tcx.hir.local_def_id(ty_param.id);
+            let has_default = Untracked(ty_param.default.is_some());
+            self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
+        }
+    }
 
-        let total_bytes = self.position();
+    fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
+        if let hir::TyImplTrait(_) = ty.node {
+            let def_id = self.tcx.hir.local_def_id(ty.id);
+            self.record(def_id, IsolatedEncoder::encode_info_for_anon_ty, def_id);
+        }
+    }
 
-        if self.tcx.sess.meta_stats() {
-            let mut zero_bytes = 0;
-            for e in self.opaque.cursor.get_ref() {
-                if *e == 0 {
-                    zero_bytes += 1;
+    fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
+        match expr.node {
+            hir::ExprClosure(..) => {
+                let def_id = self.tcx.hir.local_def_id(expr.id);
+                self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
+            }
+            _ => {}
+        }
+    }
+
+    /// In some cases, along with the item itself, we also
+    /// encode some sub-items. Usually we want some info from the item
+    /// so it's easier to do that here then to wait until we would encounter
+    /// normally in the visitor walk.
+    fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
+        let def_id = self.tcx.hir.local_def_id(item.id);
+        match item.node {
+            hir::ItemStatic(..) |
+            hir::ItemConst(..) |
+            hir::ItemFn(..) |
+            hir::ItemMod(..) |
+            hir::ItemForeignMod(..) |
+            hir::ItemGlobalAsm(..) |
+            hir::ItemExternCrate(..) |
+            hir::ItemUse(..) |
+            hir::ItemDefaultImpl(..) |
+            hir::ItemTy(..) => {
+                // no sub-item recording needed in these cases
+            }
+            hir::ItemEnum(..) => {
+                self.encode_fields(def_id);
+
+                let def = self.tcx.adt_def(def_id);
+                for (i, variant) in def.variants.iter().enumerate() {
+                    self.record(variant.did,
+                                IsolatedEncoder::encode_enum_variant_info,
+                                (def_id, Untracked(i)));
                 }
             }
+            hir::ItemStruct(ref struct_def, _) => {
+                self.encode_fields(def_id);
 
-            println!("metadata stats:");
-            println!("             dep bytes: {}", dep_bytes);
-            println!("       lang item bytes: {}", lang_item_bytes);
-            println!("          native bytes: {}", native_lib_bytes);
-            println!("         codemap bytes: {}", codemap_bytes);
-            println!("            impl bytes: {}", impl_bytes);
-            println!("    exp. symbols bytes: {}", exported_symbols_bytes);
-            println!("  def-path table bytes: {}", def_path_table_bytes);
-            println!("            item bytes: {}", item_bytes);
-            println!("           index bytes: {}", index_bytes);
-            println!("            zero bytes: {}", zero_bytes);
-            println!("           total bytes: {}", total_bytes);
+                // If the struct has a constructor, encode it.
+                if !struct_def.is_struct() {
+                    let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
+                    self.record(ctor_def_id,
+                                IsolatedEncoder::encode_struct_ctor,
+                                (def_id, ctor_def_id));
+                }
+            }
+            hir::ItemUnion(..) => {
+                self.encode_fields(def_id);
+            }
+            hir::ItemImpl(..) => {
+                for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
+                    self.record(trait_item_def_id,
+                                IsolatedEncoder::encode_info_for_impl_item,
+                                trait_item_def_id);
+                }
+            }
+            hir::ItemTrait(..) => {
+                for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
+                    self.record(item_def_id,
+                                IsolatedEncoder::encode_info_for_trait_item,
+                                item_def_id);
+                }
+            }
         }
+    }
+}
 
-        root
+struct ImplVisitor<'a, 'tcx: 'a> {
+    tcx: TyCtxt<'a, 'tcx, 'tcx>,
+    impls: FxHashMap<DefId, Vec<DefIndex>>,
+}
+
+impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, item: &hir::Item) {
+        if let hir::ItemImpl(..) = item.node {
+            let impl_id = self.tcx.hir.local_def_id(item.id);
+            if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
+                self.impls
+                    .entry(trait_ref.def_id)
+                    .or_insert(vec![])
+                    .push(impl_id.index);
+            }
+        }
+    }
+
+    fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
+
+    fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
+        // handled in `visit_item` above
     }
 }
 
@@ -1525,7 +1583,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
 // generated regardless of trailing bytes that end up in it.
 
 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                                 cstore: &cstore::CStore,
                                  link_meta: &LinkMeta,
                                  exported_symbols: &NodeSet)
                                  -> EncodedMetadata
@@ -1533,20 +1590,24 @@ pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
     let mut cursor = Cursor::new(vec![]);
     cursor.write_all(METADATA_HEADER).unwrap();
 
-    // Will be filed with the root position after encoding everything.
+    // Will be filled with the root position after encoding everything.
     cursor.write_all(&[0, 0, 0, 0]).unwrap();
 
+     let compute_ich = (tcx.sess.opts.debugging_opts.query_dep_graph ||
+                        tcx.sess.opts.debugging_opts.incremental_cc) &&
+                        tcx.sess.opts.build_dep_graph();
+
     let (root, metadata_hashes) = {
         let mut ecx = EncodeContext {
             opaque: opaque::Encoder::new(&mut cursor),
             tcx: tcx,
             link_meta: link_meta,
-            cstore: cstore,
             exported_symbols: exported_symbols,
             lazy_state: LazyState::NoNode,
             type_shorthands: Default::default(),
             predicate_shorthands: Default::default(),
-            metadata_hashes: Vec::new(),
+            metadata_hashes: EncodedMetadataHashes::new(),
+            compute_ich: compute_ich,
         };
 
         // Encode the rustc version string in a predictable location.
diff --git a/src/librustc_metadata/index_builder.rs b/src/librustc_metadata/index_builder.rs
index 01f948866b8..478202aeba4 100644
--- a/src/librustc_metadata/index_builder.rs
+++ b/src/librustc_metadata/index_builder.rs
@@ -58,20 +58,16 @@
 use encoder::EncodeContext;
 use index::Index;
 use schema::*;
+use isolated_encoder::IsolatedEncoder;
 
 use rustc::hir;
 use rustc::hir::def_id::DefId;
-use rustc::ich::{StableHashingContext, Fingerprint};
 use rustc::middle::cstore::EncodedMetadataHash;
 use rustc::ty::TyCtxt;
 use syntax::ast;
 
 use std::ops::{Deref, DerefMut};
 
-use rustc_data_structures::accumulate_vec::AccumulateVec;
-use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
-use rustc_serialize::Encodable;
-
 /// Builder that can encode new items, adding them into the index.
 /// Item encoding cannot be nested.
 pub struct IndexBuilder<'a, 'b: 'a, 'tcx: 'b> {
@@ -119,7 +115,7 @@ impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
     /// content system.
     pub fn record<'x, DATA>(&'x mut self,
                             id: DefId,
-                            op: fn(&mut EntryBuilder<'x, 'b, 'tcx>, DATA) -> Entry<'tcx>,
+                            op: fn(&mut IsolatedEncoder<'x, 'b, 'tcx>, DATA) -> Entry<'tcx>,
                             data: DATA)
         where DATA: DepGraphRead
     {
@@ -132,29 +128,19 @@ impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
         // unclear whether that would be a win since hashing is cheap enough.
         let _task = tcx.dep_graph.in_ignore();
 
-        let compute_ich = (tcx.sess.opts.debugging_opts.query_dep_graph ||
-                           tcx.sess.opts.debugging_opts.incremental_cc) &&
-                           tcx.sess.opts.build_dep_graph();
-
         let ecx: &'x mut EncodeContext<'b, 'tcx> = &mut *self.ecx;
-        let mut entry_builder = EntryBuilder {
-            tcx: tcx,
-            ecx: ecx,
-            hcx: if compute_ich {
-                Some((StableHashingContext::new(tcx), StableHasher::new()))
-            } else {
-                None
-            }
-        };
-
+        let mut entry_builder = IsolatedEncoder::new(ecx);
         let entry = op(&mut entry_builder, data);
+        let entry = entry_builder.lazy(&entry);
 
-        if let Some((ref mut hcx, ref mut hasher)) = entry_builder.hcx {
-            entry.hash_stable(hcx, hasher);
+        let (fingerprint, ecx) = entry_builder.finish();
+        if let Some(hash) = fingerprint {
+            ecx.metadata_hashes.entry_hashes.push(EncodedMetadataHash {
+                def_index: id.index,
+                hash: hash,
+            });
         }
 
-        let entry = entry_builder.ecx.lazy(&entry);
-        entry_builder.finish(id);
         self.items.record(id, entry);
     }
 
@@ -257,91 +243,3 @@ impl<T> DepGraphRead for FromId<T> {
         tcx.hir.read(self.0);
     }
 }
-
-pub struct EntryBuilder<'a, 'b: 'a, 'tcx: 'b> {
-    pub tcx: TyCtxt<'b, 'tcx, 'tcx>,
-    ecx: &'a mut EncodeContext<'b, 'tcx>,
-    hcx: Option<(StableHashingContext<'b, 'tcx>, StableHasher<Fingerprint>)>,
-}
-
-impl<'a, 'b: 'a, 'tcx: 'b> EntryBuilder<'a, 'b, 'tcx> {
-
-    pub fn finish(self, def_id: DefId) {
-        if let Some((_, hasher)) = self.hcx {
-            let hash = hasher.finish();
-            self.ecx.metadata_hashes.push(EncodedMetadataHash {
-                def_index: def_id.index,
-                hash: hash,
-            });
-        }
-    }
-
-    pub fn lazy<T>(&mut self, value: &T) -> Lazy<T>
-        where T: Encodable + HashStable<StableHashingContext<'b, 'tcx>>
-    {
-        if let Some((ref mut hcx, ref mut hasher)) = self.hcx {
-            value.hash_stable(hcx, hasher);
-            debug!("metadata-hash: {:?}", hasher);
-        }
-        self.ecx.lazy(value)
-    }
-
-    pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
-        where I: IntoIterator<Item = T>,
-              T: Encodable + HashStable<StableHashingContext<'b, 'tcx>>
-    {
-        if let Some((ref mut hcx, ref mut hasher)) = self.hcx {
-            let iter = iter.into_iter();
-            let (lower_bound, upper_bound) = iter.size_hint();
-
-            if upper_bound == Some(lower_bound) {
-                lower_bound.hash_stable(hcx, hasher);
-                let mut num_items_hashed = 0;
-                let ret = self.ecx.lazy_seq(iter.inspect(|item| {
-                    item.hash_stable(hcx, hasher);
-                    num_items_hashed += 1;
-                }));
-
-                // Sometimes items in a sequence are filtered out without being
-                // hashed (e.g. for &[ast::Attribute]) and this code path cannot
-                // handle that correctly, so we want to make sure we didn't hit
-                // it by accident.
-                if lower_bound != num_items_hashed {
-                    bug!("Hashed a different number of items ({}) than expected ({})",
-                         num_items_hashed,
-                         lower_bound);
-                }
-                debug!("metadata-hash: {:?}", hasher);
-                ret
-            } else {
-                // Collect into a vec so we know the length of the sequence
-                let items: AccumulateVec<[T; 32]> = iter.collect();
-                items.hash_stable(hcx, hasher);
-                debug!("metadata-hash: {:?}", hasher);
-                self.ecx.lazy_seq(items)
-            }
-        } else {
-            self.ecx.lazy_seq(iter)
-        }
-    }
-
-    pub fn lazy_seq_from_slice<T>(&mut self, slice: &[T]) -> LazySeq<T>
-        where T: Encodable + HashStable<StableHashingContext<'b, 'tcx>>
-    {
-        if let Some((ref mut hcx, ref mut hasher)) = self.hcx {
-            slice.hash_stable(hcx, hasher);
-            debug!("metadata-hash: {:?}", hasher);
-        }
-        self.ecx.lazy_seq_ref(slice.iter())
-    }
-
-    pub fn lazy_seq_ref_from_slice<T>(&mut self, slice: &[&T]) -> LazySeq<T>
-        where T: Encodable + HashStable<StableHashingContext<'b, 'tcx>>
-    {
-        if let Some((ref mut hcx, ref mut hasher)) = self.hcx {
-            slice.hash_stable(hcx, hasher);
-            debug!("metadata-hash: {:?}", hasher);
-        }
-        self.ecx.lazy_seq_ref(slice.iter().map(|x| *x))
-    }
-}
diff --git a/src/librustc_metadata/isolated_encoder.rs b/src/librustc_metadata/isolated_encoder.rs
new file mode 100644
index 00000000000..7722a7b10c9
--- /dev/null
+++ b/src/librustc_metadata/isolated_encoder.rs
@@ -0,0 +1,160 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use encoder::EncodeContext;
+use schema::{Lazy, LazySeq};
+
+use rustc::ich::{StableHashingContext, Fingerprint};
+use rustc::ty::TyCtxt;
+
+use rustc_data_structures::accumulate_vec::AccumulateVec;
+use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
+use rustc_serialize::Encodable;
+
+/// The IsolatedEncoder provides facilities to write to crate metadata while
+/// making sure that anything going through it is also feed into an ICH hasher.
+pub struct IsolatedEncoder<'a, 'b: 'a, 'tcx: 'b> {
+    pub tcx: TyCtxt<'b, 'tcx, 'tcx>,
+    ecx: &'a mut EncodeContext<'b, 'tcx>,
+    hcx: Option<(StableHashingContext<'b, 'tcx>, StableHasher<Fingerprint>)>,
+}
+
+impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
+
+    pub fn new(ecx: &'a mut EncodeContext<'b, 'tcx>) -> Self {
+        let tcx = ecx.tcx;
+        let compute_ich = ecx.compute_ich;
+        IsolatedEncoder {
+            tcx: tcx,
+            ecx: ecx,
+            hcx: if compute_ich {
+                Some((StableHashingContext::new(tcx), StableHasher::new()))
+            } else {
+                None
+            }
+        }
+    }
+
+    pub fn finish(self) -> (Option<Fingerprint>, &'a mut EncodeContext<'b, 'tcx>) {
+        if let Some((_, hasher)) = self.hcx {
+            (Some(hasher.finish()), self.ecx)
+        } else {
+            (None, self.ecx)
+        }
+    }
+
+    pub fn lazy<T>(&mut self, value: &T) -> Lazy<T>
+        where T: Encodable + HashStable<StableHashingContext<'b, 'tcx>>
+    {
+        if let Some((ref mut hcx, ref mut hasher)) = self.hcx {
+            value.hash_stable(hcx, hasher);
+            debug!("metadata-hash: {:?}", hasher);
+        }
+        self.ecx.lazy(value)
+    }
+
+    pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
+        where I: IntoIterator<Item = T>,
+              T: Encodable + HashStable<StableHashingContext<'b, 'tcx>>
+    {
+        if let Some((ref mut hcx, ref mut hasher)) = self.hcx {
+            let iter = iter.into_iter();
+            let (lower_bound, upper_bound) = iter.size_hint();
+
+            if upper_bound == Some(lower_bound) {
+                lower_bound.hash_stable(hcx, hasher);
+                let mut num_items_hashed = 0;
+                let ret = self.ecx.lazy_seq(iter.inspect(|item| {
+                    item.hash_stable(hcx, hasher);
+                    num_items_hashed += 1;
+                }));
+
+                // Sometimes items in a sequence are filtered out without being
+                // hashed (e.g. for &[ast::Attribute]) and this code path cannot
+                // handle that correctly, so we want to make sure we didn't hit
+                // it by accident.
+                if lower_bound != num_items_hashed {
+                    bug!("Hashed a different number of items ({}) than expected ({})",
+                         num_items_hashed,
+                         lower_bound);
+                }
+                debug!("metadata-hash: {:?}", hasher);
+                ret
+            } else {
+                // Collect into a vec so we know the length of the sequence
+                let items: AccumulateVec<[T; 32]> = iter.collect();
+                items.hash_stable(hcx, hasher);
+                debug!("metadata-hash: {:?}", hasher);
+                self.ecx.lazy_seq(items)
+            }
+        } else {
+            self.ecx.lazy_seq(iter)
+        }
+    }
+
+    pub fn lazy_seq_ref<'x, I, T>(&mut self, iter: I) -> LazySeq<T>
+        where I: IntoIterator<Item = &'x T>,
+              T: 'x + Encodable + HashStable<StableHashingContext<'b, 'tcx>>
+    {
+        if let Some((ref mut hcx, ref mut hasher)) = self.hcx {
+            let iter = iter.into_iter();
+            let (lower_bound, upper_bound) = iter.size_hint();
+
+            if upper_bound == Some(lower_bound) {
+                lower_bound.hash_stable(hcx, hasher);
+                let mut num_items_hashed = 0;
+                let ret = self.ecx.lazy_seq_ref(iter.inspect(|item| {
+                    item.hash_stable(hcx, hasher);
+                    num_items_hashed += 1;
+                }));
+
+                // Sometimes items in a sequence are filtered out without being
+                // hashed (e.g. for &[ast::Attribute]) and this code path cannot
+                // handle that correctly, so we want to make sure we didn't hit
+                // it by accident.
+                if lower_bound != num_items_hashed {
+                    bug!("Hashed a different number of items ({}) than expected ({})",
+                         num_items_hashed,
+                         lower_bound);
+                }
+                debug!("metadata-hash: {:?}", hasher);
+                ret
+            } else {
+                // Collect into a vec so we know the length of the sequence
+                let items: AccumulateVec<[&'x T; 32]> = iter.collect();
+                items.hash_stable(hcx, hasher);
+                debug!("metadata-hash: {:?}", hasher);
+                self.ecx.lazy_seq_ref(items.iter().map(|x| *x))
+            }
+        } else {
+            self.ecx.lazy_seq_ref(iter)
+        }
+    }
+
+    pub fn lazy_seq_from_slice<T>(&mut self, slice: &[T]) -> LazySeq<T>
+        where T: Encodable + HashStable<StableHashingContext<'b, 'tcx>>
+    {
+        if let Some((ref mut hcx, ref mut hasher)) = self.hcx {
+            slice.hash_stable(hcx, hasher);
+            debug!("metadata-hash: {:?}", hasher);
+        }
+        self.ecx.lazy_seq_ref(slice.iter())
+    }
+
+    pub fn lazy_seq_ref_from_slice<T>(&mut self, slice: &[&T]) -> LazySeq<T>
+        where T: Encodable + HashStable<StableHashingContext<'b, 'tcx>>
+    {
+        if let Some((ref mut hcx, ref mut hasher)) = self.hcx {
+            slice.hash_stable(hcx, hasher);
+            debug!("metadata-hash: {:?}", hasher);
+        }
+        self.ecx.lazy_seq_ref(slice.iter().map(|x| *x))
+    }
+}
diff --git a/src/librustc_metadata/lib.rs b/src/librustc_metadata/lib.rs
index b9e142ac650..90eb2bc0f6a 100644
--- a/src/librustc_metadata/lib.rs
+++ b/src/librustc_metadata/lib.rs
@@ -57,6 +57,7 @@ mod index;
 mod encoder;
 mod decoder;
 mod cstore_impl;
+mod isolated_encoder;
 mod schema;
 
 pub mod creader;
diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs
index e8bc8b01652..84bb82de370 100644
--- a/src/librustc_metadata/locator.rs
+++ b/src/librustc_metadata/locator.rs
@@ -367,7 +367,7 @@ impl<'a> Context<'a> {
                 && self.triple != config::host_triple() {
                 err.note(&format!("the `{}` target may not be installed", self.triple));
             }
-            err.span_label(self.span, &format!("can't find crate"));
+            err.span_label(self.span, "can't find crate");
             err
         };
 
diff --git a/src/librustc_metadata/schema.rs b/src/librustc_metadata/schema.rs
index 5870903e771..5abe1adfb6f 100644
--- a/src/librustc_metadata/schema.rs
+++ b/src/librustc_metadata/schema.rs
@@ -13,7 +13,7 @@ use index;
 
 use rustc::hir;
 use rustc::hir::def::{self, CtorKind};
-use rustc::hir::def_id::{DefIndex, DefId};
+use rustc::hir::def_id::{DefIndex, DefId, CrateNum};
 use rustc::ich::StableHashingContext;
 use rustc::middle::cstore::{DepKind, LinkagePreference, NativeLibrary};
 use rustc::middle::lang_items;
@@ -32,6 +32,8 @@ use std::mem;
 use rustc_data_structures::stable_hasher::{StableHasher, HashStable,
                                            StableHasherResult};
 
+use rustc::dep_graph::{DepGraph, DepNode};
+
 pub fn rustc_version() -> String {
     format!("rustc {}",
             option_env!("CFG_VERSION").unwrap_or("unknown version"))
@@ -186,25 +188,59 @@ pub enum LazyState {
     Previous(usize),
 }
 
+/// A `Tracked<T>` wraps a value so that one can only access it when specifying
+/// the `DepNode` for that value. This makes it harder to forget registering
+/// reads.
+#[derive(RustcEncodable, RustcDecodable)]
+pub struct Tracked<T> {
+    state: T,
+}
+
+impl<T> Tracked<T> {
+    pub fn new(state: T) -> Tracked<T> {
+        Tracked {
+            state: state,
+        }
+    }
+
+    pub fn get(&self, dep_graph: &DepGraph, dep_node: DepNode<DefId>) -> &T {
+        dep_graph.read(dep_node);
+        &self.state
+    }
+
+    pub fn get_untracked(&self) -> &T {
+        &self.state
+    }
+
+    pub fn map<F, R>(&self, f: F) -> Tracked<R>
+        where F: FnOnce(&T) -> R
+    {
+        Tracked {
+            state: f(&self.state),
+        }
+    }
+}
+
+
 #[derive(RustcEncodable, RustcDecodable)]
 pub struct CrateRoot {
     pub name: Symbol,
     pub triple: String,
     pub hash: hir::svh::Svh,
     pub disambiguator: Symbol,
-    pub panic_strategy: PanicStrategy,
+    pub panic_strategy: Tracked<PanicStrategy>,
     pub plugin_registrar_fn: Option<DefIndex>,
     pub macro_derive_registrar: Option<DefIndex>,
 
-    pub crate_deps: LazySeq<CrateDep>,
-    pub dylib_dependency_formats: LazySeq<Option<LinkagePreference>>,
-    pub lang_items: LazySeq<(DefIndex, usize)>,
-    pub lang_items_missing: LazySeq<lang_items::LangItem>,
-    pub native_libraries: LazySeq<NativeLibrary>,
+    pub crate_deps: Tracked<LazySeq<CrateDep>>,
+    pub dylib_dependency_formats: Tracked<LazySeq<Option<LinkagePreference>>>,
+    pub lang_items: Tracked<LazySeq<(DefIndex, usize)>>,
+    pub lang_items_missing: Tracked<LazySeq<lang_items::LangItem>>,
+    pub native_libraries: Tracked<LazySeq<NativeLibrary>>,
     pub codemap: LazySeq<syntax_pos::FileMap>,
     pub def_path_table: Lazy<hir::map::definitions::DefPathTable>,
-    pub impls: LazySeq<TraitImpls>,
-    pub exported_symbols: LazySeq<DefIndex>,
+    pub impls: Tracked<LazySeq<TraitImpls>>,
+    pub exported_symbols: Tracked<LazySeq<DefIndex>>,
     pub index: LazySeq<index::Index>,
 }
 
@@ -215,12 +251,35 @@ pub struct CrateDep {
     pub kind: DepKind,
 }
 
+impl_stable_hash_for!(struct CrateDep {
+    name,
+    hash,
+    kind
+});
+
 #[derive(RustcEncodable, RustcDecodable)]
 pub struct TraitImpls {
     pub trait_id: (u32, DefIndex),
     pub impls: LazySeq<DefIndex>,
 }
 
+impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for TraitImpls {
+    fn hash_stable<W: StableHasherResult>(&self,
+                                          hcx: &mut StableHashingContext<'a, 'tcx>,
+                                          hasher: &mut StableHasher<W>) {
+        let TraitImpls {
+            trait_id: (krate, def_index),
+            ref impls,
+        } = *self;
+
+        DefId {
+            krate: CrateNum::from_u32(krate),
+            index: def_index
+        }.hash_stable(hcx, hasher);
+        impls.hash_stable(hcx, hasher);
+    }
+}
+
 #[derive(RustcEncodable, RustcDecodable)]
 pub struct Entry<'tcx> {
     pub kind: EntryKind<'tcx>,
diff --git a/src/librustc_mir/transform/qualify_consts.rs b/src/librustc_mir/transform/qualify_consts.rs
index 4b1c82f383f..0d592b4d72b 100644
--- a/src/librustc_mir/transform/qualify_consts.rs
+++ b/src/librustc_mir/transform/qualify_consts.rs
@@ -242,9 +242,9 @@ impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
                    to the crate attributes to enable");
         } else {
             self.find_drop_implementation_method_span()
-                .map(|span| err.span_label(span, &format!("destructor defined here")));
+                .map(|span| err.span_label(span, "destructor defined here"));
 
-            err.span_label(self.span, &format!("constants cannot have destructors"));
+            err.span_label(self.span, "constants cannot have destructors");
         }
 
         err.emit();
@@ -291,8 +291,8 @@ impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
                 "cannot refer to statics by value, use a constant instead"
             };
             struct_span_err!(self.tcx.sess, self.span, E0394, "{}", msg)
-                .span_label(self.span, &format!("referring to another static by value"))
-                .note(&format!("use the address-of operator or a constant instead"))
+                .span_label(self.span, "referring to another static by value")
+                .note("use the address-of operator or a constant instead")
                 .emit();
 
             // Replace STATIC with NOT_CONST to avoid further errors.
@@ -529,7 +529,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> {
                                         "raw pointers cannot be dereferenced in {}s",
                                         this.mode)
                                     .span_label(this.span,
-                                        &format!("dereference of raw pointer in constant"))
+                                        "dereference of raw pointer in constant")
                                     .emit();
                                 }
                             }
@@ -645,7 +645,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> {
                             struct_span_err!(self.tcx.sess,  self.span, E0017,
                                              "references in {}s may only refer \
                                               to immutable values", self.mode)
-                                .span_label(self.span, &format!("{}s require immutable values",
+                                .span_label(self.span, format!("{}s require immutable values",
                                                                 self.mode))
                                 .emit();
                         }
@@ -713,7 +713,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> {
                             self.mode)
                         .span_label(
                             self.span,
-                            &format!("comparing raw pointers in static"))
+                            "comparing raw pointers in static")
                         .emit();
                     }
                 }
@@ -724,7 +724,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> {
                 if self.mode != Mode::Fn {
                     struct_span_err!(self.tcx.sess, self.span, E0010,
                                      "allocations are not allowed in {}s", self.mode)
-                        .span_label(self.span, &format!("allocation not allowed in {}s", self.mode))
+                        .span_label(self.span, format!("allocation not allowed in {}s", self.mode))
                         .emit();
                 }
             }
diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs
index 5f51888019b..14f277d1767 100644
--- a/src/librustc_mir/util/pretty.rs
+++ b/src/librustc_mir/util/pretty.rs
@@ -13,6 +13,7 @@ use rustc::hir::def_id::{DefId, LOCAL_CRATE};
 use rustc::mir::*;
 use rustc::mir::transform::{MirSuite, MirPassIndex, MirSource};
 use rustc::ty::TyCtxt;
+use rustc::ty::item_path;
 use rustc_data_structures::fx::FxHashMap;
 use rustc_data_structures::indexed_vec::{Idx};
 use std::fmt::Display;
@@ -48,7 +49,9 @@ pub fn dump_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
         return;
     }
 
-    let node_path = tcx.item_path_str(tcx.hir.local_def_id(source.item_id()));
+    let node_path = item_path::with_forced_impl_filename_line(|| { // see notes on #41697 below
+        tcx.item_path_str(tcx.hir.local_def_id(source.item_id()))
+    });
     dump_matched_mir_node(tcx, pass_num, pass_name, &node_path,
                           disambiguator, source, mir);
     for (index, promoted_mir) in mir.promoted.iter_enumerated() {
@@ -67,7 +70,9 @@ pub fn dump_enabled<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
         Some(ref filters) => filters,
     };
     let node_id = source.item_id();
-    let node_path = tcx.item_path_str(tcx.hir.local_def_id(node_id));
+    let node_path = item_path::with_forced_impl_filename_line(|| { // see notes on #41697 below
+        tcx.item_path_str(tcx.hir.local_def_id(node_id))
+    });
     filters.split("&")
            .any(|filter| {
                filter == "all" ||
@@ -76,6 +81,10 @@ pub fn dump_enabled<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
            })
 }
 
+// #41697 -- we use `with_forced_impl_filename_line()` because
+// `item_path_str()` would otherwise trigger `type_of`, and this can
+// run while we are already attempting to evaluate `type_of`.
+
 fn dump_matched_mir_node<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                    pass_num: Option<(MirSuite, MirPassIndex)>,
                                    pass_name: &str,
diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs
index 8c45a666945..d7fee7f3110 100644
--- a/src/librustc_passes/ast_validation.rs
+++ b/src/librustc_passes/ast_validation.rs
@@ -55,7 +55,7 @@ impl<'a> AstValidator<'a> {
                                            E0449,
                                            "unnecessary visibility qualifier");
             if vis == &Visibility::Public {
-                err.span_label(span, &format!("`pub` not needed here"));
+                err.span_label(span, "`pub` not needed here");
             }
             if let Some(note) = note {
                 err.note(note);
@@ -80,7 +80,7 @@ impl<'a> AstValidator<'a> {
             Constness::Const => {
                 struct_span_err!(self.session, constness.span, E0379,
                                  "trait fns cannot be declared const")
-                    .span_label(constness.span, &format!("trait fns cannot be const"))
+                    .span_label(constness.span, "trait fns cannot be const")
                     .emit();
             }
             _ => {}
@@ -272,7 +272,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
                                                    E0130,
                                                    "patterns aren't allowed in foreign function \
                                                     declarations");
-                    err.span_label(span, &format!("pattern not allowed in foreign function"));
+                    err.span_label(span, "pattern not allowed in foreign function");
                     if is_recent {
                         err.span_note(span,
                                       "this is a recent error, see issue #35203 for more details");
diff --git a/src/librustc_passes/consts.rs b/src/librustc_passes/consts.rs
index 608238dfe37..a0998b1bd1b 100644
--- a/src/librustc_passes/consts.rs
+++ b/src/librustc_passes/consts.rs
@@ -180,7 +180,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CheckCrateVisitor<'a, 'tcx> {
                     Ok(Ordering::Greater) => {
                         struct_span_err!(self.tcx.sess, start.span, E0030,
                             "lower range bound must be less than or equal to upper")
-                            .span_label(start.span, &format!("lower bound larger than upper bound"))
+                            .span_label(start.span, "lower bound larger than upper bound")
                             .emit();
                     }
                     Err(ErrorReported) => {}
diff --git a/src/librustc_passes/loops.rs b/src/librustc_passes/loops.rs
index 2ea235af103..21a4c007fb1 100644
--- a/src/librustc_passes/loops.rs
+++ b/src/librustc_passes/loops.rs
@@ -118,7 +118,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
                                              "`break` with value from a `{}` loop",
                                              kind.name())
                                 .span_label(e.span,
-                                            &format!("can only break with a value inside `loop`"))
+                                            "can only break with a value inside `loop`")
                                 .emit();
                         }
                     }
@@ -154,12 +154,12 @@ impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
             Loop(_) => {}
             Closure => {
                 struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
-                .span_label(span, &format!("cannot break inside of a closure"))
+                .span_label(span, "cannot break inside of a closure")
                 .emit();
             }
             Normal => {
                 struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
-                .span_label(span, &format!("cannot break outside of a loop"))
+                .span_label(span, "cannot break outside of a loop")
                 .emit();
             }
         }
@@ -169,7 +169,7 @@ impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
         struct_span_err!(self.sess, span, E0590,
                          "`break` or `continue` with no label in the condition of a `while` loop")
             .span_label(span,
-                        &format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
+                        format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
             .emit();
     }
 }
diff --git a/src/librustc_passes/static_recursion.rs b/src/librustc_passes/static_recursion.rs
index d0bf49b7b33..8d455adc23c 100644
--- a/src/librustc_passes/static_recursion.rs
+++ b/src/librustc_passes/static_recursion.rs
@@ -138,7 +138,7 @@ impl<'a, 'b: 'a, 'hir: 'b> CheckItemRecursionVisitor<'a, 'b, 'hir> {
             });
             if !any_static {
                 struct_span_err!(self.sess, span, E0265, "recursive constant")
-                    .span_label(span, &format!("recursion not allowed in constant"))
+                    .span_label(span, "recursion not allowed in constant")
                     .emit();
             }
             return;
diff --git a/src/librustc_platform_intrinsics/hexagon.rs b/src/librustc_platform_intrinsics/hexagon.rs
new file mode 100644
index 00000000000..56d639868e0
--- /dev/null
+++ b/src/librustc_platform_intrinsics/hexagon.rs
@@ -0,0 +1,2937 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// DO NOT EDIT: autogenerated by etc/platform-intrinsics/generator.py
+// ignore-tidy-linelength
+
+#![allow(unused_imports)]
+
+use {Intrinsic, Type};
+use IntrinsicDef::Named;
+
+// The default inlining settings trigger a pathological behaviour in
+// LLVM, which causes makes compilation very slow. See #28273.
+#[inline(never)]
+pub fn find(name: &str) -> Option<Intrinsic> {
+    if !name.starts_with("Q6_") { return None }
+    Some(match &name["Q6_".len()..] {
+        "R_vextract64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x16, &::U32]; &INPUTS },
+            output: &::U32,
+            definition: Named("llvm.hexagon.V6.extractw")
+        },
+        "R_vextract128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x32, &::U32]; &INPUTS },
+            output: &::U32,
+            definition: Named("llvm.hexagon.V6.extractw.128B")
+        },
+        "V_lo64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x32]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.lo")
+        },
+        "V_lo128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x64]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.lo.128B")
+        },
+        "V_hi64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x32]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.hi")
+        },
+        "V_hi128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x64]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.hi.128B")
+        },
+        "V_vsplat_R64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.lvsplatuw")
+        },
+        "V_vsplat_R128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.lvsplatuw.128B")
+        },
+        "Q_and_QQ64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x2, &::U32x2]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.pred.and")
+        },
+        "Q_and_QQ128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x4, &::U32x4]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.pred.and.128B")
+        },
+        "Q_not_Q64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x2]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.pred.not")
+        },
+        "Q_not_Q128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x4]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.pred.not.128B")
+        },
+        "Q_or_QQ64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x2, &::U32x2]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.pred.or")
+        },
+        "Q_or_QQ128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x4, &::U32x4]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.pred.or.128B")
+        },
+        "Q_xor_QQ64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x2, &::U32x2]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.pred.xor")
+        },
+        "Q_xor_QQ128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x4, &::U32x4]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.pred.xor.128B")
+        },
+        "Vub_vabsdiff_VubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vabsdiffub")
+        },
+        "Vuh_vabsdiff_VuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vabsdiffuh")
+        },
+        "Vub_vabsdiff_VubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vabsdiffub.128B")
+        },
+        "Vuh_vabsdiff_VuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vabsdiffuh.128B")
+        },
+        "Vuh_vabsdiff_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vabsdiffh")
+        },
+        "Vuw_vabsdiff_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vabsdiffw")
+        },
+        "Vuh_vabsdiff_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vabsdiffh.128B")
+        },
+        "Vuw_vabsdiff_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vabsdiffw.128B")
+        },
+        "Vh_vabs_Vh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vabsh")
+        },
+        "Vw_vabs_Vw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vabsw")
+        },
+        "Vh_vabs_Vh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vabsh.128B")
+        },
+        "Vw_vabs_Vw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vabsw.128B")
+        },
+        "Vh_vabs_Vh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vabsh.sat")
+        },
+        "Vw_vabs_Vw_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vabsw.sat")
+        },
+        "Vh_vabs_Vh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vabsh.sat.128B")
+        },
+        "Vw_vabs_Vw_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vabsw.sat.128B")
+        },
+        "Vb_vadd_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vaddb")
+        },
+        "Vh_vadd_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vaddh")
+        },
+        "Vw_vadd_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vaddw")
+        },
+        "Vb_vadd_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vaddb.128B")
+        },
+        "Vh_vadd_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vaddh.128B")
+        },
+        "Vw_vadd_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vaddw.128B")
+        },
+        "Vh_vadd_VhVh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vaddhsat")
+        },
+        "Vw_vadd_VwVw_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vaddwsat")
+        },
+        "Vh_vadd_VhVh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vaddhsat.128B")
+        },
+        "Vw_vadd_VwVw_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vaddwsat.128B")
+        },
+        "Vub_vadd_VubVub_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vaddubsat")
+        },
+        "Vuh_vadd_VuhVuh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vadduhsat")
+        },
+        "Vub_vadd_VubVub_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vaddubsat.128B")
+        },
+        "Vuh_vadd_VuhVuh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vadduhsat.128B")
+        },
+        "Wb_vadd_WbWb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vaddb.dv")
+        },
+        "Wh_vadd_WhWh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vaddh.dv")
+        },
+        "Ww_vadd_WwWw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vaddw.dv")
+        },
+        "Wb_vadd_WbWb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x256, &::I8x256]; &INPUTS },
+            output: &::I8x256,
+            definition: Named("llvm.hexagon.V6.vaddb.dv.128B")
+        },
+        "Wh_vadd_WhWh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x128, &::I16x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vaddh.dv.128B")
+        },
+        "Ww_vadd_WwWw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x64, &::I32x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vaddw.dv.128B")
+        },
+        "Wh_vadd_WhWh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vaddhsat.dv")
+        },
+        "Ww_vadd_WwWw_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vaddwsat.dv")
+        },
+        "Wh_vadd_WhWh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x128, &::I16x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vaddhsat.dv.128B")
+        },
+        "Ww_vadd_WwWw_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x64, &::I32x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vaddwsat.dv.128B")
+        },
+        "Wub_vadd_WubWub_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vaddubsat.dv")
+        },
+        "Wuh_vadd_WuhWuh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vadduhsat.dv")
+        },
+        "Wub_vadd_WubWub_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::U8x256]; &INPUTS },
+            output: &::U8x256,
+            definition: Named("llvm.hexagon.V6.vaddubsat.dv.128B")
+        },
+        "Wuh_vadd_WuhWuh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x128, &::U16x128]; &INPUTS },
+            output: &::U16x128,
+            definition: Named("llvm.hexagon.V6.vadduhsat.dv.128B")
+        },
+        "V_valign_VVR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x64, &::U8x64, &::U32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.valignb")
+        },
+        "V_valign_VVR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x128, &::U8x128, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.valignb.128B")
+        },
+        "V_valign_VVI64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x64, &::U8x64, &::U32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.valignbi")
+        },
+        "V_valign_VVI128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x128, &::U8x128, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.valignbi.128B")
+        },
+        "V_vlalign_VVR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x64, &::U8x64, &::U32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vlalignb")
+        },
+        "V_vlalign_VVR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x128, &::U8x128, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vlalignb.128B")
+        },
+        "V_vlalign_VVI64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x64, &::U8x64, &::U32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vlalignbi")
+        },
+        "V_vlalign_VVI128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x128, &::U8x128, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vlalignbi.128B")
+        },
+        "V_vand_VV64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vand")
+        },
+        "V_vand_VV128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vand.128B")
+        },
+        "V_vand_QR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x2, &::U32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vandqrt")
+        },
+        "V_vand_QR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x4, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vandqrt.128B")
+        },
+        "V_vandor_VQR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x64, &::U32x2, &::U32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vandqrt.acc")
+        },
+        "V_vandor_VQR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x128, &::U32x4, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vandqrt.acc.128B")
+        },
+        "Q_vand_VR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vandvrt")
+        },
+        "Q_vand_VR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vandvrt.128B")
+        },
+        "Q_vandor_QVR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::U8x64, &::U32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vandvrt")
+        },
+        "Q_vandor_QVR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::U8x128, &::U32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vandvrt.128B")
+        },
+        "Vh_vasl_VhR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vaslh")
+        },
+        "Vw_vasl_VwR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vaslw")
+        },
+        "Vh_vasl_VhR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vaslh.128B")
+        },
+        "Vw_vasl_VwR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vaslw.128B")
+        },
+        "Vh_vasl_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vaslhv")
+        },
+        "Vw_vasl_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vaslwv")
+        },
+        "Vh_vasl_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vaslhv.128B")
+        },
+        "Vw_vasl_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vaslwv.128B")
+        },
+        "Vw_vaslacc_VwVwR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vaslw.acc")
+        },
+        "Vw_vaslacc_VwVwR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vaslw.acc.128B")
+        },
+        "Vh_vasr_VhR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vasrh")
+        },
+        "Vw_vasr_VwR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vasrw")
+        },
+        "Vh_vasr_VhR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vasrh.128B")
+        },
+        "Vw_vasr_VwR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vasrw.128B")
+        },
+        "Vh_vasr_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vasrhv")
+        },
+        "Vw_vasr_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vasrwv")
+        },
+        "Vh_vasr_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vasrhv.128B")
+        },
+        "Vw_vasr_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vasrwv.128B")
+        },
+        "Vw_vasracc_VwVwR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vasrw.acc")
+        },
+        "Vw_vasracc_VwVwR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vasrw.acc.128B")
+        },
+        "Vh_vasr_VwVwR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vasrhw")
+        },
+        "Vh_vasr_VwVwR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vasrhw.128B")
+        },
+        "Vb_vasr_VhVhR_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x32, &::I16x32, &::U32]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vasrhbsat")
+        },
+        "Vub_vasr_VhVhR_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x32, &::I16x32, &::U32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vasrhbsat")
+        },
+        "Vh_vasr_VwVwR_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vasrwhsat")
+        },
+        "Vuh_vasr_VwVwR_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vasrwhsat")
+        },
+        "Vb_vasr_VhVhR_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::I16x64, &::U32]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vasrhbsat.128B")
+        },
+        "Vub_vasr_VhVhR_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::I16x64, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vasrhbsat.128B")
+        },
+        "Vh_vasr_VwVwR_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vasrwhsat.128B")
+        },
+        "Vuh_vasr_VwVwR_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vasrwhsat.128B")
+        },
+        "Vb_vasr_VhVhR_rnd_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x32, &::I16x32, &::U32]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vasrhbrndsat")
+        },
+        "Vub_vasr_VhVhR_rnd_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x32, &::I16x32, &::U32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vasrhbrndsat")
+        },
+        "Vh_vasr_VwVwR_rnd_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vasrwhrndsat")
+        },
+        "Vuh_vasr_VwVwR_rnd_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vasrwhrndsat")
+        },
+        "Vb_vasr_VhVhR_rnd_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::I16x64, &::U32]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vasrhbrndsat.128B")
+        },
+        "Vub_vasr_VhVhR_rnd_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::I16x64, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vasrhbrndsat.128B")
+        },
+        "Vh_vasr_VwVwR_rnd_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vasrwhrndsat.128B")
+        },
+        "Vuh_vasr_VwVwR_rnd_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vasrwhrndsat.128B")
+        },
+        "V_equals_V64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x16]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vassign")
+        },
+        "V_equals_V128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vassign.128B")
+        },
+        "W_equals_W64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vassignp")
+        },
+        "W_equals_W128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x64]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vassignp.128B")
+        },
+        "Vh_vavg_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vavgh")
+        },
+        "Vw_vavg_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vavgw")
+        },
+        "Vh_vavg_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vavgh.128B")
+        },
+        "Vw_vavg_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vavgw.128B")
+        },
+        "Vub_vavg_VubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vavgub")
+        },
+        "Vuh_vavg_VuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vavguh")
+        },
+        "Vub_vavg_VubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vavgub.128B")
+        },
+        "Vuh_vavg_VuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vavguh.128B")
+        },
+        "Vh_vavg_VhVh_rnd64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vavgrndh")
+        },
+        "Vw_vavg_VwVw_rnd64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vavgrndw")
+        },
+        "Vh_vavg_VhVh_rnd128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vavgrndh.128B")
+        },
+        "Vw_vavg_VwVw_rnd128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vavgrndw.128B")
+        },
+        "Vub_vavg_VubVub_rnd64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vavgrndub")
+        },
+        "Vuh_vavg_VuhVuh_rnd64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vavgrnduh")
+        },
+        "Vub_vavg_VubVub_rnd128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vavgrndub.128B")
+        },
+        "Vuh_vavg_VuhVuh_rnd128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vavgrnduh.128B")
+        },
+        "Vuh_vcl0_Vuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vcl0h")
+        },
+        "Vuw_vcl0_Vuw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x16]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vcl0w")
+        },
+        "Vuh_vcl0_Vuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vcl0h.128B")
+        },
+        "Vuw_vcl0_Vuw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U32x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vcl0w.128B")
+        },
+        "W_vcombine_VV64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vcombine")
+        },
+        "W_vcombine_VV128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x256,
+            definition: Named("llvm.hexagon.V6.vcombine.128B")
+        },
+        "V_vzero64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 0] = []; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vd0")
+        },
+        "V_vzero128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 0] = []; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vd0.128B")
+        },
+        "Vb_vdeal_Vb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vdealb")
+        },
+        "Vh_vdeal_Vh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vdealh")
+        },
+        "Vb_vdeal_Vb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vdealb.128B")
+        },
+        "Vh_vdeal_Vh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vdealh.128B")
+        },
+        "Vb_vdeale_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vdealb4w")
+        },
+        "Vb_vdeale_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vdealb4w.128B")
+        },
+        "W_vdeal_VVR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x64, &::U8x64, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vdealvdd")
+        },
+        "W_vdeal_VVR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x128, &::U8x128, &::U32]; &INPUTS },
+            output: &::U8x256,
+            definition: Named("llvm.hexagon.V6.vdealvdd.128B")
+        },
+        "V_vdelta_VV64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vdelta")
+        },
+        "V_vdelta_VV128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vdelta.128B")
+        },
+        "Vh_vdmpy_VubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vdmpybus")
+        },
+        "Vh_vdmpy_VubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vdmpybus.128B")
+        },
+        "Vh_vdmpyacc_VhVubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x32, &::U8x64, &::U32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vdmpybus.acc")
+        },
+        "Vh_vdmpyacc_VhVubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::U8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vdmpybus.acc.128B")
+        },
+        "Wh_vdmpy_WubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vdmpybus.dv")
+        },
+        "Wh_vdmpy_WubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vdmpybus.dv.128B")
+        },
+        "Wh_vdmpyacc_WhWubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::U8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vdmpybus.dv.acc")
+        },
+        "Wh_vdmpyacc_WhWubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x128, &::U8x256, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vdmpybus.dv.acc.128B")
+        },
+        "Vw_vdmpy_VhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhb")
+        },
+        "Vw_vdmpy_VhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhb.128B")
+        },
+        "Vw_vdmpyacc_VwVhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I16x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhb.acc")
+        },
+        "Vw_vdmpyacc_VwVhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhb.acc.128B")
+        },
+        "Ww_vdmpy_WhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhb.dv")
+        },
+        "Ww_vdmpy_WhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x128, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vdmpyhb.dv.128B")
+        },
+        "Ww_vdmpyacc_WwWhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhb.dv.acc")
+        },
+        "Ww_vdmpyacc_WwWhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x64, &::I16x128, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vdmpyhb.dv.acc.128B")
+        },
+        "Vw_vdmpy_WwRh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhisat")
+        },
+        "Vw_vdmpy_WwRh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhisat.128B")
+        },
+        "Vw_vdmpy_VhRh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhsat")
+        },
+        "Vw_vdmpy_VhRh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhsat.128B")
+        },
+        "Vw_vdmpy_WhRuh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhsuisat")
+        },
+        "Vw_vdmpy_WhRuh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x128, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhsuisat.128B")
+        },
+        "Vw_vdmpy_VhRuh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhsusat")
+        },
+        "Vw_vdmpy_VhRuh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhsusat.128B")
+        },
+        "Vw_vdmpy_VhVh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhvsat")
+        },
+        "Vw_vdmpy_VhVh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhvsat.128B")
+        },
+        "Vw_vdmpyacc_VwWwRh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhisat_acc")
+        },
+        "Vw_vdmpyacc_VwWwRh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhisat_acc.128B")
+        },
+        "Wuw_vdsad_WuhRuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vdsaduh")
+        },
+        "Wuw_vdsad_WuhRuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x128, &::U32]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vdsaduh.128B")
+        },
+        "Wuw_vdsadacc_WuwWuhRuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x32, &::U16x64, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vdsaduh.acc")
+        },
+        "Wuw_vdsadacc_WuwWuhRuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x64, &::U16x128, &::U32]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vdsaduh.acc.128B")
+        },
+        "Vw_vdmpyacc_VwVhRh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I16x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhsat_acc")
+        },
+        "Vw_vdmpyacc_VwVhRh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhsat_acc.128B")
+        },
+        "Vw_vdmpyacc_VwWhRuh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I16x64, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhsuisat_acc")
+        },
+        "Vw_vdmpyacc_VwWhRuh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x128, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhsuisat_acc.128B")
+        },
+        "Vw_vdmpyacc_VwVhRuh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I16x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhsusat_acc")
+        },
+        "Vw_vdmpyacc_VwVhRuh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhsusat_acc.128B")
+        },
+        "Vw_vdmpyacc_VwVhVh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vdmpyhvsat_acc")
+        },
+        "Vw_vdmpyacc_VwVhVh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vdmpyhvsat_acc.128B")
+        },
+        "Q_vcmp_eq_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqb")
+        },
+        "Q_vcmp_eq_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqh")
+        },
+        "Q_vcmp_eq_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqw")
+        },
+        "Q_vcmp_eq_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqb.128B")
+        },
+        "Q_vcmp_eq_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqh.128B")
+        },
+        "Q_vcmp_eq_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqw.128B")
+        },
+        "Q_vcmp_eqand_QVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqb.and")
+        },
+        "Q_vcmp_eqand_QVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqh.and")
+        },
+        "Q_vcmp_eqand_QVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqw.and")
+        },
+        "Q_vcmp_eqand_QVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqb.and.128B")
+        },
+        "Q_vcmp_eqand_QVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqh.and.128B")
+        },
+        "Q_vcmp_eqand_QVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqw.and.128B")
+        },
+        "Q_vcmp_eqor_QVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqb.or")
+        },
+        "Q_vcmp_eqor_QVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqh.or")
+        },
+        "Q_vcmp_eqor_QVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqw.or")
+        },
+        "Q_vcmp_eqor_QVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqb.or.128B")
+        },
+        "Q_vcmp_eqor_QVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqh.or.128B")
+        },
+        "Q_vcmp_eqor_QVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqw.or.128B")
+        },
+        "Q_vcmp_eqxacc_QVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqb.xor")
+        },
+        "Q_vcmp_eqxacc_QVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqh.xor")
+        },
+        "Q_vcmp_eqxacc_QVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.veqw.xor")
+        },
+        "Q_vcmp_eqxacc_QVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqb.xor.128B")
+        },
+        "Q_vcmp_eqxacc_QVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqh.xor.128B")
+        },
+        "Q_vcmp_eqxacc_QVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.veqw.xor.128B")
+        },
+        "Q_vcmp_gt_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtb")
+        },
+        "Q_vcmp_gt_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgth")
+        },
+        "Q_vcmp_gt_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtw")
+        },
+        "Q_vcmp_gt_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtb.128B")
+        },
+        "Q_vcmp_gt_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgth.128B")
+        },
+        "Q_vcmp_gt_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtw.128B")
+        },
+        "Q_vcmp_gt_VubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtub")
+        },
+        "Q_vcmp_gt_VuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtuh")
+        },
+        "Q_vcmp_gt_VubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtub.128B")
+        },
+        "Q_vcmp_gt_VuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtuh.128B")
+        },
+        "Q_vcmp_gtand_QVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtb.and")
+        },
+        "Q_vcmp_gtand_QVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgth.and")
+        },
+        "Q_vcmp_gtand_QVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtw.and")
+        },
+        "Q_vcmp_gtand_QVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtb.and.128B")
+        },
+        "Q_vcmp_gtand_QVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgth.and.128B")
+        },
+        "Q_vcmp_gtand_QVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtw.and.128B")
+        },
+        "Q_vcmp_gtand_QVubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::U8x64, &::U8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtub.and")
+        },
+        "Q_vcmp_gtand_QVuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::U16x32, &::U16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtuh.and")
+        },
+        "Q_vcmp_gtand_QVubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::U8x128, &::U8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtub.and.128B")
+        },
+        "Q_vcmp_gtand_QVuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::U16x64, &::U16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtuh.and.128B")
+        },
+        "Q_vcmp_gtor_QVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtb.or")
+        },
+        "Q_vcmp_gtor_QVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgth.or")
+        },
+        "Q_vcmp_gtor_QVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtw.or")
+        },
+        "Q_vcmp_gtor_QVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtb.or.128B")
+        },
+        "Q_vcmp_gtor_QVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgth.or.128B")
+        },
+        "Q_vcmp_gtor_QVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtw.or.128B")
+        },
+        "Q_vcmp_gtor_QVubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::U8x64, &::U8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtub.or")
+        },
+        "Q_vcmp_gtor_QVuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::U16x32, &::U16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtuh.or")
+        },
+        "Q_vcmp_gtor_QVubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::U8x128, &::U8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtub.or.128B")
+        },
+        "Q_vcmp_gtor_QVuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::U16x64, &::U16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtuh.or.128B")
+        },
+        "Q_vcmp_gtxacc_QVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtb.xor")
+        },
+        "Q_vcmp_gtxacc_QVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgth.xor")
+        },
+        "Q_vcmp_gtxacc_QVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtw.xor")
+        },
+        "Q_vcmp_gtxacc_QVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtb.xor.128B")
+        },
+        "Q_vcmp_gtxacc_QVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgth.xor.128B")
+        },
+        "Q_vcmp_gtxacc_QVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtw.xor.128B")
+        },
+        "Q_vcmp_gtxacc_QVubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::U8x64, &::U8x64]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtub.xor")
+        },
+        "Q_vcmp_gtxacc_QVuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::U16x32, &::U16x32]; &INPUTS },
+            output: &::U32x2,
+            definition: Named("llvm.hexagon.V6.vgtuh.xor")
+        },
+        "Q_vcmp_gtxacc_QVubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::U8x128, &::U8x128]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtub.xor.128B")
+        },
+        "Q_vcmp_gtxacc_QVuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::U16x64, &::U16x64]; &INPUTS },
+            output: &::U32x4,
+            definition: Named("llvm.hexagon.V6.vgtuh.xor.128B")
+        },
+        "Vw_vinsert_VwR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vinsertwr")
+        },
+        "Vw_vinsert_VwR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vinsertwr.128B")
+        },
+        "Vuh_vlsr_VuhR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vlsrh")
+        },
+        "Vuw_vlsr_VuwR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x16, &::U32]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vlsrw")
+        },
+        "Vuh_vlsr_VuhR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U32]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vlsrh.128B")
+        },
+        "Vuw_vlsr_VuwR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x32, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vlsrw.128B")
+        },
+        "Vh_vlsr_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vlsrhv")
+        },
+        "Vw_vlsr_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vlsrwv")
+        },
+        "Vh_vlsr_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vlsrhv.128B")
+        },
+        "Vw_vlsr_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vlsrwv.128B")
+        },
+        "Vb_vlut32_VbVbR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I8x64, &::I8x64, &::U32]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vlutvvb")
+        },
+        "Vb_vlut32_VbVbR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I8x128, &::I8x128, &::U32]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vlutvvb.128B")
+        },
+        "Wh_vlut16_VbVhR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I8x64, &::I16x32, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vlutvwh")
+        },
+        "Wh_vlut16_VbVhR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I8x128, &::I16x64, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vlutvwh.128B")
+        },
+        "Vb_vlut32or_VbVbVbR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 4] = [&::I8x64, &::I8x64, &::I8x64, &::U32]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vlutvvb.oracc")
+        },
+        "Vb_vlut32or_VbVbVbR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 4] = [&::I8x128, &::I8x128, &::I8x128, &::U32]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vlutvvb.oracc.128B")
+        },
+        "Wh_vlut16or_WhVbVhR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 4] = [&::I16x64, &::I8x64, &::I16x32, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vlutvwh.oracc")
+        },
+        "Wh_vlut16or_WhVbVhR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 4] = [&::I16x128, &::I8x128, &::I16x64, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vlutvwh.oracc.128B")
+        },
+        "Vh_vmax_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vmaxh")
+        },
+        "Vw_vmax_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmaxw")
+        },
+        "Vh_vmax_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmaxh.128B")
+        },
+        "Vw_vmax_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmaxw.128B")
+        },
+        "Vub_vmax_VubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vmaxub")
+        },
+        "Vuh_vmax_VuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vmaxuh")
+        },
+        "Vub_vmax_VubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vmaxub.128B")
+        },
+        "Vuh_vmax_VuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vmaxuh.128B")
+        },
+        "Vh_vmin_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vminh")
+        },
+        "Vw_vmin_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vminw")
+        },
+        "Vh_vmin_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vminh.128B")
+        },
+        "Vw_vmin_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vminw.128B")
+        },
+        "Vub_vmin_VubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vminub")
+        },
+        "Vuh_vmin_VuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vminuh")
+        },
+        "Vub_vmin_VubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vminub.128B")
+        },
+        "Vuh_vmin_VuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vminuh.128B")
+        },
+        "Wh_vmpa_WubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpabus")
+        },
+        "Wh_vmpa_WubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpabus.128B")
+        },
+        "Wh_vmpaacc_WhWubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::U8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpabus.acc")
+        },
+        "Wh_vmpaacc_WhWubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x128, &::U8x256, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpabus.acc.128B")
+        },
+        "Wh_vmpa_WubWb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::I8x128]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpabusv")
+        },
+        "Wh_vmpa_WubWub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpabuuv")
+        },
+        "Wh_vmpa_WubWb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::I8x256]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpabusv.128B")
+        },
+        "Wh_vmpa_WubWub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::U8x256]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpabuuv.128B")
+        },
+        "Ww_vmpa_WhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpahb")
+        },
+        "Ww_vmpa_WhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x128, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vmpahb.128B")
+        },
+        "Ww_vmpaacc_WwWhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpahb.acc")
+        },
+        "Ww_vmpaacc_WwWhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x64, &::I16x128, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vmpahb.acc.128B")
+        },
+        "Wh_vmpy_VbVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::U8x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpybus")
+        },
+        "Ww_vmpy_VhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U16x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyhus")
+        },
+        "Wh_vmpy_VbVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::U8x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpybus.128B")
+        },
+        "Ww_vmpy_VhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U16x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vmpyhus.128B")
+        },
+        "Wh_vmpyacc_WhVbVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::I8x64, &::U8x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpybus.acc")
+        },
+        "Ww_vmpyacc_WwVhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x32, &::U16x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyhus.acc")
+        },
+        "Wh_vmpyacc_WhVbVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x128, &::I8x128, &::U8x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpybus.acc.128B")
+        },
+        "Ww_vmpyacc_WwVhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x64, &::I16x64, &::U16x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vmpyhus.acc.128B")
+        },
+        "Wh_vmpy_VubVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::I8x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpybusv")
+        },
+        "Wh_vmpy_VubVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::I8x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpybusv.128B")
+        },
+        "Wh_vmpyacc_WhVubVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::U8x64, &::I8x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpybusv.acc")
+        },
+        "Wh_vmpyacc_WhVubVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x128, &::U8x128, &::I8x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpybusv.acc.128B")
+        },
+        "Wh_vmpy_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpybv")
+        },
+        "Wuh_vmpy_VubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vmpyubv")
+        },
+        "Ww_vmpy_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyhv")
+        },
+        "Wuw_vmpy_VuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vmpyuhv")
+        },
+        "Wh_vmpy_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpybv.128B")
+        },
+        "Wuh_vmpy_VubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U16x128,
+            definition: Named("llvm.hexagon.V6.vmpyubv.128B")
+        },
+        "Ww_vmpy_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vmpyhv.128B")
+        },
+        "Wuw_vmpy_VuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vmpyuhv.128B")
+        },
+        "Wh_vmpyacc_WhVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpybv.acc")
+        },
+        "Wuh_vmpyacc_WuhVubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U16x64, &::U8x64, &::U8x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vmpyubv.acc")
+        },
+        "Ww_vmpyacc_WwVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyhv.acc")
+        },
+        "Wuw_vmpyacc_WuwVuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x32, &::U16x32, &::U16x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vmpyuhv.acc")
+        },
+        "Wh_vmpyacc_WhVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x128, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vmpybv.acc.128B")
+        },
+        "Wuh_vmpyacc_WuhVubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U16x128, &::U8x128, &::U8x128]; &INPUTS },
+            output: &::U16x128,
+            definition: Named("llvm.hexagon.V6.vmpyubv.acc.128B")
+        },
+        "Ww_vmpyacc_WwVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x64, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vmpyhv.acc.128B")
+        },
+        "Wuw_vmpyacc_WuwVuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x64, &::U16x64, &::U16x64]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vmpyuhv.acc.128B")
+        },
+        "Vw_vmpye_VwVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::U16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyewuh")
+        },
+        "Vw_vmpye_VwVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::U16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyewuh.128B")
+        },
+        "Ww_vmpy_VhRh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyh")
+        },
+        "Wuw_vmpy_VuhRuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vmpyuh")
+        },
+        "Ww_vmpy_VhRh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vmpyh.128B")
+        },
+        "Wuw_vmpy_VuhRuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U32]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vmpyuh.128B")
+        },
+        "Ww_vmpyacc_WwVhRh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyhsat.acc")
+        },
+        "Ww_vmpyacc_WwVhRh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x64, &::I16x64, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vmpyhsat.acc.128B")
+        },
+        "Vw_vmpy_VhRh_s1_rnd_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyhsrs")
+        },
+        "Vw_vmpy_VhRh_s1_rnd_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyhsrs.128B")
+        },
+        "Vw_vmpy_VhRh_s1_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyhss")
+        },
+        "Vw_vmpy_VhRh_s1_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyhss.128B")
+        },
+        "Vh_vmpy_VhVh_s1_rnd_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vmpyhvsrs")
+        },
+        "Vh_vmpy_VhVh_s1_rnd_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpyhvsrs.128B")
+        },
+        "Vw_vmpyieo_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyieoh")
+        },
+        "Vw_vmpyieo_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyieoh.128B")
+        },
+        "Vw_vmpyieacc_VwVwVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::I16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiewh.acc")
+        },
+        "Vw_vmpyieacc_VwVwVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiewuh.acc")
+        },
+        "Vw_vmpyieacc_VwVwVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::I16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiewh.acc.128B")
+        },
+        "Vw_vmpyieacc_VwVwVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiewuh.acc.128B")
+        },
+        "Vw_vmpyie_VwVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::U16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiewuh")
+        },
+        "Vw_vmpyie_VwVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::U16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiewuh.128B")
+        },
+        "Vh_vmpyi_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vmpyih")
+        },
+        "Vh_vmpyi_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpyih.128B")
+        },
+        "Vh_vmpyiacc_VhVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x32, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vmpyih.acc")
+        },
+        "Vh_vmpyiacc_VhVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpyih.acc.128B")
+        },
+        "Vh_vmpyi_VhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::U32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vmpyihb")
+        },
+        "Vw_vmpyi_VwRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiwb")
+        },
+        "Vh_vmpyi_VhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpyihb.128B")
+        },
+        "Vw_vmpyi_VwRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiwb.128B")
+        },
+        "Vh_vmpyiacc_VhVhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x32, &::I16x32, &::U32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vmpyihb.acc")
+        },
+        "Vw_vmpyiacc_VwVwRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiwb.acc")
+        },
+        "Vh_vmpyiacc_VhVhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::I16x64, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vmpyihb.acc.128B")
+        },
+        "Vw_vmpyiacc_VwVwRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiwb.acc.128B")
+        },
+        "Vw_vmpyi_VwRh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiwh")
+        },
+        "Vw_vmpyi_VwRh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiwh.128B")
+        },
+        "Vw_vmpyiacc_VwVwRh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiwh.acc")
+        },
+        "Vw_vmpyiacc_VwVwRh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiwh.acc.128B")
+        },
+        "Vw_vmpyi_VwRub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiwub")
+        },
+        "Vw_vmpyi_VwRub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiwub.128B")
+        },
+        "Vw_vmpyiacc_VwVwRub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I32x16, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiwub.acc")
+        },
+        "Vw_vmpyiacc_VwVwRub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I32x32, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiwub.acc.128B")
+        },
+        "Vw_vmpyo_VwVh_s1_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyowh")
+        },
+        "Vw_vmpyo_VwVh_s1_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyowh.128B")
+        },
+        "Vw_vmpyo_VwVh_s1_rnd_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyowh.rnd")
+        },
+        "Vw_vmpyo_VwVh_s1_rnd_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyowh.rnd.128B")
+        },
+        "Vw_vmpyo_VwVh_s1_rnd_sat_shift64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyowh.rnd.sacc")
+        },
+        "Vw_vmpyo_VwVh_s1_rnd_sat_shift128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyowh.rnd.sacc.128B")
+        },
+        "Vw_vmpyo_VwVh_s1_sat_shift64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyowh.sacc")
+        },
+        "Vw_vmpyo_VwVh_s1_sat_shift128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyowh.sacc.128B")
+        },
+        "Vw_vmpyio_VwVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I16x32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vmpyiowh")
+        },
+        "Vw_vmpyio_VwVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I16x64]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vmpyiowh.128B")
+        },
+        "Wuh_vmpy_VubRub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U32]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vmpyub")
+        },
+        "Wuh_vmpy_VubRub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::U16x128,
+            definition: Named("llvm.hexagon.V6.vmpyub.128B")
+        },
+        "Wuh_vmpyacc_WuhVubRub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U16x64, &::U8x64, &::U32]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vmpyub.acc")
+        },
+        "Wuw_vmpyacc_WuwVuhRuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x32, &::U16x32, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vmpyuh.acc")
+        },
+        "Wuh_vmpyacc_WuhVubRub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U16x128, &::U8x128, &::U32]; &INPUTS },
+            output: &::U16x128,
+            definition: Named("llvm.hexagon.V6.vmpyub.acc.128B")
+        },
+        "Wuw_vmpyacc_WuwVuhRuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x64, &::U16x64, &::U32]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vmpyuh.acc.128B")
+        },
+        "Vuw_vmux_QVV64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::U32x16, &::U32x16]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vmux")
+        },
+        "Vuw_vmux_QVV128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::U32x32, &::U32x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vmux.128B")
+        },
+        "Vh_vnavg_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vnavgh")
+        },
+        "Vuh_vnavg_VuhVuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vnavguh")
+        },
+        "Vw_vnavg_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vnavgw")
+        },
+        "Vuw_vnavg_VuwVuw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x16, &::U32x16]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vnavguw")
+        },
+        "Vh_vnavg_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vnavgh.128B")
+        },
+        "Vuh_vnavg_VuhVuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vnavguh.128B")
+        },
+        "Vw_vnavg_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vnavgw.128B")
+        },
+        "Vuw_vnavg_VuwVuw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U32x32, &::U32x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vnavguw.128B")
+        },
+        "Vub_vnavg_VubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vnavgub")
+        },
+        "Vub_vnavg_VubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vnavgub.128B")
+        },
+        "Vh_vnormamt_Vh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vnormamth")
+        },
+        "Vw_vnormamt_Vw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vnormamtw")
+        },
+        "Vh_vnormamt_Vh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vnormamth.128B")
+        },
+        "Vw_vnormamt_Vw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vnormamtw.128B")
+        },
+        "V_vnot_VV64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vnot")
+        },
+        "V_vnot_VV128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vnot.128B")
+        },
+        "V_vor_VV64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vor")
+        },
+        "V_vor_VV128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vor.128B")
+        },
+        "Vb_vpacke_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vpackhe")
+        },
+        "Vh_vpacke_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vpackwe")
+        },
+        "Vb_vpacke_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vpackhe.128B")
+        },
+        "Vh_vpacke_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vpackwe.128B")
+        },
+        "Vb_vpacko_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vpackho")
+        },
+        "Vh_vpacko_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vpackwo")
+        },
+        "Vb_vpacko_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vpackho.128B")
+        },
+        "Vh_vpacko_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vpackwo.128B")
+        },
+        "Vb_vpack_VhVh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vpackhb.sat")
+        },
+        "Vub_vpack_VhVh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vpackhub.sat")
+        },
+        "Vh_vpack_VwVw_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vpackwh.sat")
+        },
+        "Vuh_vpack_VwVw_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vpackwuh.sat")
+        },
+        "Vb_vpack_VhVh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vpackhb.sat.128B")
+        },
+        "Vub_vpack_VhVh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vpackhub.sat.128B")
+        },
+        "Vh_vpack_VwVw_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vpackwh.sat.128B")
+        },
+        "Vuh_vpack_VwVw_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vpackwuh.sat.128B")
+        },
+        "Vh_vpopcount_Vh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vpopcounth")
+        },
+        "Vh_vpopcount_Vh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vpopcounth.128B")
+        },
+        "V_vrdelta_VV64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vrdelta")
+        },
+        "V_vrdelta_VV128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vrdelta.128B")
+        },
+        "Vw_vrmpy_VubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vrmpybus")
+        },
+        "Vw_vrmpy_VubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vrmpybus.128B")
+        },
+        "Vw_vrmpyacc_VwVubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::U8x64, &::U32]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vrmpybus.acc")
+        },
+        "Vw_vrmpyacc_VwVubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::U8x128, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vrmpybus.acc.128B")
+        },
+        "Ww_vrmpy_WubRbI64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vrmpybusi")
+        },
+        "Ww_vrmpy_WubRbI128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vrmpybusi.128B")
+        },
+        "Ww_vrmpyacc_WwWubRbI64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::U8x128, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vrmpybusi.acc")
+        },
+        "Ww_vrmpyacc_WwWubRbI128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x64, &::U8x256, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vrmpybusi.acc.128B")
+        },
+        "Vw_vrmpy_VubVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::I8x64]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vrmpybusv")
+        },
+        "Vw_vrmpy_VubVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::I8x128]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vrmpybusv.128B")
+        },
+        "Vw_vrmpyacc_VwVubVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::U8x64, &::I8x64]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vrmpybusv.acc")
+        },
+        "Vw_vrmpyacc_VwVubVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::U8x128, &::I8x128]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vrmpybusv.acc.128B")
+        },
+        "Vw_vrmpy_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vrmpybv")
+        },
+        "Vuw_vrmpy_VubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vrmpyubv")
+        },
+        "Vw_vrmpy_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vrmpybv.128B")
+        },
+        "Vuw_vrmpy_VubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vrmpyubv.128B")
+        },
+        "Vw_vrmpyacc_VwVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x16, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vrmpywv.acc")
+        },
+        "Vuw_vrmpyacc_VuwVubVub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x16, &::U8x64, &::U8x64]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vrmpyuwv.acc")
+        },
+        "Vw_vrmpyacc_VwVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vrmpywv.acc.128B")
+        },
+        "Vuw_vrmpyacc_VuwVubVub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x32, &::U8x128, &::U8x128]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vrmpyuwv.acc.128B")
+        },
+        "Vuw_vrmpy_VubRub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U32]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vrmpyub")
+        },
+        "Vuw_vrmpy_VubRub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vrmpyub.128B")
+        },
+        "Vuw_vrmpyacc_VuwVubRub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x16, &::U8x64, &::U32]; &INPUTS },
+            output: &::U32x16,
+            definition: Named("llvm.hexagon.V6.vrmpyub.acc")
+        },
+        "Vuw_vrmpyacc_VuwVubRub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x32, &::U8x128, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vrmpyub.acc.128B")
+        },
+        "Wuw_vrmpy_WubRubI64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vrmpyubi")
+        },
+        "Wuw_vrmpy_WubRubI128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::U32]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vrmpyubi.128B")
+        },
+        "Wuw_vrmpyacc_WuwWubRubI64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x32, &::U8x128, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vrmpyubi.acc")
+        },
+        "Wuw_vrmpyacc_WuwWubRubI128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x64, &::U8x256, &::U32]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vrmpyubi.acc.128B")
+        },
+        "V_vror_VR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vror")
+        },
+        "V_vror_VR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vror.128B")
+        },
+        "Vb_vround_VhVh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vroundhb")
+        },
+        "Vub_vround_VhVh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vroundhub")
+        },
+        "Vh_vround_VwVw_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vroundwh")
+        },
+        "Vuh_vround_VwVw_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vroundwuh")
+        },
+        "Vb_vround_VhVh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vroundhb.128B")
+        },
+        "Vub_vround_VhVh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vroundhub.128B")
+        },
+        "Vh_vround_VwVw_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vroundwh.128B")
+        },
+        "Vuh_vround_VwVw_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vroundwuh.128B")
+        },
+        "Wuw_vrsad_WubRubI64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vrsadubi")
+        },
+        "Wuw_vrsad_WubRubI128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::U32]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vrsadubi.128B")
+        },
+        "Wuw_vrsadacc_WuwWubRubI64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x32, &::U8x128, &::U32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vrsadubi.acc")
+        },
+        "Wuw_vrsadacc_WuwWubRubI128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x64, &::U8x256, &::U32]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vrsadubi.acc.128B")
+        },
+        "Vub_vsat_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vsathub")
+        },
+        "Vub_vsat_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vsathub.128B")
+        },
+        "Vh_vsat_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vsatwh")
+        },
+        "Vh_vsat_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vsatwh.128B")
+        },
+        "Wh_vsxt_Vb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I8x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vsb")
+        },
+        "Ww_vsxt_Vh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vsh")
+        },
+        "Wh_vsxt_Vb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I8x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vsb.128B")
+        },
+        "Ww_vsxt_Vh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vsh.128B")
+        },
+        "Wuh_vzxt_Vub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U8x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vzb")
+        },
+        "Wuw_vzxt_Vuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U16x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vzh")
+        },
+        "Wuh_vzxt_Vub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U8x128]; &INPUTS },
+            output: &::U16x128,
+            definition: Named("llvm.hexagon.V6.vzb.128B")
+        },
+        "Wuw_vzxt_Vuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U16x64]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vzh.128B")
+        },
+        "Vb_condacc_QVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vaddbq")
+        },
+        "Vh_condacc_QVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vaddhq")
+        },
+        "Vw_condacc_QVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vaddwq")
+        },
+        "Vb_condacc_QVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vaddbq.128B")
+        },
+        "Vh_condacc_QVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vaddhq.128B")
+        },
+        "Vw_condacc_QVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vaddwq.128B")
+        },
+        "Vb_condacc_QnVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vaddbnq")
+        },
+        "Vh_condacc_QnVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vaddhnq")
+        },
+        "Vw_condacc_QnVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vaddwnq")
+        },
+        "Vb_condacc_QnVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vaddbnq.128B")
+        },
+        "Vh_condacc_QnVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vaddhnq.128B")
+        },
+        "Vw_condacc_QnVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vaddwnq.128B")
+        },
+        "Vb_condnac_QVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vsubbq")
+        },
+        "Vh_condnac_QVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vsubhq")
+        },
+        "Vw_condnac_QVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vsubwq")
+        },
+        "Vb_condnac_QVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vsubbq.128B")
+        },
+        "Vh_condnac_QVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vsubhq.128B")
+        },
+        "Vw_condnac_QVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vsubwq.128B")
+        },
+        "Vb_condnac_QnVbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vsubbnq")
+        },
+        "Vh_condnac_QnVhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vsubhnq")
+        },
+        "Vw_condnac_QnVwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vsubwnq")
+        },
+        "Vb_condnac_QnVbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vsubbnq.128B")
+        },
+        "Vh_condnac_QnVhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vsubhnq.128B")
+        },
+        "Vw_condnac_QnVwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vsubwnq.128B")
+        },
+        "Vh_vshuffe_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vshufeh")
+        },
+        "Vh_vshuffe_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vshufeh.128B")
+        },
+        "Vh_vshuffo_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vshufoh")
+        },
+        "Vh_vshuffo_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vshufoh.128B")
+        },
+        "Vb_vshuff_Vb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vshuffb")
+        },
+        "Vh_vshuff_Vh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vshuffh")
+        },
+        "Vb_vshuff_Vb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vshuffb.128B")
+        },
+        "Vh_vshuff_Vh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vshuffh.128B")
+        },
+        "Vb_vshuffe_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vshuffeb")
+        },
+        "Vb_vshuffe_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vshuffeb.128B")
+        },
+        "Vb_vshuffo_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vshuffob")
+        },
+        "Vb_vshuffo_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vshuffob.128B")
+        },
+        "Vb_vshuffoe_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vshuffoeb")
+        },
+        "Vh_vshuffoe_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vshuffoeh")
+        },
+        "Vb_vshuffoe_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vshuffoeb.128B")
+        },
+        "Vh_vshuffoe_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vshuffoeh.128B")
+        },
+        "W_vshuff_VVR64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x64, &::U8x64, &::U32]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vshufvvd")
+        },
+        "W_vshuff_VVR128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U8x128, &::U8x128, &::U32]; &INPUTS },
+            output: &::U8x256,
+            definition: Named("llvm.hexagon.V6.vshufvvd.128B")
+        },
+        "Vb_vsub_VbVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x64, &::I8x64]; &INPUTS },
+            output: &::I8x64,
+            definition: Named("llvm.hexagon.V6.vsubb")
+        },
+        "Vh_vsub_VhVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vsubh")
+        },
+        "Vw_vsub_VwVw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vsubw")
+        },
+        "Vb_vsub_VbVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vsubb.128B")
+        },
+        "Vh_vsub_VhVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vsubh.128B")
+        },
+        "Vw_vsub_VwVw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vsubw.128B")
+        },
+        "Vh_vsub_VhVh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x32, &::I16x32]; &INPUTS },
+            output: &::I16x32,
+            definition: Named("llvm.hexagon.V6.vsubhsat")
+        },
+        "Vw_vsub_VwVw_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x16, &::I32x16]; &INPUTS },
+            output: &::I32x16,
+            definition: Named("llvm.hexagon.V6.vsubwsat")
+        },
+        "Vh_vsub_VhVh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vsubhsat.128B")
+        },
+        "Vw_vsub_VwVw_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vsubwsat.128B")
+        },
+        "Vub_vsub_VubVub_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x64,
+            definition: Named("llvm.hexagon.V6.vsububsat")
+        },
+        "Vuh_vsub_VuhVuh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vsubuhsat")
+        },
+        "Vub_vsub_VubVub_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vsububsat.128B")
+        },
+        "Vuh_vsub_VuhVuh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vsubuhsat.128B")
+        },
+        "Wb_vsub_WbWb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::I8x128]; &INPUTS },
+            output: &::I8x128,
+            definition: Named("llvm.hexagon.V6.vsubb.dv")
+        },
+        "Wh_vsub_WhWh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vsubh.dv")
+        },
+        "Ww_vsub_WwWw64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vsubw.dv")
+        },
+        "Wb_vsub_WbWb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x256, &::I8x256]; &INPUTS },
+            output: &::I8x256,
+            definition: Named("llvm.hexagon.V6.vsubb.dv.128B")
+        },
+        "Wh_vsub_WhWh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x128, &::I16x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vsubh.dv.128B")
+        },
+        "Ww_vsub_WwWw128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x64, &::I32x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vsubw.dv.128B")
+        },
+        "Wh_vsub_WhWh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I16x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vsubhsat.dv")
+        },
+        "Ww_vsub_WwWw_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I32x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vsubwsat.dv")
+        },
+        "Wh_vsub_WhWh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x128, &::I16x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vsubhsat.dv.128B")
+        },
+        "Ww_vsub_WwWw_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x64, &::I32x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vsubwsat.dv.128B")
+        },
+        "Wub_vsub_WubWub_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vsububsat.dv")
+        },
+        "Wuh_vsub_WuhWuh_sat64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vsubuhsat.dv")
+        },
+        "Wub_vsub_WubWub_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::U8x256]; &INPUTS },
+            output: &::U8x256,
+            definition: Named("llvm.hexagon.V6.vsububsat.dv.128B")
+        },
+        "Wuh_vsub_WuhWuh_sat128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x128, &::U16x128]; &INPUTS },
+            output: &::U16x128,
+            definition: Named("llvm.hexagon.V6.vsubuhsat.dv.128B")
+        },
+        "W_vswap_QVV64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x2, &::U8x64, &::U8x64]; &INPUTS },
+            output: &::U8x128,
+            definition: Named("llvm.hexagon.V6.vswap")
+        },
+        "W_vswap_QVV128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::U32x4, &::U8x128, &::U8x128]; &INPUTS },
+            output: &::U8x256,
+            definition: Named("llvm.hexagon.V6.vswap.128B")
+        },
+        "Wh_vtmpy_WbRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vtmpyb")
+        },
+        "Wh_vtmpy_WbRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I8x256, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vtmpyb.128B")
+        },
+        "Wh_vtmpyacc_WhWbRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::I8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vtmpyb.acc")
+        },
+        "Wh_vtmpyacc_WhWbRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x128, &::I8x256, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vtmpyb.acc.128B")
+        },
+        "Wh_vtmpy_WubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vtmpybus")
+        },
+        "Wh_vtmpy_WubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U8x256, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vtmpybus.128B")
+        },
+        "Wh_vtmpyacc_WhWubRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x64, &::U8x128, &::U32]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vtmpybus.acc")
+        },
+        "Wh_vtmpyacc_WhWubRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I16x128, &::U8x256, &::U32]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vtmpybus.acc.128B")
+        },
+        "Ww_vtmpy_WhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vtmpyhb")
+        },
+        "Ww_vtmpy_WhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x128, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vtmpyhb.128B")
+        },
+        "Wh_vunpack_Vb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I8x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vunpackb")
+        },
+        "Wuh_vunpack_Vub64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U8x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vunpackub")
+        },
+        "Ww_vunpack_Vh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vunpackh")
+        },
+        "Wuw_vunpack_Vuh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U16x32]; &INPUTS },
+            output: &::U32x32,
+            definition: Named("llvm.hexagon.V6.vunpackuh")
+        },
+        "Wh_vunpack_Vb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I8x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vunpackb.128B")
+        },
+        "Wuh_vunpack_Vub128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U8x128]; &INPUTS },
+            output: &::U16x128,
+            definition: Named("llvm.hexagon.V6.vunpackub.128B")
+        },
+        "Ww_vunpack_Vh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::I16x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vunpackh.128B")
+        },
+        "Wuw_vunpack_Vuh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 1] = [&::U16x64]; &INPUTS },
+            output: &::U32x64,
+            definition: Named("llvm.hexagon.V6.vunpackuh.128B")
+        },
+        "Wh_vunpackoor_WhVb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x64, &::I8x64]; &INPUTS },
+            output: &::I16x64,
+            definition: Named("llvm.hexagon.V6.vunpackob")
+        },
+        "Ww_vunpackoor_WwVh64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x32, &::I16x32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vunpackoh")
+        },
+        "Wh_vunpackoor_WhVb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I16x128, &::I8x128]; &INPUTS },
+            output: &::I16x128,
+            definition: Named("llvm.hexagon.V6.vunpackob.128B")
+        },
+        "Ww_vunpackoor_WwVh128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::I32x64, &::I16x64]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vunpackoh.128B")
+        },
+        "Ww_vtmpyacc_WwWhRb64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x32, &::I16x64, &::U32]; &INPUTS },
+            output: &::I32x32,
+            definition: Named("llvm.hexagon.V6.vtmpyhb.acc")
+        },
+        "Ww_vtmpyacc_WwWhRb128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 3] = [&::I32x64, &::I16x128, &::U32]; &INPUTS },
+            output: &::I32x64,
+            definition: Named("llvm.hexagon.V6.vtmpyhb.acc.128B")
+        },
+        "V_vxor_VV64" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x32, &::U16x32]; &INPUTS },
+            output: &::U16x32,
+            definition: Named("llvm.hexagon.V6.vxor")
+        },
+        "V_vxor_VV128" => Intrinsic {
+            inputs: { static INPUTS: [&'static Type; 2] = [&::U16x64, &::U16x64]; &INPUTS },
+            output: &::U16x64,
+            definition: Named("llvm.hexagon.V6.vxor.128B")
+        },
+        _ => return None,
+    })
+}
diff --git a/src/librustc_platform_intrinsics/lib.rs b/src/librustc_platform_intrinsics/lib.rs
index 296c133115f..dd2d60a1d22 100644
--- a/src/librustc_platform_intrinsics/lib.rs
+++ b/src/librustc_platform_intrinsics/lib.rs
@@ -29,7 +29,7 @@ pub enum Type {
     Integer(/* signed */ bool, u8, /* llvm width */ u8),
     Float(u8),
     Pointer(&'static Type, Option<&'static Type>, /* const */ bool),
-    Vector(&'static Type, Option<&'static Type>, u8),
+    Vector(&'static Type, Option<&'static Type>, u16),
     Aggregate(bool, &'static [&'static Type]),
 }
 
@@ -56,6 +56,12 @@ static I8x16: Type = Type::Vector(&I8, None, 16);
 static U8x16: Type = Type::Vector(&U8, None, 16);
 static I8x32: Type = Type::Vector(&I8, None, 32);
 static U8x32: Type = Type::Vector(&U8, None, 32);
+static I8x64: Type = Type::Vector(&I8, None, 64);
+static U8x64: Type = Type::Vector(&U8, None, 64);
+static I8x128: Type = Type::Vector(&I8, None, 128);
+static U8x128: Type = Type::Vector(&U8, None, 128);
+static I8x256: Type = Type::Vector(&I8, None, 256);
+static U8x256: Type = Type::Vector(&U8, None, 256);
 
 static I16x4: Type = Type::Vector(&I16, None, 4);
 static U16x4: Type = Type::Vector(&U16, None, 4);
@@ -63,6 +69,12 @@ static I16x8: Type = Type::Vector(&I16, None, 8);
 static U16x8: Type = Type::Vector(&U16, None, 8);
 static I16x16: Type = Type::Vector(&I16, None, 16);
 static U16x16: Type = Type::Vector(&U16, None, 16);
+static I16x32: Type = Type::Vector(&I16, None, 32);
+static U16x32: Type = Type::Vector(&U16, None, 32);
+static I16x64: Type = Type::Vector(&I16, None, 64);
+static U16x64: Type = Type::Vector(&U16, None, 64);
+static I16x128: Type = Type::Vector(&I16, None, 128);
+static U16x128: Type = Type::Vector(&U16, None, 128);
 
 static I32x2: Type = Type::Vector(&I32, None, 2);
 static U32x2: Type = Type::Vector(&U32, None, 2);
@@ -70,6 +82,12 @@ static I32x4: Type = Type::Vector(&I32, None, 4);
 static U32x4: Type = Type::Vector(&U32, None, 4);
 static I32x8: Type = Type::Vector(&I32, None, 8);
 static U32x8: Type = Type::Vector(&U32, None, 8);
+static I32x16: Type = Type::Vector(&I32, None, 16);
+static U32x16: Type = Type::Vector(&U32, None, 16);
+static I32x32: Type = Type::Vector(&I32, None, 32);
+static U32x32: Type = Type::Vector(&U32, None, 32);
+static I32x64: Type = Type::Vector(&I32, None, 64);
+static U32x64: Type = Type::Vector(&U32, None, 64);
 
 static I64x1: Type = Type::Vector(&I64, None, 1);
 static U64x1: Type = Type::Vector(&U64, None, 1);
@@ -96,6 +114,7 @@ mod x86;
 mod arm;
 mod aarch64;
 mod nvptx;
+mod hexagon;
 
 impl Intrinsic {
     pub fn find(name: &str) -> Option<Intrinsic> {
@@ -107,6 +126,8 @@ impl Intrinsic {
             aarch64::find(name)
         } else if name.starts_with("nvptx_") {
             nvptx::find(name)
+        } else if name.starts_with("Q6_") {
+            hexagon::find(name)
         } else {
             None
         }
diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs
index 82c91727293..f63102433c1 100644
--- a/src/librustc_privacy/lib.rs
+++ b/src/librustc_privacy/lib.rs
@@ -433,7 +433,7 @@ impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
         if !def.is_enum() && !field.vis.is_accessible_from(self.current_item, self.tcx) {
             struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
                              field.name, def.variant_descr(), self.tcx.item_path_str(def.did))
-                .span_label(span, &format!("field `{}` is private", field.name))
+                .span_label(span, format!("field `{}` is private", field.name))
                 .emit();
         }
     }
@@ -926,7 +926,7 @@ impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'
                     if self.has_pub_restricted || self.has_old_errors {
                         let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
                             "private type `{}` in public interface", ty);
-                        err.span_label(self.span, &format!("can't leak private type"));
+                        err.span_label(self.span, "can't leak private type");
                         err.emit();
                     } else {
                         self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
@@ -961,7 +961,7 @@ impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'
                 if self.has_pub_restricted || self.has_old_errors {
                     struct_span_err!(self.tcx.sess, self.span, E0445,
                                      "private trait `{}` in public interface", trait_ref)
-                        .span_label(self.span, &format!(
+                        .span_label(self.span, format!(
                                     "private trait can't be public"))
                         .emit();
                 } else {
diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs
index a4e9a8be49f..ac556270886 100644
--- a/src/librustc_resolve/lib.rs
+++ b/src/librustc_resolve/lib.rs
@@ -183,7 +183,7 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                                            E0401,
                                            "can't use type parameters from outer function; \
                                            try using a local type parameter instead");
-            err.span_label(span, &format!("use of type variable from outer function"));
+            err.span_label(span, "use of type variable from outer function");
             err
         }
         ResolutionError::OuterTypeParameterContext => {
@@ -199,8 +199,8 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                                             "the name `{}` is already used for a type parameter \
                                             in this type parameter list",
                                             name);
-             err.span_label(span, &format!("already used"));
-             err.span_label(first_use_span.clone(), &format!("first use of `{}`", name));
+             err.span_label(span, "already used");
+             err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
              err
         }
         ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
@@ -210,7 +210,7 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                                            "method `{}` is not a member of trait `{}`",
                                            method,
                                            trait_);
-            err.span_label(span, &format!("not a member of trait `{}`", trait_));
+            err.span_label(span, format!("not a member of trait `{}`", trait_));
             err
         }
         ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
@@ -220,7 +220,7 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                              "type `{}` is not a member of trait `{}`",
                              type_,
                              trait_);
-            err.span_label(span, &format!("not a member of trait `{}`", trait_));
+            err.span_label(span, format!("not a member of trait `{}`", trait_));
             err
         }
         ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
@@ -230,7 +230,7 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                              "const `{}` is not a member of trait `{}`",
                              const_,
                              trait_);
-            err.span_label(span, &format!("not a member of trait `{}`", trait_));
+            err.span_label(span, format!("not a member of trait `{}`", trait_));
             err
         }
         ResolutionError::VariableNotBoundInPattern(binding_error) => {
@@ -239,11 +239,11 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
             let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
             let mut err = resolver.session.struct_span_err_with_code(msp, &msg, "E0408");
             for sp in target_sp {
-                err.span_label(sp, &format!("pattern doesn't bind `{}`", binding_error.name));
+                err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
             }
             let origin_sp = binding_error.origin.iter().map(|x| *x).collect::<Vec<_>>();
             for sp in origin_sp {
-                err.span_label(sp, &"variable not in all patterns");
+                err.span_label(sp, "variable not in all patterns");
             }
             err
         }
@@ -255,8 +255,8 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                              "variable `{}` is bound in inconsistent \
                              ways within the same match arm",
                              variable_name);
-            err.span_label(span, &format!("bound in different ways"));
-            err.span_label(first_binding_span, &format!("first binding"));
+            err.span_label(span, "bound in different ways");
+            err.span_label(first_binding_span, "first binding");
             err
         }
         ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
@@ -265,7 +265,7 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                              E0415,
                              "identifier `{}` is bound more than once in this parameter list",
                              identifier);
-            err.span_label(span, &format!("used as parameter more than once"));
+            err.span_label(span, "used as parameter more than once");
             err
         }
         ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
@@ -274,7 +274,7 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                              E0416,
                              "identifier `{}` is bound more than once in the same pattern",
                              identifier);
-            err.span_label(span, &format!("used in a pattern more than once"));
+            err.span_label(span, "used in a pattern more than once");
             err
         }
         ResolutionError::UndeclaredLabel(name) => {
@@ -283,7 +283,7 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                                            E0426,
                                            "use of undeclared label `{}`",
                                            name);
-            err.span_label(span, &format!("undeclared label `{}`",&name));
+            err.span_label(span, format!("undeclared label `{}`", name));
             err
         }
         ResolutionError::SelfImportsOnlyAllowedWithin => {
@@ -313,14 +313,14 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
             };
             let mut err = struct_span_err!(resolver.session, span, E0432, "{}", msg);
             if let Some((_, p)) = name {
-                err.span_label(span, &p);
+                err.span_label(span, p);
             }
             err
         }
         ResolutionError::FailedToResolve(msg) => {
             let mut err = struct_span_err!(resolver.session, span, E0433,
                                            "failed to resolve. {}", msg);
-            err.span_label(span, &msg);
+            err.span_label(span, msg);
             err
         }
         ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
@@ -336,7 +336,7 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                              span,
                              E0435,
                              "attempt to use a non-constant value in a constant");
-            err.span_label(span, &format!("non-constant used with constant"));
+            err.span_label(span, "non-constant used with constant");
             err
         }
         ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
@@ -345,9 +345,9 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                                            span,
                                            E0530,
                                            "{}s cannot shadow {}s", what_binding, shadows_what);
-            err.span_label(span, &format!("cannot be named the same as a {}", shadows_what));
+            err.span_label(span, format!("cannot be named the same as a {}", shadows_what));
             let participle = if binding.is_import() { "imported" } else { "defined" };
-            let msg = &format!("a {} `{}` is {} here", shadows_what, name, participle);
+            let msg = format!("a {} `{}` is {} here", shadows_what, name, participle);
             err.span_label(binding.span, msg);
             err
         }
@@ -355,7 +355,7 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
             let mut err = struct_span_err!(resolver.session, span, E0128,
                                            "type parameters with a default cannot use \
                                             forward declared identifiers");
-            err.span_label(span, &format!("defaulted type parameters \
+            err.span_label(span, format!("defaulted type parameters \
                                            cannot be forward declared"));
             err
         }
@@ -2256,13 +2256,13 @@ impl<'a> Resolver<'a> {
             if is_self_type(path, ns) {
                 __diagnostic_used!(E0411);
                 err.code("E0411".into());
-                err.span_label(span, &format!("`Self` is only available in traits and impls"));
+                err.span_label(span, "`Self` is only available in traits and impls");
                 return err;
             }
             if is_self_value(path, ns) {
                 __diagnostic_used!(E0424);
                 err.code("E0424".into());
-                err.span_label(span, &format!("`self` value is only available in \
+                err.span_label(span, format!("`self` value is only available in \
                                                methods with `self` parameter"));
                 return err;
             }
@@ -2294,18 +2294,18 @@ impl<'a> Resolver<'a> {
                     let self_is_available = this.self_value_is_available(path[0].ctxt);
                     match candidate {
                         AssocSuggestion::Field => {
-                            err.span_label(span, &format!("did you mean `self.{}`?", path_str));
+                            err.span_label(span, format!("did you mean `self.{}`?", path_str));
                             if !self_is_available {
-                                err.span_label(span, &format!("`self` value is only available in \
+                                err.span_label(span, format!("`self` value is only available in \
                                                                methods with `self` parameter"));
                             }
                         }
                         AssocSuggestion::MethodWithSelf if self_is_available => {
-                            err.span_label(span, &format!("did you mean `self.{}(...)`?",
+                            err.span_label(span, format!("did you mean `self.{}(...)`?",
                                                            path_str));
                         }
                         AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
-                            err.span_label(span, &format!("did you mean `Self::{}`?", path_str));
+                            err.span_label(span, format!("did you mean `Self::{}`?", path_str));
                         }
                     }
                     return err;
@@ -2316,7 +2316,7 @@ impl<'a> Resolver<'a> {
 
             // Try Levenshtein.
             if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected) {
-                err.span_label(ident_span, &format!("did you mean `{}`?", candidate));
+                err.span_label(ident_span, format!("did you mean `{}`?", candidate));
                 levenshtein_worked = true;
             }
 
@@ -2324,21 +2324,21 @@ impl<'a> Resolver<'a> {
             if let Some(def) = def {
                 match (def, source) {
                     (Def::Macro(..), _) => {
-                        err.span_label(span, &format!("did you mean `{}!(...)`?", path_str));
+                        err.span_label(span, format!("did you mean `{}!(...)`?", path_str));
                         return err;
                     }
                     (Def::TyAlias(..), PathSource::Trait) => {
-                        err.span_label(span, &format!("type aliases cannot be used for traits"));
+                        err.span_label(span, "type aliases cannot be used for traits");
                         return err;
                     }
                     (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
                         ExprKind::Field(_, ident) => {
-                            err.span_label(parent.span, &format!("did you mean `{}::{}`?",
+                            err.span_label(parent.span, format!("did you mean `{}::{}`?",
                                                                  path_str, ident.node));
                             return err;
                         }
                         ExprKind::MethodCall(ident, ..) => {
-                            err.span_label(parent.span, &format!("did you mean `{}::{}(...)`?",
+                            err.span_label(parent.span, format!("did you mean `{}::{}(...)`?",
                                                                  path_str, ident.node));
                             return err;
                         }
@@ -2349,12 +2349,12 @@ impl<'a> Resolver<'a> {
                             if let Some((ctor_def, ctor_vis))
                                     = this.struct_constructors.get(&def_id).cloned() {
                                 if is_expected(ctor_def) && !this.is_accessible(ctor_vis) {
-                                    err.span_label(span, &format!("constructor is not visible \
+                                    err.span_label(span, format!("constructor is not visible \
                                                                    here due to private fields"));
                                 }
                             }
                         }
-                        err.span_label(span, &format!("did you mean `{} {{ /* fields */ }}`?",
+                        err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
                                                        path_str));
                         return err;
                     }
@@ -2364,7 +2364,7 @@ impl<'a> Resolver<'a> {
 
             // Fallback label.
             if !levenshtein_worked {
-                err.span_label(base_span, &fallback_label);
+                err.span_label(base_span, fallback_label);
             }
             err
         };
@@ -3374,9 +3374,9 @@ impl<'a> Resolver<'a> {
             },
         };
 
-        err.span_label(span, &format!("`{}` already {}", name, participle));
+        err.span_label(span, format!("`{}` already {}", name, participle));
         if old_binding.span != syntax_pos::DUMMY_SP {
-            err.span_label(old_binding.span, &format!("previous {} of `{}` here", noun, name));
+            err.span_label(old_binding.span, format!("previous {} of `{}` here", noun, name));
         }
         err.emit();
         self.name_already_seen.insert(name, span);
diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs
index 030e3936de9..106f421f39e 100644
--- a/src/librustc_resolve/macros.rs
+++ b/src/librustc_resolve/macros.rs
@@ -630,7 +630,7 @@ impl<'a> Resolver<'a> {
                     err.help(&format!("did you mean `{}`?", suggestion));
                 }
             } else {
-                err.help(&format!("have you added the `#[macro_use]` on the module/import?"));
+                err.help("have you added the `#[macro_use]` on the module/import?");
             }
         }
     }
diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs
index 43654c8ce6f..804e1ea740f 100644
--- a/src/librustc_resolve/resolve_imports.rs
+++ b/src/librustc_resolve/resolve_imports.rs
@@ -539,7 +539,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
                 Ok(binding) if !binding.is_importable() => {
                     let msg = format!("`{}` is not directly importable", target);
                     struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
-                        .span_label(directive.span, &format!("cannot be imported directly"))
+                        .span_label(directive.span, "cannot be imported directly")
                         .emit();
                     // Do not import this illegal binding. Import a dummy binding and pretend
                     // everything is fine
@@ -701,7 +701,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
             } else if ns == TypeNS {
                 struct_span_err!(self.session, directive.span, E0365,
                                  "`{}` is private, and cannot be reexported", ident)
-                    .span_label(directive.span, &format!("reexport of private `{}`", ident))
+                    .span_label(directive.span, format!("reexport of private `{}`", ident))
                     .note(&format!("consider declaring type or module `{}` with `pub`", ident))
                     .emit();
             } else {
@@ -794,7 +794,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
                             let msg =
                                 format!("a macro named `{}` has already been exported", ident);
                             self.session.struct_span_err(span, &msg)
-                                .span_label(span, &format!("`{}` already exported", ident))
+                                .span_label(span, format!("`{}` already exported", ident))
                                 .span_note(binding.span, "previous macro export here")
                                 .emit();
                         }
diff --git a/src/librustc_save_analysis/Cargo.toml b/src/librustc_save_analysis/Cargo.toml
index 07a5c266fc0..6d04bff8282 100644
--- a/src/librustc_save_analysis/Cargo.toml
+++ b/src/librustc_save_analysis/Cargo.toml
@@ -11,9 +11,10 @@ crate-type = ["dylib"]
 [dependencies]
 log = "0.3"
 rustc = { path = "../librustc" }
+rustc_typeck = { path = "../librustc_typeck" }
 syntax = { path = "../libsyntax" }
 syntax_pos = { path = "../libsyntax_pos" }
-rls-data = "0.1"
-rls-span = "0.1"
+rls-data = "0.3"
+rls-span = "0.4"
 # FIXME(#40527) should move rustc serialize out of tree
 rustc-serialize = "0.3"
diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs
index 26780c48a13..763414c1a55 100644
--- a/src/librustc_save_analysis/dump_visitor.rs
+++ b/src/librustc_save_analysis/dump_visitor.rs
@@ -122,7 +122,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
             f(self);
             self.save_ctxt.tables = old_tables;
         } else {
-            f(self)
+            f(self);
         }
     }
 
diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs
index e2c399e85cd..fd6898d19d8 100644
--- a/src/librustc_save_analysis/lib.rs
+++ b/src/librustc_save_analysis/lib.rs
@@ -27,6 +27,7 @@
 #[macro_use] extern crate log;
 #[macro_use] extern crate syntax;
 extern crate rustc_serialize;
+extern crate rustc_typeck;
 extern crate syntax_pos;
 
 extern crate rls_data;
@@ -50,6 +51,7 @@ use rustc::hir::def_id::DefId;
 use rustc::session::config::CrateType::CrateTypeExecutable;
 use rustc::session::Session;
 use rustc::ty::{self, TyCtxt};
+use rustc_typeck::hir_ty_to_ty;
 
 use std::env;
 use std::fs::File;
@@ -606,11 +608,12 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
                 Def::Local(def_id)
             }
 
-            Node::NodeTy(&hir::Ty { node: hir::TyPath(ref qpath), .. }) => {
-                match *qpath {
-                    hir::QPath::Resolved(_, ref path) => path.def,
-                    hir::QPath::TypeRelative(..) => {
-                        if let Some(ty) = self.tcx.ast_ty_to_ty_cache.borrow().get(&id) {
+            Node::NodeTy(ty) => {
+                if let hir::Ty { node: hir::TyPath(ref qpath), .. } = *ty {
+                    match *qpath {
+                        hir::QPath::Resolved(_, ref path) => path.def,
+                        hir::QPath::TypeRelative(..) => {
+                            let ty = hir_ty_to_ty(self.tcx, ty);
                             if let ty::TyProjection(proj) = ty.sty {
                                 for item in self.tcx.associated_items(proj.trait_ref.def_id) {
                                     if item.kind == ty::AssociatedKind::Type {
@@ -620,9 +623,11 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
                                     }
                                 }
                             }
+                            Def::Err
                         }
-                        Def::Err
                     }
+                } else {
+                    Def::Err
                 }
             }
 
diff --git a/src/librustc_trans/base.rs b/src/librustc_trans/base.rs
index 56ff5ebb069..8689e176f7a 100644
--- a/src/librustc_trans/base.rs
+++ b/src/librustc_trans/base.rs
@@ -754,10 +754,7 @@ fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
     }).max().unwrap();
 
     if kind == MetadataKind::None {
-        return (metadata_llcx, metadata_llmod, EncodedMetadata {
-            raw_data: vec![],
-            hashes: vec![],
-        });
+        return (metadata_llcx, metadata_llmod, EncodedMetadata::new());
     }
 
     let cstore = &tcx.sess.cstore;
diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs
index c89e3ca8b68..adcb3d682ca 100644
--- a/src/librustc_typeck/astconv.rs
+++ b/src/librustc_typeck/astconv.rs
@@ -25,9 +25,8 @@ use rustc::ty::wf::object_region_bounds;
 use rustc_back::slice;
 use require_c_abi_if_variadic;
 use util::common::{ErrorReported, FN_OUTPUT_NAME};
-use util::nodemap::{NodeMap, FxHashSet};
+use util::nodemap::FxHashSet;
 
-use std::cell::RefCell;
 use std::iter;
 use syntax::{abi, ast};
 use syntax::feature_gate::{GateIssue, emit_feature_err};
@@ -37,9 +36,6 @@ use syntax_pos::Span;
 pub trait AstConv<'gcx, 'tcx> {
     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
 
-    /// A cache used for the result of `ast_ty_to_ty_cache`
-    fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
-
     /// Returns the set of bounds in scope for the type parameter with
     /// the given id.
     fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
@@ -167,7 +163,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
             hir::ParenthesizedParameters(..) => {
                 struct_span_err!(tcx.sess, span, E0214,
                           "parenthesized parameters may only be used with a trait")
-                    .span_label(span, &format!("only traits may use parentheses"))
+                    .span_label(span, "only traits may use parentheses")
                     .emit();
 
                 return Substs::for_item(tcx, def_id, |_, _| {
@@ -298,7 +294,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
                     struct_span_err!(tcx.sess, span, E0393,
                                      "the type parameter `{}` must be explicitly specified",
                                      def.name)
-                        .span_label(span, &format!("missing reference to `{}`", def.name))
+                        .span_label(span, format!("missing reference to `{}`", def.name))
                         .note(&format!("because of the default `Self` reference, \
                                         type parameters must be specified on object types"))
                         .emit();
@@ -639,7 +635,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
             let span = b.trait_ref.path.span;
             struct_span_err!(self.tcx().sess, span, E0225,
                 "only Send/Sync traits can be used as additional traits in a trait object")
-                .span_label(span, &format!("non-Send/Sync additional trait"))
+                .span_label(span, "non-Send/Sync additional trait")
                 .emit();
         }
 
@@ -688,7 +684,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
                 "the value of the associated type `{}` (from the trait `{}`) must be specified",
                         name,
                         tcx.item_path_str(trait_def_id))
-                        .span_label(span, &format!(
+                        .span_label(span, format!(
                             "missing associated type `{}` value", name))
                         .emit();
         }
@@ -734,7 +730,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
                                         trait_str: &str,
                                         name: &str) {
         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
-            .span_label(span, &format!("ambiguous associated type"))
+            .span_label(span, "ambiguous associated type")
             .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
                   type_str, trait_str, name))
             .emit();
@@ -788,7 +784,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
                           "associated type `{}` not found for `{}`",
                           assoc_name,
                           ty_param_name)
-                  .span_label(span, &format!("associated type `{}` not found", assoc_name))
+                  .span_label(span, format!("associated type `{}` not found", assoc_name))
                   .emit();
                 return Err(ErrorReported);
             }
@@ -801,7 +797,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
                 "ambiguous associated type `{}` in bounds of `{}`",
                 assoc_name,
                 ty_param_name);
-            err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
+            err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
 
             for bound in bounds {
                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
@@ -810,7 +806,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
                 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
 
                 if let Some(span) = bound_span {
-                    err.span_label(span, &format!("ambiguous `{}` from `{}`",
+                    err.span_label(span, format!("ambiguous `{}` from `{}`",
                                                   assoc_name,
                                                   bound));
                 } else {
@@ -955,7 +951,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
             for typ in segment.parameters.types() {
                 struct_span_err!(self.tcx().sess, typ.span, E0109,
                                  "type parameters are not allowed on this type")
-                    .span_label(typ.span, &format!("type parameter not allowed"))
+                    .span_label(typ.span, "type parameter not allowed")
                     .emit();
                 break;
             }
@@ -963,7 +959,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
                 struct_span_err!(self.tcx().sess, lifetime.span, E0110,
                                  "lifetime parameters are not allowed on this type")
                     .span_label(lifetime.span,
-                                &format!("lifetime parameter not allowed on this type"))
+                                "lifetime parameter not allowed on this type")
                     .emit();
                 break;
             }
@@ -977,7 +973,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
     pub fn prohibit_projection(&self, span: Span) {
         let mut err = struct_span_err!(self.tcx().sess, span, E0229,
                                        "associated type bindings are not allowed here");
-        err.span_label(span, &format!("associate type not allowed here")).emit();
+        err.span_label(span, "associate type not allowed here").emit();
     }
 
     // Check a type Path and convert it to a Ty.
@@ -1074,11 +1070,6 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
 
         let tcx = self.tcx();
 
-        let cache = self.ast_ty_to_ty_cache();
-        if let Some(ty) = cache.borrow().get(&ast_ty.id) {
-            return ty;
-        }
-
         let result_ty = match ast_ty.node {
             hir::TySlice(ref ty) => {
                 tcx.mk_slice(self.ast_ty_to_ty(&ty))
@@ -1223,7 +1214,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
             hir::TyTypeof(ref _e) => {
                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
                                  "`typeof` is a reserved keyword but unimplemented")
-                    .span_label(ast_ty.span, &format!("reserved keyword"))
+                    .span_label(ast_ty.span, "reserved keyword")
                     .emit();
 
                 tcx.types.err
@@ -1240,8 +1231,6 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
             }
         };
 
-        cache.borrow_mut().insert(ast_ty.id, result_ty);
-
         result_ty
     }
 
@@ -1437,7 +1426,7 @@ fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
                 "wrong number of type arguments: {} {}, found {}",
                 expected, required, supplied)
             .span_label(span,
-                &format!("{} {} type argument{}",
+                format!("{} {} type argument{}",
                     expected,
                     required,
                     arguments_plural))
@@ -1455,7 +1444,7 @@ fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
                 expected, supplied)
             .span_label(
                 span,
-                &format!("{} type argument{}",
+                format!("{} type argument{}",
                     if accepted == 0 { "expected no" } else { &expected },
                     arguments_plural)
             )
@@ -1481,7 +1470,7 @@ fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected
     struct_span_err!(tcx.sess, span, E0107,
                      "wrong number of lifetime parameters: expected {}, found {}",
                      expected, number)
-        .span_label(span, &label)
+        .span_label(span, label)
         .emit();
 }
 
diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs
index ac10dfd36e2..bbe34f37950 100644
--- a/src/librustc_typeck/check/_match.rs
+++ b/src/librustc_typeck/check/_match.rs
@@ -97,7 +97,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
 
                     struct_span_err!(tcx.sess, span, E0029,
                         "only char and numeric types are allowed in range patterns")
-                        .span_label(span, &format!("ranges require char or numeric types"))
+                        .span_label(span, "ranges require char or numeric types")
                         .note(&format!("start type: {}", self.ty_to_string(lhs_ty)))
                         .note(&format!("end type: {}", self.ty_to_string(rhs_ty)))
                         .emit();
@@ -263,7 +263,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                                     tcx.sess, pat.span, E0527,
                                     "pattern requires {} elements but array has {}",
                                     min_len, size)
-                                    .span_label(pat.span, &format!("expected {} elements",size))
+                                    .span_label(pat.span, format!("expected {} elements",size))
                                     .emit();
                             }
                             (inner_ty, tcx.types.err)
@@ -274,7 +274,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                                     "pattern requires at least {} elements but array has {}",
                                     min_len, size)
                                 .span_label(pat.span,
-                                    &format!("pattern cannot match array of {} elements", size))
+                                    format!("pattern cannot match array of {} elements", size))
                                 .emit();
                             (inner_ty, tcx.types.err)
                         }
@@ -297,7 +297,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                             }
 
                             err.span_label( pat.span,
-                                &format!("pattern cannot match with input type `{}`", expected_ty)
+                                format!("pattern cannot match with input type `{}`", expected_ty)
                             ).emit();
                         }
                         (tcx.types.err, tcx.types.err)
@@ -379,7 +379,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                     let type_str = self.ty_to_string(expected);
                     struct_span_err!(self.tcx.sess, span, E0033,
                               "type `{}` cannot be dereferenced", type_str)
-                        .span_label(span, &format!("type `{}` cannot be dereferenced", type_str))
+                        .span_label(span, format!("type `{}` cannot be dereferenced", type_str))
                         .emit();
                     return false
                 }
@@ -593,7 +593,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                               def.kind_name(),
                               hir::print::to_string(&tcx.hir, |s| s.print_qpath(qpath, false)));
             struct_span_err!(tcx.sess, pat.span, E0164, "{}", msg)
-                .span_label(pat.span, &format!("not a tuple variant or struct")).emit();
+                .span_label(pat.span, "not a tuple variant or struct").emit();
             on_error();
         };
 
@@ -642,7 +642,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                              "this pattern has {} field{}, but the corresponding {} has {} field{}",
                              subpats.len(), subpats_ending, def.kind_name(),
                              variant.fields.len(),  fields_ending)
-                .span_label(pat.span, &format!("expected {} field{}, found {}",
+                .span_label(pat.span, format!("expected {} field{}, found {}",
                                                variant.fields.len(), fields_ending, subpats.len()))
                 .emit();
             on_error();
@@ -683,8 +683,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                                       in the pattern",
                                      field.name)
                         .span_label(span,
-                                    &format!("multiple uses of `{}` in pattern", field.name))
-                        .span_label(*occupied.get(), &format!("first use of `{}`", field.name))
+                                    format!("multiple uses of `{}` in pattern", field.name))
+                        .span_label(*occupied.get(), format!("first use of `{}`", field.name))
                         .emit();
                     tcx.types.err
                 }
@@ -703,7 +703,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                                              tcx.item_path_str(variant.did),
                                              field.name)
                                 .span_label(span,
-                                            &format!("{} `{}` does not have field `{}`",
+                                            format!("{} `{}` does not have field `{}`",
                                                      kind_name,
                                                      tcx.item_path_str(variant.did),
                                                      field.name))
@@ -732,7 +732,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                 struct_span_err!(tcx.sess, span, E0027,
                                 "pattern does not mention field `{}`",
                                 field.name)
-                                .span_label(span, &format!("missing field `{}`", field.name))
+                                .span_label(span, format!("missing field `{}`", field.name))
                                 .emit();
             }
         }
diff --git a/src/librustc_typeck/check/autoderef.rs b/src/librustc_typeck/check/autoderef.rs
index c9584f1d9e1..f03451c04ed 100644
--- a/src/librustc_typeck/check/autoderef.rs
+++ b/src/librustc_typeck/check/autoderef.rs
@@ -62,7 +62,7 @@ impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> {
                              E0055,
                              "reached the recursion limit while auto-dereferencing {:?}",
                              self.cur_ty)
-                .span_label(self.span, &format!("deref recursion limit reached"))
+                .span_label(self.span, "deref recursion limit reached")
                 .help(&format!(
                         "consider adding a `#[recursion_limit=\"{}\"]` attribute to your crate",
                         suggested_limit))
diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs
index 7a49309e005..dde5f598a68 100644
--- a/src/librustc_typeck/check/callee.rs
+++ b/src/librustc_typeck/check/callee.rs
@@ -27,7 +27,7 @@ use rustc::hir;
 pub fn check_legal_trait_for_method_call(tcx: TyCtxt, span: Span, trait_id: DefId) {
     if tcx.lang_items.drop_trait() == Some(trait_id) {
         struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method")
-            .span_label(span, &format!("explicit destructor calls not allowed"))
+            .span_label(span, "explicit destructor calls not allowed")
             .emit();
     }
 }
diff --git a/src/librustc_typeck/check/cast.rs b/src/librustc_typeck/check/cast.rs
index 32b363ed755..72ce7d3b5ed 100644
--- a/src/librustc_typeck/check/cast.rs
+++ b/src/librustc_typeck/check/cast.rs
@@ -155,7 +155,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
                                        },
                                        self.expr_ty);
                 err.span_label(error_span,
-                               &format!("cannot cast `{}` as `{}`",
+                               format!("cannot cast `{}` as `{}`",
                                         fcx.ty_to_string(self.expr_ty),
                                         cast_ty));
                 if let Ok(snippet) = fcx.sess().codemap().span_to_snippet(self.expr.span) {
@@ -200,7 +200,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
             }
             CastError::CastToBool => {
                 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`")
-                    .span_label(self.span, &format!("unsupported cast"))
+                    .span_label(self.span, "unsupported cast")
                     .help("compare with zero instead")
                     .emit();
             }
diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs
index 45b0a571bd0..fb3be849319 100644
--- a/src/librustc_typeck/check/closure.rs
+++ b/src/librustc_typeck/check/closure.rs
@@ -126,6 +126,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                 (sig, kind)
             }
             ty::TyInfer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
+            ty::TyFnPtr(sig) => (Some(sig.skip_binder().clone()), Some(ty::ClosureKind::Fn)),
             _ => (None, None),
         }
     }
diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs
index 61d04876bfe..c228fc6b24a 100644
--- a/src/librustc_typeck/check/coercion.rs
+++ b/src/librustc_typeck/check/coercion.rs
@@ -965,10 +965,6 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E>
         }
     }
 
-    pub fn is_empty(&self) -> bool {
-        self.pushed == 0
-    }
-
     /// Return the "expected type" with which this coercion was
     /// constructed.  This represents the "downward propagated" type
     /// that was given to us at the start of typing whatever construct
@@ -1148,7 +1144,7 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E>
                         db = struct_span_err!(
                             fcx.tcx.sess, cause.span, E0069,
                             "`return;` in a function whose return type is not `()`");
-                        db.span_label(cause.span, &format!("return type is not ()"));
+                        db.span_label(cause.span, "return type is not ()");
                     }
                     _ => {
                         db = fcx.report_mismatched_types(cause, expected, found, err);
diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs
index 9ed5528e867..0579bb15fd6 100644
--- a/src/librustc_typeck/check/compare_method.rs
+++ b/src/librustc_typeck/check/compare_method.rs
@@ -402,7 +402,7 @@ fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                          "lifetime parameters or bounds on method `{}` do not match the \
                           trait declaration",
                          impl_m.name)
-            .span_label(span, &format!("lifetimes do not match trait"))
+            .span_label(span, "lifetimes do not match trait")
             .emit();
         return Err(ErrorReported);
     }
@@ -534,9 +534,9 @@ fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                             not in the trait",
                                            trait_m.name,
                                            self_descr);
-            err.span_label(impl_m_span, &format!("`{}` used in impl", self_descr));
+            err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
-                err.span_label(span, &format!("trait declared without `{}`", self_descr));
+                err.span_label(span, format!("trait declared without `{}`", self_descr));
             }
             err.emit();
             return Err(ErrorReported);
@@ -552,9 +552,9 @@ fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                            trait_m.name,
                                            self_descr);
             err.span_label(impl_m_span,
-                           &format!("expected `{}` in impl", self_descr));
+                           format!("expected `{}` in impl", self_descr));
             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
-                err.span_label(span, &format!("`{}` used in trait", self_descr));
+                err.span_label(span, format!("`{}` used in trait", self_descr));
             }
             err.emit();
             return Err(ErrorReported);
@@ -606,7 +606,7 @@ fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
 
         if let Some(span) = trait_item_span {
             err.span_label(span,
-                           &format!("expected {}",
+                           format!("expected {}",
                                     &if num_trait_m_type_params != 1 {
                                         format!("{} type parameters", num_trait_m_type_params)
                                     } else {
@@ -617,7 +617,7 @@ fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
         }
 
         err.span_label(span,
-                       &format!("found {}{}",
+                       format!("found {}{}",
                                 &if num_impl_m_type_params != 1 {
                                     format!("{} type parameters", num_impl_m_type_params)
                                 } else {
@@ -696,7 +696,7 @@ fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                        trait_number_args);
         if let Some(trait_span) = trait_span {
             err.span_label(trait_span,
-                           &format!("trait requires {}",
+                           format!("trait requires {}",
                                     &if trait_number_args != 1 {
                                         format!("{} parameters", trait_number_args)
                                     } else {
@@ -704,7 +704,7 @@ fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                     }));
         }
         err.span_label(impl_span,
-                       &format!("expected {}, found {}",
+                       format!("expected {}, found {}",
                                 &if trait_number_args != 1 {
                                     format!("{} parameters", trait_number_args)
                                 } else {
diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs
index 2a97bc1d98f..60067e6a6ec 100644
--- a/src/librustc_typeck/check/intrinsic.rs
+++ b/src/librustc_typeck/check/intrinsic.rs
@@ -57,7 +57,7 @@ fn equate_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                         "intrinsic has wrong number of type \
                         parameters: found {}, expected {}",
                         i_n_tps, n_tps)
-            .span_label(span, &format!("expected {} type parameter", n_tps))
+            .span_label(span, format!("expected {} type parameter", n_tps))
             .emit();
     } else {
         require_same_types(tcx,
@@ -101,7 +101,7 @@ pub fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             op => {
                 struct_span_err!(tcx.sess, it.span, E0092,
                       "unrecognized atomic operation function: `{}`", op)
-                  .span_label(it.span, &format!("unrecognized atomic operation"))
+                  .span_label(it.span, "unrecognized atomic operation")
                   .emit();
                 return;
             }
@@ -305,7 +305,7 @@ pub fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                 struct_span_err!(tcx.sess, it.span, E0093,
                                 "unrecognized intrinsic function: `{}`",
                                 *other)
-                                .span_label(it.span, &format!("unrecognized intrinsic"))
+                                .span_label(it.span, "unrecognized intrinsic")
                                 .emit();
                 return;
             }
@@ -505,7 +505,7 @@ fn match_intrinsic_type_to_type<'a, 'tcx>(
                     }
                 }
                 _ => simple_error(&format!("`{}`", t),
-                                  &format!("tuple")),
+                                  "tuple"),
             }
         }
     }
diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs
index aad14bc975d..a9e82a0601f 100644
--- a/src/librustc_typeck/check/method/confirm.rs
+++ b/src/librustc_typeck/check/method/confirm.rs
@@ -285,7 +285,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> {
                                  self.span,
                                  E0035,
                                  "does not take type parameters")
-                    .span_label(self.span, &"called with unneeded type parameters")
+                    .span_label(self.span, "called with unneeded type parameters")
                     .emit();
             } else {
                 struct_span_err!(self.tcx.sess,
@@ -296,7 +296,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> {
                                  num_method_types,
                                  num_supplied_types)
                     .span_label(self.span,
-                                &format!("Passed {} type argument{}, expected {}",
+                                format!("Passed {} type argument{}, expected {}",
                                          num_supplied_types,
                                          if num_supplied_types != 1 { "s" } else { "" },
                                          num_method_types))
@@ -433,22 +433,11 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> {
         for (i, &expr) in exprs.iter().rev().enumerate() {
             debug!("convert_lvalue_derefs_to_mutable: i={} expr={:?}", i, expr);
 
-            // Fix up the adjustment.
-            let autoderefs = match self.tables.borrow_mut().adjustments.get_mut(&expr.id) {
-                Some(&mut Adjustment {
-                    kind: Adjust::DerefRef { autoderefs, ref mut autoref, .. }, ref mut target
-                }) => {
-                    if let &mut Some(AutoBorrow::Ref(_, ref mut mutbl)) = autoref {
-                        *mutbl = hir::Mutability::MutMutable;
-                        *target = match target.sty {
-                            ty::TyRef(r, ty::TypeAndMut { ty, .. }) =>
-                                self.tcx.mk_ref(r, ty::TypeAndMut { ty, mutbl: *mutbl }),
-                            _ => span_bug!(expr.span, "AutoBorrow::Ref resulted in non-ref {:?}",
-                                           target)
-                        };
-                    }
-                    autoderefs
-                }
+            // Fix up the autoderefs. Autorefs can only occur immediately preceding
+            // overloaded lvalue ops, and will be fixed by them in order to get
+            // the correct region.
+            let autoderefs = match self.tables.borrow().adjustments.get(&expr.id) {
+                Some(&Adjustment { kind: Adjust::DerefRef { autoderefs, .. }, .. }) => autoderefs,
                 Some(_) | None => 0
             };
 
@@ -502,10 +491,35 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> {
 
         let method = self.try_overloaded_lvalue_op(
             expr.span, None, base_ty, arg_tys, PreferMutLvalue, op);
-        let ok = method.expect("re-trying op failed");
+        let ok = match method {
+            Some(method) => method,
+            None => return self.tcx.sess.delay_span_bug(expr.span, "re-trying op failed")
+        };
         let method = self.register_infer_ok_obligations(ok);
         debug!("convert_lvalue_op_to_mutable: method={:?}", method);
         self.tables.borrow_mut().method_map.insert(method_call, method);
+
+        // Convert the autoref in the base expr to mutable with the correct
+        // region and mutability.
+        if let Some(&mut Adjustment {
+            ref mut target, kind: Adjust::DerefRef {
+                autoref: Some(AutoBorrow::Ref(ref mut r, ref mut mutbl)), ..
+            }
+        }) = self.tables.borrow_mut().adjustments.get_mut(&base_expr.id) {
+            debug!("convert_lvalue_op_to_mutable: converting autoref of {:?}", target);
+
+            // extract method return type, which will be &mut T;
+            // all LB regions should have been instantiated during method lookup
+            let method_sig = self.tcx.no_late_bound_regions(&method.ty.fn_sig()).unwrap();
+
+            *target = method_sig.inputs()[0];
+            if let ty::TyRef(r_, mt) = target.sty {
+                *r = r_;
+                *mutbl = mt.mutbl;
+            } else {
+                span_bug!(expr.span, "input to lvalue op is not a ref?");
+            }
+        }
     }
 
     ///////////////////////////////////////////////////////////////////////////
diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs
index 4b975d7b324..c7ec379b0de 100644
--- a/src/librustc_typeck/check/method/suggest.rs
+++ b/src/librustc_typeck/check/method/suggest.rs
@@ -209,9 +209,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                                                               expr_string,
                                                               item_name));
                                         }
-                                        err.span_label(span, &"field, not a method");
+                                        err.span_label(span, "field, not a method");
                                     } else {
-                                        err.span_label(span, &"private field, not a method");
+                                        err.span_label(span, "private field, not a method");
                                     }
                                     break;
                                 }
@@ -272,7 +272,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                                                span,
                                                E0034,
                                                "multiple applicable items in scope");
-                err.span_label(span, &format!("multiple `{}` found", item_name));
+                err.span_label(span, format!("multiple `{}` found", item_name));
 
                 report_candidates(&mut err, sources);
                 err.emit();
diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs
index 11095e70f62..127ffc60cf4 100644
--- a/src/librustc_typeck/check/mod.rs
+++ b/src/librustc_typeck/check/mod.rs
@@ -451,8 +451,6 @@ impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> {
 }
 
 pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
-    ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
-
     body_id: ast::NodeId,
 
     // Number of errors that had been reported when we started
@@ -1132,7 +1130,7 @@ fn check_on_unimplemented<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             struct_span_err!(
                 tcx.sess, attr.span, E0232,
                 "this attribute must have a value")
-                .span_label(attr.span, &format!("attribute requires a value"))
+                .span_label(attr.span, "attribute requires a value")
                 .note(&format!("eg `#[rustc_on_unimplemented = \"foo\"]`"))
                 .emit();
         }
@@ -1148,12 +1146,12 @@ fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
         "`{}` specializes an item from a parent `impl`, but \
          that item is not marked `default`",
         impl_item.name);
-    err.span_label(impl_item.span, &format!("cannot specialize default item `{}`",
+    err.span_label(impl_item.span, format!("cannot specialize default item `{}`",
                                             impl_item.name));
 
     match tcx.span_of_impl(parent_impl) {
         Ok(span) => {
-            err.span_label(span, &"parent `impl` is here");
+            err.span_label(span, "parent `impl` is here");
             err.note(&format!("to specialize, `{}` in the parent `impl` must be marked `default`",
                               impl_item.name));
         }
@@ -1228,11 +1226,11 @@ fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                   which doesn't match its trait `{}`",
                                   ty_impl_item.name,
                                   impl_trait_ref);
-                         err.span_label(impl_item.span, &format!("does not match trait"));
+                         err.span_label(impl_item.span, "does not match trait");
                          // We can only get the spans from local trait definition
                          // Same for E0324 and E0325
                          if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
-                            err.span_label(trait_span, &format!("item in trait"));
+                            err.span_label(trait_span, "item in trait");
                          }
                          err.emit()
                     }
@@ -1264,9 +1262,9 @@ fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                   which doesn't match its trait `{}`",
                                   ty_impl_item.name,
                                   impl_trait_ref);
-                         err.span_label(impl_item.span, &format!("does not match trait"));
+                         err.span_label(impl_item.span, "does not match trait");
                          if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
-                            err.span_label(trait_span, &format!("item in trait"));
+                            err.span_label(trait_span, "item in trait");
                          }
                          err.emit()
                     }
@@ -1282,9 +1280,9 @@ fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                   which doesn't match its trait `{}`",
                                   ty_impl_item.name,
                                   impl_trait_ref);
-                         err.span_label(impl_item.span, &format!("does not match trait"));
+                         err.span_label(impl_item.span, "does not match trait");
                          if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
-                            err.span_label(trait_span, &format!("item in trait"));
+                            err.span_label(trait_span, "item in trait");
                          }
                          err.emit()
                     }
@@ -1333,13 +1331,13 @@ fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             missing_items.iter()
                   .map(|trait_item| trait_item.name.to_string())
                   .collect::<Vec<_>>().join("`, `"));
-        err.span_label(impl_span, &format!("missing `{}` in implementation",
+        err.span_label(impl_span, format!("missing `{}` in implementation",
                 missing_items.iter()
                     .map(|trait_item| trait_item.name.to_string())
                     .collect::<Vec<_>>().join("`, `")));
         for trait_item in missing_items {
             if let Some(span) = tcx.hir.span_if_local(trait_item.def_id) {
-                err.span_label(span, &format!("`{}` from trait", trait_item.name));
+                err.span_label(span, format!("`{}` from trait", trait_item.name));
             } else {
                 err.note(&format!("`{}` from trait: `{}`",
                                   trait_item.name,
@@ -1376,8 +1374,12 @@ fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
     // contain themselves. For case 2, there must be an inner type that will be
     // caught by case 1.
     match rty.is_representable(tcx, sp) {
-        Representability::SelfRecursive => {
-            tcx.recursive_type_with_infinite_size_error(item_def_id).emit();
+        Representability::SelfRecursive(spans) => {
+            let mut err = tcx.recursive_type_with_infinite_size_error(item_def_id);
+            for span in spans {
+                err.span_label(span, "recursive without indirection");
+            }
+            err.emit();
             return false
         }
         Representability::Representable | Representability::ContainsRecursive => (),
@@ -1397,7 +1399,7 @@ pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId
             let e = fields[0].ty(tcx, substs);
             if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
                 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
-                                .span_label(sp, &format!("SIMD elements must have the same type"))
+                                .span_label(sp, "SIMD elements must have the same type")
                                 .emit();
                 return;
             }
@@ -1469,7 +1471,7 @@ pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
         struct_span_err!(
             tcx.sess, sp, E0084,
             "unsupported representation for zero-variant enum")
-            .span_label(sp, &format!("unsupported enum representation"))
+            .span_label(sp, "unsupported enum representation")
             .emit();
     }
 
@@ -1503,8 +1505,8 @@ pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             };
             struct_span_err!(tcx.sess, span, E0081,
                              "discriminant value `{}` already exists", disr_vals[i])
-                .span_label(i_span, &format!("first use of `{}`", disr_vals[i]))
-                .span_label(span , &format!("enum already has `{}`", disr_vals[i]))
+                .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
+                .span_label(span , format!("enum already has `{}`", disr_vals[i]))
                 .emit();
         }
         disr_vals.push(discr);
@@ -1516,10 +1518,6 @@ pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
 impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
 
-    fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>> {
-        &self.ast_ty_to_ty_cache
-    }
-
     fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
         Some(&self.parameter_environment.free_substs)
     }
@@ -1621,7 +1619,6 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                body_id: ast::NodeId)
                -> FnCtxt<'a, 'gcx, 'tcx> {
         FnCtxt {
-            ast_ty_to_ty_cache: RefCell::new(NodeMap()),
             body_id: body_id,
             err_count_on_creation: inh.tcx.sess.err_count(),
             ret_coercion: None,
@@ -2404,12 +2401,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                     if arg_count == 1 {" was"} else {"s were"}),
                 error_code);
 
-            err.span_label(sp, &format!("expected {}{} parameter{}",
+            err.span_label(sp, format!("expected {}{} parameter{}",
                                         if variadic {"at least "} else {""},
                                         expected_count,
                                         if expected_count == 1 {""} else {"s"}));
             if let Some(def_s) = def_span {
-                err.span_label(def_s, &format!("defined here"));
+                err.span_label(def_s, "defined here");
             }
             err.emit();
         }
@@ -2941,10 +2938,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                     if let Some(suggested_field_name) =
                         Self::suggest_field_name(def.struct_variant(), field, vec![]) {
                             err.span_label(field.span,
-                                           &format!("did you mean `{}`?", suggested_field_name));
+                                           format!("did you mean `{}`?", suggested_field_name));
                         } else {
                             err.span_label(field.span,
-                                           &format!("unknown field"));
+                                           "unknown field");
                         };
                 }
                 ty::TyRawPtr(..) => {
@@ -3079,15 +3076,15 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                                                            &field.name,
                                                            skip_fields.collect()) {
             err.span_label(field.name.span,
-                           &format!("field does not exist - did you mean `{}`?", field_name));
+                           format!("field does not exist - did you mean `{}`?", field_name));
         } else {
             match ty.sty {
                 ty::TyAdt(adt, ..) if adt.is_enum() => {
-                    err.span_label(field.name.span, &format!("`{}::{}` does not have this field",
+                    err.span_label(field.name.span, format!("`{}::{}` does not have this field",
                                                              ty, variant.name));
                 }
                 _ => {
-                    err.span_label(field.name.span, &format!("`{}` does not have this field", ty));
+                    err.span_label(field.name.span, format!("`{}` does not have this field", ty));
                 }
             }
         };
@@ -3152,10 +3149,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                                                 "field `{}` specified more than once",
                                                 field.name.node);
 
-                    err.span_label(field.name.span, &format!("used more than once"));
+                    err.span_label(field.name.span, "used more than once");
 
                     if let Some(prev_span) = seen_fields.get(&field.name.node) {
-                        err.span_label(*prev_span, &format!("first use of `{}`", field.name.node));
+                        err.span_label(*prev_span, format!("first use of `{}`", field.name.node));
                     }
 
                     err.emit();
@@ -3202,7 +3199,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                         remaining_fields_names,
                         truncated_fields_error,
                         adt_ty)
-                        .span_label(span, &format!("missing {}{}",
+                        .span_label(span, format!("missing {}{}",
                             remaining_fields_names,
                             truncated_fields_error))
                         .emit();
@@ -3269,7 +3266,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
             struct_span_err!(self.tcx.sess, path_span, E0071,
                              "expected struct, variant or union type, found {}",
                              ty.sort_string(self.tcx))
-                .span_label(path_span, &format!("not a struct"))
+                .span_label(path_span, "not a struct")
                 .emit();
             None
         }
@@ -3628,7 +3625,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                     "invalid left-hand side expression")
                 .span_label(
                     expr.span,
-                    &format!("left-hand of expression not valid"))
+                    "left-hand of expression not valid")
                 .emit();
             }
 
@@ -4520,7 +4517,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                              "too many lifetime parameters provided: \
                               expected at most {}, found {}",
                              expected_text, actual_text)
-                .span_label(span, &format!("expected {}", expected_text))
+                .span_label(span, format!("expected {}", expected_text))
                 .emit();
         } else if lifetimes.len() > 0 && lifetimes.len() < lifetime_defs.len() {
             let expected_text = count_lifetime_params(lifetime_defs.len());
@@ -4529,7 +4526,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                              "too few lifetime parameters provided: \
                               expected {}, found {}",
                              expected_text, actual_text)
-                .span_label(span, &format!("expected {}", expected_text))
+                .span_label(span, format!("expected {}", expected_text))
                 .emit();
         }
 
@@ -4554,7 +4551,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                              "too many type parameters provided: \
                               expected at most {}, found {}",
                              expected_text, actual_text)
-                .span_label(span, &format!("expected {}", expected_text))
+                .span_label(span, format!("expected {}", expected_text))
                 .emit();
 
             // To prevent derived errors to accumulate due to extra
@@ -4568,7 +4565,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                              "too few type parameters provided: \
                               expected {}, found {}",
                              expected_text, actual_text)
-                .span_label(span, &format!("expected {}", expected_text))
+                .span_label(span, format!("expected {}", expected_text))
                 .emit();
         }
 
@@ -4657,7 +4654,7 @@ pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             struct_span_err!(tcx.sess, param.span, E0091,
                 "type parameter `{}` is unused",
                 param.name)
-                .span_label(param.span, &format!("unused type parameter"))
+                .span_label(param.span, "unused type parameter")
                 .emit();
         }
     }
diff --git a/src/librustc_typeck/check/op.rs b/src/librustc_typeck/check/op.rs
index d3d65ce4a62..59cb61d9b97 100644
--- a/src/librustc_typeck/check/op.rs
+++ b/src/librustc_typeck/check/op.rs
@@ -50,7 +50,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                 E0067, "invalid left-hand side expression")
             .span_label(
                 lhs_expr.span,
-                &format!("invalid expression for left-hand side"))
+                "invalid expression for left-hand side")
             .emit();
         }
         ty
@@ -203,7 +203,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
                                          op.node.as_str(),
                                          lhs_ty)
                             .span_label(lhs_expr.span,
-                                        &format!("cannot use `{}=` on type `{}`",
+                                        format!("cannot use `{}=` on type `{}`",
                                         op.node.as_str(), lhs_ty))
                             .emit();
                     } else {
@@ -278,7 +278,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
             if let TyRef(_, r_ty) = rhs_ty.sty {
                 if l_ty.ty.sty == TyStr && r_ty.ty.sty == TyStr {
                     err.span_label(expr.span,
-                        &"`+` can't be used to concatenate two `&str` strings");
+                        "`+` can't be used to concatenate two `&str` strings");
                     let codemap = self.tcx.sess.codemap();
                     let suggestion =
                         match codemap.span_to_snippet(lhs_expr.span) {
diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs
index 1887eaef360..93529aecac0 100644
--- a/src/librustc_typeck/check/wfcheck.rs
+++ b/src/librustc_typeck/check/wfcheck.rs
@@ -684,7 +684,7 @@ fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast:
                        -> DiagnosticBuilder<'tcx> {
     let mut err = struct_span_err!(tcx.sess, span, E0392,
                   "parameter `{}` is never used", param_name);
-    err.span_label(span, &format!("unused type parameter"));
+    err.span_label(span, "unused type parameter");
     err
 }
 
@@ -692,7 +692,7 @@ fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: ast::Name) {
     struct_span_err!(tcx.sess, span, E0194,
               "type parameter `{}` shadows another type parameter of the same name",
               name)
-        .span_label(span, &format!("shadows another type parameter"))
-        .span_label(trait_decl_span, &format!("first `{}` declared here", name))
+        .span_label(span, "shadows another type parameter")
+        .span_label(trait_decl_span, format!("first `{}` declared here", name))
         .emit();
 }
diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs
index ab2151544fc..49440037af5 100644
--- a/src/librustc_typeck/check/writeback.rs
+++ b/src/librustc_typeck/check/writeback.rs
@@ -43,7 +43,6 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
         wbcx.visit_liberated_fn_sigs();
         wbcx.visit_fru_field_types();
         wbcx.visit_anon_types();
-        wbcx.visit_type_nodes();
         wbcx.visit_cast_types();
         wbcx.visit_lints();
         wbcx.visit_free_region_map();
@@ -442,13 +441,6 @@ impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
         }
     }
 
-    fn visit_type_nodes(&self) {
-        for (&id, ty) in self.fcx.ast_ty_to_ty_cache.borrow().iter() {
-            let ty = self.resolve(ty, &id);
-            self.fcx.tcx.ast_ty_to_ty_cache.borrow_mut().insert(id, ty);
-        }
-    }
-
     fn resolve<T>(&self, x: &T, span: &Locatable) -> T::Lifted
         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
     {
diff --git a/src/librustc_typeck/coherence/builtin.rs b/src/librustc_typeck/coherence/builtin.rs
index 49785d8850f..743bfbb44ab 100644
--- a/src/librustc_typeck/coherence/builtin.rs
+++ b/src/librustc_typeck/coherence/builtin.rs
@@ -74,7 +74,7 @@ fn visit_implementation_of_drop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                          E0120,
                                          "the Drop trait may only be implemented on \
                                          structures")
-                            .span_label(span, &format!("implementing Drop requires a struct"))
+                            .span_label(span, "implementing Drop requires a struct")
                             .emit();
                     }
                     _ => {
@@ -130,7 +130,7 @@ fn visit_implementation_of_copy<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                              "the trait `Copy` may not be implemented for this type")
                 .span_label(
                     tcx.def_span(field.did),
-                    &"this field does not implement `Copy`")
+                    "this field does not implement `Copy`")
                 .emit()
         }
         Err(CopyImplementationError::NotAnAdt) => {
@@ -145,7 +145,7 @@ fn visit_implementation_of_copy<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                              span,
                              E0206,
                              "the trait `Copy` may not be implemented for this type")
-                .span_label(span, &format!("type is not a structure or enumeration"))
+                .span_label(span, "type is not a structure or enumeration")
                 .emit();
         }
         Err(CopyImplementationError::HasDestructor) => {
@@ -154,7 +154,7 @@ fn visit_implementation_of_copy<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                              E0184,
                              "the trait `Copy` may not be implemented for this type; the \
                               type has a destructor")
-                .span_label(span, &format!("Copy not allowed on types with destructors"))
+                .span_label(span, "Copy not allowed on types with destructors")
                 .emit();
         }
     }
@@ -310,7 +310,7 @@ pub fn coerce_unsized_info<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                           })
                                           .collect::<Vec<_>>()
                                           .join(", ")));
-                    err.span_label(span, &format!("requires multiple coercions"));
+                    err.span_label(span, "requires multiple coercions");
                     err.emit();
                     return err_info;
                 }
diff --git a/src/librustc_typeck/coherence/inherent_impls.rs b/src/librustc_typeck/coherence/inherent_impls.rs
index 238952865c7..f7ebc210442 100644
--- a/src/librustc_typeck/coherence/inherent_impls.rs
+++ b/src/librustc_typeck/coherence/inherent_impls.rs
@@ -259,7 +259,7 @@ impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for InherentCollect<'a, 'tcx> {
                                  ty.span,
                                  E0118,
                                  "no base type found for inherent implementation")
-                    .span_label(ty.span, &format!("impl requires a base type"))
+                    .span_label(ty.span, "impl requires a base type")
                     .note(&format!("either implement a trait on it or create a newtype \
                                     to wrap it instead"))
                     .emit();
@@ -296,7 +296,7 @@ impl<'a, 'tcx> InherentCollect<'a, 'tcx> {
                              "cannot define inherent `impl` for a type outside of the crate \
                               where the type is defined")
                 .span_label(item.span,
-                            &format!("impl for type defined outside of crate."))
+                            "impl for type defined outside of crate.")
                 .note("define and implement a trait or new type instead")
                 .emit();
         }
diff --git a/src/librustc_typeck/coherence/inherent_impls_overlap.rs b/src/librustc_typeck/coherence/inherent_impls_overlap.rs
index 34aec8ef1ac..2751e1ff38a 100644
--- a/src/librustc_typeck/coherence/inherent_impls_overlap.rs
+++ b/src/librustc_typeck/coherence/inherent_impls_overlap.rs
@@ -56,9 +56,9 @@ impl<'a, 'tcx> InherentOverlapChecker<'a, 'tcx> {
                                      "duplicate definitions with name `{}`",
                                      name)
                         .span_label(self.tcx.span_of_impl(item1).unwrap(),
-                                    &format!("duplicate definitions for `{}`", name))
+                                    format!("duplicate definitions for `{}`", name))
                         .span_label(self.tcx.span_of_impl(item2).unwrap(),
-                                    &format!("other definition for `{}`", name))
+                                    format!("other definition for `{}`", name))
                         .emit();
                 }
             }
diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs
index 56ae9d54575..8b9dc20315d 100644
--- a/src/librustc_typeck/coherence/mod.rs
+++ b/src/librustc_typeck/coherence/mod.rs
@@ -62,7 +62,7 @@ fn enforce_trait_manually_implementable(tcx: TyCtxt, impl_def_id: DefId, trait_d
                          span,
                          E0322,
                          "explicit impls for the `Sized` trait are not permitted")
-            .span_label(span, &format!("impl of 'Sized' not allowed"))
+            .span_label(span, "impl of 'Sized' not allowed")
             .emit();
         return;
     }
diff --git a/src/librustc_typeck/coherence/orphan.rs b/src/librustc_typeck/coherence/orphan.rs
index 8ded3003c78..097720adad4 100644
--- a/src/librustc_typeck/coherence/orphan.rs
+++ b/src/librustc_typeck/coherence/orphan.rs
@@ -48,7 +48,7 @@ impl<'cx, 'tcx, 'v> ItemLikeVisitor<'v> for OrphanChecker<'cx, 'tcx> {
                                          E0117,
                                          "only traits defined in the current crate can be \
                                           implemented for arbitrary types")
-                            .span_label(item.span, &format!("impl doesn't use types inside crate"))
+                            .span_label(item.span, "impl doesn't use types inside crate")
                             .note(&format!("the impl does not reference any types defined in \
                                             this crate"))
                             .note("define and implement a trait or new type instead")
@@ -153,7 +153,7 @@ impl<'cx, 'tcx, 'v> ItemLikeVisitor<'v> for OrphanChecker<'cx, 'tcx> {
                                      "cannot create default implementations for traits outside \
                                       the crate they're defined in; define a new trait instead")
                         .span_label(item_trait_ref.path.span,
-                                    &format!("`{}` trait not defined in this crate",
+                                    format!("`{}` trait not defined in this crate",
                             self.tcx.hir.node_to_pretty_string(item_trait_ref.ref_id)))
                         .emit();
                     return;
diff --git a/src/librustc_typeck/coherence/overlap.rs b/src/librustc_typeck/coherence/overlap.rs
index 383a9e0e695..f479dc2e6ab 100644
--- a/src/librustc_typeck/coherence/overlap.rs
+++ b/src/librustc_typeck/coherence/overlap.rs
@@ -60,9 +60,9 @@ pub fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, node_id: ast::NodeId) {
 
         match tcx.span_of_impl(overlap.with_impl) {
             Ok(span) => {
-                err.span_label(span, &format!("first implementation here"));
+                err.span_label(span, "first implementation here");
                 err.span_label(tcx.span_of_impl(impl_def_id).unwrap(),
-                               &format!("conflicting implementation{}",
+                               format!("conflicting implementation{}",
                                         overlap.self_desc
                                             .map_or(String::new(),
                                                     |ty| format!(" for `{}`", ty))));
diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs
index 0d75a1ecf3d..ec200241ee6 100644
--- a/src/librustc_typeck/collect.rs
+++ b/src/librustc_typeck/collect.rs
@@ -64,11 +64,10 @@ use rustc::ty::{ToPredicate, ReprOptions};
 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
 use rustc::ty::maps::Providers;
 use rustc::ty::util::IntTypeExt;
-use util::nodemap::{NodeMap, FxHashMap};
+use util::nodemap::FxHashMap;
 
 use rustc_const_math::ConstInt;
 
-use std::cell::RefCell;
 use std::collections::BTreeMap;
 
 use syntax::{abi, ast};
@@ -116,7 +115,7 @@ pub fn provide(providers: &mut Providers) {
 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
 /// `get_type_parameter_bounds` requests, drawing the information from
 /// the AST (`hir::Generics`), recursively.
-struct ItemCtxt<'a,'tcx:'a> {
+pub struct ItemCtxt<'a,'tcx:'a> {
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
     item_def_id: DefId,
 }
@@ -180,7 +179,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
 // Utility types and common code for the above passes.
 
 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
-    fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId)
+    pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId)
            -> ItemCtxt<'a,'tcx> {
         ItemCtxt {
             tcx: tcx,
@@ -190,7 +189,7 @@ impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
 }
 
 impl<'a,'tcx> ItemCtxt<'a,'tcx> {
-    fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
+    pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
         AstConv::ast_ty_to_ty(self, ast_ty)
     }
 }
@@ -198,10 +197,6 @@ impl<'a,'tcx> ItemCtxt<'a,'tcx> {
 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> { self.tcx }
 
-    fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>> {
-        &self.tcx.ast_ty_to_ty_cache
-    }
-
     fn get_type_parameter_bounds(&self,
                                  span: Span,
                                  def_id: DefId)
@@ -225,7 +220,7 @@ impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
             span,
             E0121,
             "the type placeholder `_` is not allowed within types on item signatures"
-        ).span_label(span, &format!("not allowed in type signatures"))
+        ).span_label(span, "not allowed in type signatures")
         .emit();
         self.tcx().types.err
     }
@@ -573,7 +568,7 @@ fn convert_enum_variant_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
         } else {
             struct_span_err!(tcx.sess, variant.span, E0370,
                              "enum discriminant overflowed")
-                .span_label(variant.span, &format!("overflowed on value after {}",
+                .span_label(variant.span, format!("overflowed on value after {}",
                                                    prev_discr.unwrap()))
                 .note(&format!("explicitly set `{} = {}` if that is desired outcome",
                                variant.node.name, wrapped_discr))
@@ -609,8 +604,8 @@ fn convert_struct_variant<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             struct_span_err!(tcx.sess, f.span, E0124,
                              "field `{}` is already declared",
                              f.name)
-                .span_label(f.span, &"field already declared")
-                .span_label(prev_span, &format!("`{}` first declared here", f.name))
+                .span_label(f.span, "field already declared")
+                .span_label(prev_span, format!("`{}` first declared here", f.name))
                 .emit();
         } else {
             seen_fields.insert(f.name, f.span);
diff --git a/src/librustc_typeck/impl_wf_check.rs b/src/librustc_typeck/impl_wf_check.rs
index 1c44572fbb4..6b4f08d3d4c 100644
--- a/src/librustc_typeck/impl_wf_check.rs
+++ b/src/librustc_typeck/impl_wf_check.rs
@@ -166,7 +166,7 @@ fn report_unused_parameter(tcx: TyCtxt,
         "the {} parameter `{}` is not constrained by the \
         impl trait, self type, or predicates",
         kind, name)
-        .span_label(span, &format!("unconstrained {} parameter", kind))
+        .span_label(span, format!("unconstrained {} parameter", kind))
         .emit();
 }
 
@@ -188,9 +188,9 @@ fn enforce_impl_items_are_distinct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                                "duplicate definitions with name `{}`:",
                                                impl_item.name);
                 err.span_label(*entry.get(),
-                               &format!("previous definition of `{}` here",
+                               format!("previous definition of `{}` here",
                                         impl_item.name));
-                err.span_label(impl_item.span, &format!("duplicate definition"));
+                err.span_label(impl_item.span, "duplicate definition");
                 err.emit();
             }
             Vacant(entry) => {
diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs
index 94b4bfade94..84de4ff2b7b 100644
--- a/src/librustc_typeck/lib.rs
+++ b/src/librustc_typeck/lib.rs
@@ -122,14 +122,14 @@ use std::iter;
 // registered before they are used.
 pub mod diagnostics;
 
-pub mod check;
-pub mod check_unused;
+mod check;
+mod check_unused;
 mod astconv;
-pub mod collect;
+mod collect;
 mod constrained_type_params;
 mod impl_wf_check;
-pub mod coherence;
-pub mod variance;
+mod coherence;
+mod variance;
 
 pub struct TypeAndSubsts<'tcx> {
     pub substs: &'tcx Substs<'tcx>,
@@ -143,7 +143,7 @@ fn require_c_abi_if_variadic(tcx: TyCtxt,
     if decl.variadic && abi != Abi::C {
         let mut err = struct_span_err!(tcx.sess, span, E0045,
                   "variadic function must have C calling convention");
-        err.span_label(span, &("variadics require C calling conventions").to_string())
+        err.span_label(span, "variadics require C calling conventions")
             .emit();
     }
 }
@@ -190,7 +190,7 @@ fn check_main_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                 struct_span_err!(tcx.sess, generics.span, E0131,
                                          "main function is not allowed to have type parameters")
                                     .span_label(generics.span,
-                                                &format!("main cannot have type parameters"))
+                                                "main cannot have type parameters")
                                     .emit();
                                 return;
                             }
@@ -240,7 +240,7 @@ fn check_start_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                             struct_span_err!(tcx.sess, ps.span, E0132,
                                 "start function is not allowed to have type parameters")
                                 .span_label(ps.span,
-                                            &format!("start function cannot have type parameters"))
+                                            "start function cannot have type parameters")
                                 .emit();
                             return;
                         }
@@ -293,6 +293,7 @@ pub fn provide(providers: &mut Providers) {
     collect::provide(providers);
     coherence::provide(providers);
     check::provide(providers);
+    variance::provide(providers);
 }
 
 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
@@ -307,9 +308,6 @@ pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
 
     })?;
 
-    time(time_passes, "variance inference", ||
-         variance::infer_variance(tcx));
-
     tcx.sess.track_errors(|| {
         time(time_passes, "impl wf inference", ||
              impl_wf_check::impl_wf_check(tcx));
@@ -320,6 +318,11 @@ pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
           coherence::check_coherence(tcx));
     })?;
 
+    tcx.sess.track_errors(|| {
+        time(time_passes, "variance testing", ||
+             variance::test::test_variance(tcx));
+    })?;
+
     time(time_passes, "wf checking", || check::check_wf_new(tcx))?;
 
     time(time_passes, "item-types checking", || check::check_item_types(tcx))?;
@@ -337,4 +340,16 @@ pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
     }
 }
 
+/// A quasi-deprecated helper used in rustdoc and save-analysis to get
+/// the type from a HIR node.
+pub fn hir_ty_to_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, hir_ty: &hir::Ty) -> Ty<'tcx> {
+    // In case there are any projections etc, find the "environment"
+    // def-id that will be used to determine the traits/predicates in
+    // scope.  This is derived from the enclosing item-like thing.
+    let env_node_id = tcx.hir.get_parent(hir_ty.id);
+    let env_def_id = tcx.hir.local_def_id(env_node_id);
+    let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id);
+    item_cx.to_ty(hir_ty)
+}
+
 __build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
diff --git a/src/librustc_typeck/variance/README.md b/src/librustc_typeck/variance/README.md
index ac785e4058b..59291617889 100644
--- a/src/librustc_typeck/variance/README.md
+++ b/src/librustc_typeck/variance/README.md
@@ -97,51 +97,29 @@ types involved before considering variance.
 
 #### Dependency graph management
 
-Because variance works in two phases, if we are not careful, we wind
-up with a muddled mess of a dep-graph. Basically, when gathering up
-the constraints, things are fairly well-structured, but then we do a
-fixed-point iteration and write the results back where they
-belong. You can't give this fixed-point iteration a single task
-because it reads from (and writes to) the variance of all types in the
-crate. In principle, we *could* switch the "current task" in a very
-fine-grained way while propagating constraints in the fixed-point
-iteration and everything would be automatically tracked, but that
-would add some overhead and isn't really necessary anyway.
-
-Instead what we do is to add edges into the dependency graph as we
-construct the constraint set: so, if computing the constraints for
-node `X` requires loading the inference variables from node `Y`, then
-we can add an edge `Y -> X`, since the variance we ultimately infer
-for `Y` will affect the variance we ultimately infer for `X`.
-
-At this point, we've basically mirrored the inference graph in the
-dependency graph. This means we can just completely ignore the
-fixed-point iteration, since it is just shuffling values along this
-graph. In other words, if we added the fine-grained switching of tasks
-I described earlier, all it would show is that we repeatedly read the
-values described by the constraints, but those edges were already
-added when building the constraints in the first place.
-
-Here is how this is implemented (at least as of the time of this
-writing). The associated `DepNode` for the variance map is (at least
-presently) `Signature(DefId)`. This means that, in `constraints.rs`,
-when we visit an item to load up its constraints, we set
-`Signature(DefId)` as the current task (the "memoization" pattern
-described in the `dep-graph` README). Then whenever we find an
-embedded type or trait, we add a synthetic read of `Signature(DefId)`,
-which covers the variances we will compute for all of its
-parameters. This read is synthetic (i.e., we call
-`variance_map.read()`) because, in fact, the final variance is not yet
-computed -- the read *will* occur (repeatedly) during the fixed-point
-iteration phase.
-
-In fact, we don't really *need* this synthetic read. That's because we
-do wind up looking up the `TypeScheme` or `TraitDef` for all
-references types/traits, and those reads add an edge from
-`Signature(DefId)` (that is, they share the same dep node as
-variance). However, I've kept the synthetic reads in place anyway,
-just for future-proofing (in case we change the dep-nodes in the
-future), and because it makes the intention a bit clearer I think.
+Because variance is a whole-crate inference, its dependency graph
+can become quite muddled if we are not careful. To resolve this, we refactor
+into two queries:
+
+- `crate_variances` computes the variance for all items in the current crate.
+- `variances_of` accesses the variance for an individual reading; it
+  works by requesting `crate_variances` and extracting the relevant data.
+  
+If you limit yourself to reading `variances_of`, your code will only
+depend then on the inference inferred for that particular item.
+
+Eventually, the goal is to rely on the red-green dependency management
+algorithm. At the moment, however, we rely instead on a hack, where
+`variances_of` ignores the dependencies of accessing
+`crate_variances` and instead computes the *correct* dependencies
+itself. To this end, when we build up the constraints in the system,
+we also built up a transitive `dependencies` relation as part of the
+crate map. A `(X, Y)` pair is added to the map each time we have a
+constraint that the variance of some inferred for the item `X` depends
+on the variance of some element of `Y`. This is to some extent a
+mirroring of the inference graph in the dependency graph. This means
+we can just completely ignore the fixed-point iteration, since it is
+just shuffling values along this graph.
 
 ### Addendum: Variance on traits
 
diff --git a/src/librustc_typeck/variance/constraints.rs b/src/librustc_typeck/variance/constraints.rs
index 529b2700679..e986a381cd9 100644
--- a/src/librustc_typeck/variance/constraints.rs
+++ b/src/librustc_typeck/variance/constraints.rs
@@ -15,6 +15,7 @@
 
 use hir::def_id::DefId;
 use middle::resolve_lifetime as rl;
+use rustc::dep_graph::{AssertDepGraphSafe, DepNode};
 use rustc::ty::subst::Substs;
 use rustc::ty::{self, Ty, TyCtxt};
 use rustc::hir::map as hir_map;
@@ -22,12 +23,12 @@ use syntax::ast;
 use rustc::hir;
 use rustc::hir::itemlikevisit::ItemLikeVisitor;
 
+use rustc_data_structures::transitive_relation::TransitiveRelation;
+
 use super::terms::*;
 use super::terms::VarianceTerm::*;
 use super::xform::*;
 
-use dep_graph::DepNode::ItemSignature as VarianceDepNode;
-
 pub struct ConstraintContext<'a, 'tcx: 'a> {
     pub terms_cx: TermsContext<'a, 'tcx>,
 
@@ -38,6 +39,11 @@ pub struct ConstraintContext<'a, 'tcx: 'a> {
     bivariant: VarianceTermPtr<'a>,
 
     pub constraints: Vec<Constraint<'a>>,
+
+    /// This relation tracks the dependencies between the variance of
+    /// various items. In particular, if `a < b`, then the variance of
+    /// `a` depends on the sources of `b`.
+    pub dependencies: TransitiveRelation<DefId>,
 }
 
 /// Declares that the variable `decl_id` appears in a location with
@@ -48,6 +54,20 @@ pub struct Constraint<'a> {
     pub variance: &'a VarianceTerm<'a>,
 }
 
+/// To build constriants, we visit one item (type, trait) at a time
+/// and look at its contents. So e.g. if we have
+///
+///     struct Foo<T> {
+///         b: Bar<T>
+///     }
+///
+/// then while we are visiting `Bar<T>`, the `CurrentItem` would have
+/// the def-id and generics of `Foo`.
+pub struct CurrentItem<'a> {
+    def_id: DefId,
+    generics: &'a ty::Generics,
+}
+
 pub fn add_constraints_from_crate<'a, 'tcx>(terms_cx: TermsContext<'a, 'tcx>)
                                             -> ConstraintContext<'a, 'tcx> {
     let tcx = terms_cx.tcx;
@@ -62,10 +82,10 @@ pub fn add_constraints_from_crate<'a, 'tcx>(terms_cx: TermsContext<'a, 'tcx>)
         invariant: invariant,
         bivariant: bivariant,
         constraints: Vec::new(),
+        dependencies: TransitiveRelation::new(),
     };
 
-    // See README.md for a discussion on dep-graph management.
-    tcx.visit_all_item_likes_in_krate(VarianceDepNode, &mut constraint_cx);
+    tcx.hir.krate().visit_all_item_likes(&mut constraint_cx);
 
     constraint_cx
 }
@@ -73,15 +93,67 @@ pub fn add_constraints_from_crate<'a, 'tcx>(terms_cx: TermsContext<'a, 'tcx>)
 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ConstraintContext<'a, 'tcx> {
     fn visit_item(&mut self, item: &hir::Item) {
         let tcx = self.terms_cx.tcx;
-        let did = tcx.hir.local_def_id(item.id);
+        let def_id = tcx.hir.local_def_id(item.id);
+
+        // Encapsulate constructing the constraints into a task we can
+        // reference later. This can go away once the red-green
+        // algorithm is in place.
+        //
+        // See README.md for a detailed discussion
+        // on dep-graph management.
+        match item.node {
+            hir::ItemEnum(..) |
+            hir::ItemStruct(..) |
+            hir::ItemUnion(..) => {
+                tcx.dep_graph.with_task(DepNode::ItemVarianceConstraints(def_id),
+                                        AssertDepGraphSafe(self),
+                                        def_id,
+                                        visit_item_task);
+            }
+            _ => {
+                // Nothing to do here, skip the task.
+            }
+        }
+
+        fn visit_item_task<'a, 'tcx>(ccx: AssertDepGraphSafe<&mut ConstraintContext<'a, 'tcx>>,
+                                     def_id: DefId)
+        {
+            ccx.0.build_constraints_for_item(def_id);
+        }
+    }
+
+    fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
+    }
+
+    fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
+    }
+}
+
+/// Is `param_id` a lifetime according to `map`?
+fn is_lifetime(map: &hir_map::Map, param_id: ast::NodeId) -> bool {
+    match map.find(param_id) {
+        Some(hir_map::NodeLifetime(..)) => true,
+        _ => false,
+    }
+}
+
+impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
+    fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
+        self.terms_cx.tcx
+    }
 
+    fn build_constraints_for_item(&mut self, def_id: DefId) {
+        let tcx = self.tcx();
+        let id = self.tcx().hir.as_local_node_id(def_id).unwrap();
+        let item = tcx.hir.expect_item(id);
         debug!("visit_item item={}", tcx.hir.node_to_string(item.id));
 
         match item.node {
             hir::ItemEnum(..) |
             hir::ItemStruct(..) |
             hir::ItemUnion(..) => {
-                let generics = tcx.generics_of(did);
+                let generics = tcx.generics_of(def_id);
+                let current_item = &CurrentItem { def_id, generics };
 
                 // Not entirely obvious: constraints on structs/enums do not
                 // affect the variance of their type parameters. See discussion
@@ -89,23 +161,14 @@ impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ConstraintContext<'a, 'tcx> {
                 //
                 // self.add_constraints_from_generics(generics);
 
-                for field in tcx.adt_def(did).all_fields() {
-                    self.add_constraints_from_ty(generics,
+                for field in tcx.adt_def(def_id).all_fields() {
+                    self.add_constraints_from_ty(current_item,
                                                  tcx.type_of(field.did),
                                                  self.covariant);
                 }
             }
-            hir::ItemTrait(..) => {
-                let generics = tcx.generics_of(did);
-                let trait_ref = ty::TraitRef {
-                    def_id: did,
-                    substs: Substs::identity_for_item(tcx, did)
-                };
-                self.add_constraints_from_trait_ref(generics,
-                                                    trait_ref,
-                                                    self.invariant);
-            }
 
+            hir::ItemTrait(..) |
             hir::ItemExternCrate(_) |
             hir::ItemUse(..) |
             hir::ItemStatic(..) |
@@ -116,38 +179,25 @@ impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ConstraintContext<'a, 'tcx> {
             hir::ItemGlobalAsm(..) |
             hir::ItemTy(..) |
             hir::ItemImpl(..) |
-            hir::ItemDefaultImpl(..) => {}
+            hir::ItemDefaultImpl(..) => {
+                span_bug!(item.span, "`build_constraints_for_item` invoked for non-type-def");
+            }
         }
     }
 
-    fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
-    }
-
-    fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
-    }
-}
-
-/// Is `param_id` a lifetime according to `map`?
-fn is_lifetime(map: &hir_map::Map, param_id: ast::NodeId) -> bool {
-    match map.find(param_id) {
-        Some(hir_map::NodeLifetime(..)) => true,
-        _ => false,
-    }
-}
-
-impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
-    fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
-        self.terms_cx.tcx
+    /// Load the generics for another item, adding a corresponding
+    /// relation into the dependencies to indicate that the variance
+    /// for `current` relies on `def_id`.
+    fn read_generics(&mut self, current: &CurrentItem, def_id: DefId) -> &'tcx ty::Generics {
+        let generics = self.tcx().generics_of(def_id);
+        if self.tcx().dep_graph.is_fully_enabled() {
+            self.dependencies.add(current.def_id, def_id);
+        }
+        generics
     }
 
-    fn inferred_index(&self, param_id: ast::NodeId) -> InferredIndex {
-        match self.terms_cx.inferred_map.get(&param_id) {
-            Some(&index) => index,
-            None => {
-                bug!("no inferred index entry for {}",
-                     self.tcx().hir.node_to_string(param_id));
-            }
-        }
+    fn opt_inferred_index(&self, param_id: ast::NodeId) -> Option<&InferredIndex> {
+        self.terms_cx.inferred_map.get(&param_id)
     }
 
     fn find_binding_for_lifetime(&self, param_id: ast::NodeId) -> ast::NodeId {
@@ -228,8 +278,27 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
             // Parameter on an item defined within current crate:
             // variance not yet inferred, so return a symbolic
             // variance.
-            let InferredIndex(index) = self.inferred_index(param_node_id);
-            self.terms_cx.inferred_infos[index].term
+            if let Some(&InferredIndex(index)) = self.opt_inferred_index(param_node_id) {
+                self.terms_cx.inferred_infos[index].term
+            } else {
+                // If there is no inferred entry for a type parameter,
+                // it must be declared on a (locally defiend) trait -- they don't
+                // get inferreds because they are always invariant.
+                if cfg!(debug_assertions) {
+                    let item_node_id = self.tcx().hir.as_local_node_id(item_def_id).unwrap();
+                    let item = self.tcx().hir.expect_item(item_node_id);
+                    let success = match item.node {
+                        hir::ItemTrait(..) => true,
+                        _ => false,
+                    };
+                    if !success {
+                        bug!("parameter {:?} has no inferred, but declared on non-trait: {:?}",
+                             item_def_id,
+                             item);
+                    }
+                }
+                self.invariant
+            }
         } else {
             // Parameter on an item defined within another crate:
             // variance already inferred, just look it up.
@@ -279,7 +348,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
     }
 
     fn add_constraints_from_trait_ref(&mut self,
-                                      generics: &ty::Generics,
+                                      current: &CurrentItem,
                                       trait_ref: ty::TraitRef<'tcx>,
                                       variance: VarianceTermPtr<'a>) {
         debug!("add_constraints_from_trait_ref: trait_ref={:?} variance={:?}",
@@ -288,12 +357,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
 
         let trait_generics = self.tcx().generics_of(trait_ref.def_id);
 
-        // This edge is actually implied by the call to
-        // `trait_def`, but I'm trying to be future-proof. See
-        // README.md for a discussion on dep-graph management.
-        self.tcx().dep_graph.read(VarianceDepNode(trait_ref.def_id));
-
-        self.add_constraints_from_substs(generics,
+        self.add_constraints_from_substs(current,
                                          trait_ref.def_id,
                                          &trait_generics.types,
                                          &trait_generics.regions,
@@ -305,7 +369,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
     /// in a context with the generics defined in `generics` and
     /// ambient variance `variance`
     fn add_constraints_from_ty(&mut self,
-                               generics: &ty::Generics,
+                               current: &CurrentItem,
                                ty: Ty<'tcx>,
                                variance: VarianceTermPtr<'a>) {
         debug!("add_constraints_from_ty(ty={:?}, variance={:?})",
@@ -325,34 +389,29 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
 
             ty::TyRef(region, ref mt) => {
                 let contra = self.contravariant(variance);
-                self.add_constraints_from_region(generics, region, contra);
-                self.add_constraints_from_mt(generics, mt, variance);
+                self.add_constraints_from_region(current, region, contra);
+                self.add_constraints_from_mt(current, mt, variance);
             }
 
             ty::TyArray(typ, _) |
             ty::TySlice(typ) => {
-                self.add_constraints_from_ty(generics, typ, variance);
+                self.add_constraints_from_ty(current, typ, variance);
             }
 
             ty::TyRawPtr(ref mt) => {
-                self.add_constraints_from_mt(generics, mt, variance);
+                self.add_constraints_from_mt(current, mt, variance);
             }
 
             ty::TyTuple(subtys, _) => {
                 for &subty in subtys {
-                    self.add_constraints_from_ty(generics, subty, variance);
+                    self.add_constraints_from_ty(current, subty, variance);
                 }
             }
 
             ty::TyAdt(def, substs) => {
-                let adt_generics = self.tcx().generics_of(def.did);
+                let adt_generics = self.read_generics(current, def.did);
 
-                // This edge is actually implied by the call to
-                // `trait_def`, but I'm trying to be future-proof. See
-                // README.md for a discussion on dep-graph management.
-                self.tcx().dep_graph.read(VarianceDepNode(def.did));
-
-                self.add_constraints_from_substs(generics,
+                self.add_constraints_from_substs(current,
                                                  def.did,
                                                  &adt_generics.types,
                                                  &adt_generics.regions,
@@ -364,12 +423,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
                 let trait_ref = &data.trait_ref;
                 let trait_generics = self.tcx().generics_of(trait_ref.def_id);
 
-                // This edge is actually implied by the call to
-                // `trait_def`, but I'm trying to be future-proof. See
-                // README.md for a discussion on dep-graph management.
-                self.tcx().dep_graph.read(VarianceDepNode(trait_ref.def_id));
-
-                self.add_constraints_from_substs(generics,
+                self.add_constraints_from_substs(current,
                                                  trait_ref.def_id,
                                                  &trait_generics.types,
                                                  &trait_generics.regions,
@@ -380,25 +434,25 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
             ty::TyDynamic(ref data, r) => {
                 // The type `Foo<T+'a>` is contravariant w/r/t `'a`:
                 let contra = self.contravariant(variance);
-                self.add_constraints_from_region(generics, r, contra);
+                self.add_constraints_from_region(current, r, contra);
 
                 if let Some(p) = data.principal() {
                     let poly_trait_ref = p.with_self_ty(self.tcx(), self.tcx().types.err);
-                    self.add_constraints_from_trait_ref(generics, poly_trait_ref.0, variance);
+                    self.add_constraints_from_trait_ref(current, poly_trait_ref.0, variance);
                 }
 
                 for projection in data.projection_bounds() {
-                    self.add_constraints_from_ty(generics, projection.0.ty, self.invariant);
+                    self.add_constraints_from_ty(current, projection.0.ty, self.invariant);
                 }
             }
 
             ty::TyParam(ref data) => {
-                assert_eq!(generics.parent, None);
+                assert_eq!(current.generics.parent, None);
                 let mut i = data.idx as usize;
-                if !generics.has_self || i > 0 {
-                    i -= generics.regions.len();
+                if !current.generics.has_self || i > 0 {
+                    i -= current.generics.regions.len();
                 }
-                let def_id = generics.types[i].def_id;
+                let def_id = current.generics.types[i].def_id;
                 let node_id = self.tcx().hir.as_local_node_id(def_id).unwrap();
                 match self.terms_cx.inferred_map.get(&node_id) {
                     Some(&index) => {
@@ -414,7 +468,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
 
             ty::TyFnDef(.., sig) |
             ty::TyFnPtr(sig) => {
-                self.add_constraints_from_sig(generics, sig, variance);
+                self.add_constraints_from_sig(current, sig, variance);
             }
 
             ty::TyError => {
@@ -433,7 +487,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
     /// Adds constraints appropriate for a nominal type (enum, struct,
     /// object, etc) appearing in a context with ambient variance `variance`
     fn add_constraints_from_substs(&mut self,
-                                   generics: &ty::Generics,
+                                   current: &CurrentItem,
                                    def_id: DefId,
                                    type_param_defs: &[ty::TypeParameterDef],
                                    region_param_defs: &[ty::RegionParameterDef],
@@ -451,44 +505,44 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
             debug!("add_constraints_from_substs: variance_decl={:?} variance_i={:?}",
                    variance_decl,
                    variance_i);
-            self.add_constraints_from_ty(generics, substs_ty, variance_i);
+            self.add_constraints_from_ty(current, substs_ty, variance_i);
         }
 
         for p in region_param_defs {
             let variance_decl = self.declared_variance(p.def_id, def_id, p.index as usize);
             let variance_i = self.xform(variance, variance_decl);
             let substs_r = substs.region_for_def(p);
-            self.add_constraints_from_region(generics, substs_r, variance_i);
+            self.add_constraints_from_region(current, substs_r, variance_i);
         }
     }
 
     /// Adds constraints appropriate for a function with signature
     /// `sig` appearing in a context with ambient variance `variance`
     fn add_constraints_from_sig(&mut self,
-                                generics: &ty::Generics,
+                                current: &CurrentItem,
                                 sig: ty::PolyFnSig<'tcx>,
                                 variance: VarianceTermPtr<'a>) {
         let contra = self.contravariant(variance);
         for &input in sig.0.inputs() {
-            self.add_constraints_from_ty(generics, input, contra);
+            self.add_constraints_from_ty(current, input, contra);
         }
-        self.add_constraints_from_ty(generics, sig.0.output(), variance);
+        self.add_constraints_from_ty(current, sig.0.output(), variance);
     }
 
     /// Adds constraints appropriate for a region appearing in a
     /// context with ambient variance `variance`
     fn add_constraints_from_region(&mut self,
-                                   generics: &ty::Generics,
+                                   current: &CurrentItem,
                                    region: ty::Region<'tcx>,
                                    variance: VarianceTermPtr<'a>) {
         match *region {
             ty::ReEarlyBound(ref data) => {
-                assert_eq!(generics.parent, None);
-                let i = data.index as usize - generics.has_self as usize;
-                let def_id = generics.regions[i].def_id;
+                assert_eq!(current.generics.parent, None);
+                let i = data.index as usize - current.generics.has_self as usize;
+                let def_id = current.generics.regions[i].def_id;
                 let node_id = self.tcx().hir.as_local_node_id(def_id).unwrap();
                 if self.is_to_be_inferred(node_id) {
-                    let index = self.inferred_index(node_id);
+                    let &index = self.opt_inferred_index(node_id).unwrap();
                     self.add_constraint(index, variance);
                 }
             }
@@ -518,17 +572,17 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
     /// Adds constraints appropriate for a mutability-type pair
     /// appearing in a context with ambient variance `variance`
     fn add_constraints_from_mt(&mut self,
-                               generics: &ty::Generics,
+                               current: &CurrentItem,
                                mt: &ty::TypeAndMut<'tcx>,
                                variance: VarianceTermPtr<'a>) {
         match mt.mutbl {
             hir::MutMutable => {
                 let invar = self.invariant(variance);
-                self.add_constraints_from_ty(generics, mt.ty, invar);
+                self.add_constraints_from_ty(current, mt.ty, invar);
             }
 
             hir::MutImmutable => {
-                self.add_constraints_from_ty(generics, mt.ty, variance);
+                self.add_constraints_from_ty(current, mt.ty, variance);
             }
         }
     }
diff --git a/src/librustc_typeck/variance/mod.rs b/src/librustc_typeck/variance/mod.rs
index cd0ab1cbb95..1afe2725ac8 100644
--- a/src/librustc_typeck/variance/mod.rs
+++ b/src/librustc_typeck/variance/mod.rs
@@ -12,7 +12,12 @@
 //! parameters. See README.md for details.
 
 use arena;
-use rustc::ty::TyCtxt;
+use rustc::dep_graph::DepNode;
+use rustc::hir;
+use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
+use rustc::ty::{self, CrateVariancesMap, TyCtxt};
+use rustc::ty::maps::Providers;
+use std::rc::Rc;
 
 /// Defines the `TermsContext` basically houses an arena where we can
 /// allocate terms.
@@ -24,13 +29,67 @@ mod constraints;
 /// Code to solve constraints and write out the results.
 mod solve;
 
+/// Code to write unit tests of variance.
+pub mod test;
+
 /// Code for transforming variances.
 mod xform;
 
-pub fn infer_variance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
+pub fn provide(providers: &mut Providers) {
+    *providers = Providers {
+        variances_of,
+        crate_variances,
+        ..*providers
+    };
+}
+
+fn crate_variances<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum)
+                             -> Rc<CrateVariancesMap> {
+    assert_eq!(crate_num, LOCAL_CRATE);
     let mut arena = arena::TypedArena::new();
     let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &mut arena);
     let constraints_cx = constraints::add_constraints_from_crate(terms_cx);
-    solve::solve_constraints(constraints_cx);
-    tcx.variance_computed.set(true);
+    Rc::new(solve::solve_constraints(constraints_cx))
+}
+
+fn variances_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId)
+                            -> Rc<Vec<ty::Variance>> {
+    let item_id = tcx.hir.as_local_node_id(item_def_id).expect("expected local def-id");
+    let item = tcx.hir.expect_item(item_id);
+    match item.node {
+        hir::ItemTrait(..) => {
+            // Traits are always invariant.
+            let generics = tcx.generics_of(item_def_id);
+            assert!(generics.parent.is_none());
+            Rc::new(vec![ty::Variance::Invariant; generics.count()])
+        }
+
+        hir::ItemEnum(..) |
+        hir::ItemStruct(..) |
+        hir::ItemUnion(..) => {
+            // Everything else must be inferred.
+
+            // Lacking red/green, we read the variances for all items here
+            // but ignore the dependencies, then re-synthesize the ones we need.
+            let crate_map = tcx.dep_graph.with_ignore(|| tcx.crate_variances(LOCAL_CRATE));
+            tcx.dep_graph.read(DepNode::ItemVarianceConstraints(item_def_id));
+            for &dep_def_id in crate_map.dependencies.less_than(&item_def_id) {
+                if dep_def_id.is_local() {
+                    tcx.dep_graph.read(DepNode::ItemVarianceConstraints(dep_def_id));
+                } else {
+                    tcx.dep_graph.read(DepNode::ItemVariances(dep_def_id));
+                }
+            }
+
+            crate_map.variances.get(&item_def_id)
+                               .unwrap_or(&crate_map.empty_variance)
+                               .clone()
+        }
+
+        _ => {
+            // Variance not relevant.
+            span_bug!(item.span, "asked to compute variance for wrong kind of item")
+        }
+    }
 }
+
diff --git a/src/librustc_typeck/variance/solve.rs b/src/librustc_typeck/variance/solve.rs
index 27116cbbb7a..af8ad491ec0 100644
--- a/src/librustc_typeck/variance/solve.rs
+++ b/src/librustc_typeck/variance/solve.rs
@@ -15,7 +15,9 @@
 //! optimal solution to the constraints. The final variance for each
 //! inferred is then written into the `variance_map` in the tcx.
 
+use rustc::hir::def_id::DefId;
 use rustc::ty;
+use rustc_data_structures::fx::FxHashMap;
 use std::rc::Rc;
 
 use super::constraints::*;
@@ -31,8 +33,8 @@ struct SolveContext<'a, 'tcx: 'a> {
     solutions: Vec<ty::Variance>,
 }
 
-pub fn solve_constraints(constraints_cx: ConstraintContext) {
-    let ConstraintContext { terms_cx, constraints, .. } = constraints_cx;
+pub fn solve_constraints(constraints_cx: ConstraintContext) -> ty::CrateVariancesMap {
+    let ConstraintContext { terms_cx, dependencies, constraints, .. } = constraints_cx;
 
     let solutions = terms_cx.inferred_infos
         .iter()
@@ -45,7 +47,10 @@ pub fn solve_constraints(constraints_cx: ConstraintContext) {
         solutions: solutions,
     };
     solutions_cx.solve();
-    solutions_cx.write();
+    let variances = solutions_cx.create_map();
+    let empty_variance = Rc::new(Vec::new());
+
+    ty::CrateVariancesMap { dependencies, variances, empty_variance }
 }
 
 impl<'a, 'tcx> SolveContext<'a, 'tcx> {
@@ -83,7 +88,7 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> {
         }
     }
 
-    fn write(&self) {
+    fn create_map(&self) -> FxHashMap<DefId, Rc<Vec<ty::Variance>>> {
         // Collect all the variances for a particular item and stick
         // them into the variance map. We rely on the fact that we
         // generate all the inferreds for a particular item
@@ -95,11 +100,7 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> {
 
         let tcx = self.terms_cx.tcx;
 
-        // Ignore the writes here because the relevant edges were
-        // already accounted for in `constraints.rs`. See the section
-        // on dependency graph management in README.md for more
-        // information.
-        let _ignore = tcx.dep_graph.in_ignore();
+        let mut map = FxHashMap();
 
         let solutions = &self.solutions;
         let inferred_infos = &self.terms_cx.inferred_infos;
@@ -127,19 +128,10 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> {
 
             let item_def_id = tcx.hir.local_def_id(item_id);
 
-            // For unit testing: check for a special "rustc_variance"
-            // attribute and report an error with various results if found.
-            if tcx.has_attr(item_def_id, "rustc_variance") {
-                span_err!(tcx.sess,
-                          tcx.hir.span(item_id),
-                          E0208,
-                          "{:?}",
-                          item_variances);
-            }
-
-            tcx.maps.variances_of.borrow_mut()
-               .insert(item_def_id, Rc::new(item_variances));
+            map.insert(item_def_id, Rc::new(item_variances));
         }
+
+        map
     }
 
     fn evaluate(&self, term: VarianceTermPtr<'a>) -> ty::Variance {
diff --git a/src/librustc_typeck/variance/terms.rs b/src/librustc_typeck/variance/terms.rs
index 61ff154e458..ad787c57e76 100644
--- a/src/librustc_typeck/variance/terms.rs
+++ b/src/librustc_typeck/variance/terms.rs
@@ -32,8 +32,6 @@ use self::VarianceTerm::*;
 
 pub type VarianceTermPtr<'a> = &'a VarianceTerm<'a>;
 
-use dep_graph::DepNode::ItemSignature as VarianceDepNode;
-
 #[derive(Copy, Clone, Debug)]
 pub struct InferredIndex(pub usize);
 
@@ -109,7 +107,7 @@ pub fn determine_parameters_to_be_inferred<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>
     };
 
     // See README.md for a discussion on dep-graph management.
-    tcx.visit_all_item_likes_in_krate(|def_id| VarianceDepNode(def_id), &mut terms_cx);
+    tcx.hir.krate().visit_all_item_likes(&mut terms_cx);
 
     terms_cx
 }
@@ -139,7 +137,6 @@ fn lang_items(tcx: TyCtxt) -> Vec<(ast::NodeId, Vec<ty::Variance>)> {
 impl<'a, 'tcx> TermsContext<'a, 'tcx> {
     fn add_inferreds_for_item(&mut self,
                               item_id: ast::NodeId,
-                              has_self: bool,
                               generics: &hir::Generics) {
         //! Add "inferreds" for the generic parameters declared on this
         //! item. This has a lot of annoying parameters because we are
@@ -149,38 +146,17 @@ impl<'a, 'tcx> TermsContext<'a, 'tcx> {
         //!
 
         // NB: In the code below for writing the results back into the
-        // tcx, we rely on the fact that all inferreds for a particular
-        // item are assigned continuous indices.
-
-        let inferreds_on_entry = self.num_inferred();
-
-        if has_self {
-            self.add_inferred(item_id, 0, item_id);
-        }
+        // `CrateVariancesMap`, we rely on the fact that all inferreds
+        // for a particular item are assigned continuous indices.
 
-        for (i, p) in generics.lifetimes.iter().enumerate() {
+        for (p, i) in generics.lifetimes.iter().zip(0..) {
             let id = p.lifetime.id;
-            let i = has_self as usize + i;
             self.add_inferred(item_id, i, id);
         }
 
-        for (i, p) in generics.ty_params.iter().enumerate() {
-            let i = has_self as usize + generics.lifetimes.len() + i;
+        for (p, i) in generics.ty_params.iter().zip(generics.lifetimes.len()..) {
             self.add_inferred(item_id, i, p.id);
         }
-
-        // If this item has no type or lifetime parameters,
-        // then there are no variances to infer, so just
-        // insert an empty entry into the variance map.
-        // Arguably we could just leave the map empty in this
-        // case but it seems cleaner to be able to distinguish
-        // "invalid item id" from "item id with no
-        // parameters".
-        if self.num_inferred() == inferreds_on_entry {
-            let item_def_id = self.tcx.hir.local_def_id(item_id);
-            self.tcx.maps.variances_of.borrow_mut()
-                .insert(item_def_id, self.empty_variances.clone());
-        }
     }
 
     fn add_inferred(&mut self, item_id: ast::NodeId, index: usize, param_id: ast::NodeId) {
@@ -232,15 +208,10 @@ impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for TermsContext<'a, 'tcx> {
             hir::ItemEnum(_, ref generics) |
             hir::ItemStruct(_, ref generics) |
             hir::ItemUnion(_, ref generics) => {
-                self.add_inferreds_for_item(item.id, false, generics);
-            }
-            hir::ItemTrait(_, ref generics, ..) => {
-                // Note: all inputs for traits are ultimately
-                // constrained to be invariant. See `visit_item` in
-                // the impl for `ConstraintContext` in `constraints.rs`.
-                self.add_inferreds_for_item(item.id, true, generics);
+                self.add_inferreds_for_item(item.id, generics);
             }
 
+            hir::ItemTrait(..) |
             hir::ItemExternCrate(_) |
             hir::ItemUse(..) |
             hir::ItemDefaultImpl(..) |
diff --git a/src/librustc_typeck/variance/test.rs b/src/librustc_typeck/variance/test.rs
new file mode 100644
index 00000000000..1acadb7e772
--- /dev/null
+++ b/src/librustc_typeck/variance/test.rs
@@ -0,0 +1,41 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use rustc::hir;
+use rustc::hir::itemlikevisit::ItemLikeVisitor;
+use rustc::ty::TyCtxt;
+
+pub fn test_variance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
+    tcx.hir.krate().visit_all_item_likes(&mut VarianceTest { tcx });
+}
+
+struct VarianceTest<'a, 'tcx: 'a> {
+    tcx: TyCtxt<'a, 'tcx, 'tcx>
+}
+
+impl<'a, 'tcx> ItemLikeVisitor<'tcx> for VarianceTest<'a, 'tcx> {
+    fn visit_item(&mut self, item: &'tcx hir::Item) {
+        let item_def_id = self.tcx.hir.local_def_id(item.id);
+
+        // For unit testing: check for a special "rustc_variance"
+        // attribute and report an error with various results if found.
+        if self.tcx.has_attr(item_def_id, "rustc_variance") {
+            let variances_of = self.tcx.variances_of(item_def_id);
+            span_err!(self.tcx.sess,
+                      item.span,
+                      E0208,
+                      "{:?}",
+                      variances_of);
+        }
+    }
+
+    fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { }
+    fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { }
+}
diff --git a/src/librustdoc/Cargo.toml b/src/librustdoc/Cargo.toml
index 7caae51e889..0e8a6606ae7 100644
--- a/src/librustdoc/Cargo.toml
+++ b/src/librustdoc/Cargo.toml
@@ -21,6 +21,7 @@ rustc_errors = { path = "../librustc_errors" }
 rustc_lint = { path = "../librustc_lint" }
 rustc_metadata = { path = "../librustc_metadata" }
 rustc_resolve = { path = "../librustc_resolve" }
+rustc_typeck = { path = "../librustc_typeck" }
 rustc_trans = { path = "../librustc_trans" }
 serialize = { path = "../libserialize" }
 syntax = { path = "../libsyntax" }
diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs
index 78b96e1833b..2dde6d9d4ee 100644
--- a/src/librustdoc/clean/mod.rs
+++ b/src/librustdoc/clean/mod.rs
@@ -36,6 +36,7 @@ use rustc::ty::subst::Substs;
 use rustc::ty::{self, AdtKind};
 use rustc::middle::stability;
 use rustc::util::nodemap::{FxHashMap, FxHashSet};
+use rustc_typeck::hir_ty_to_ty;
 
 use rustc::hir;
 
@@ -1779,10 +1780,9 @@ impl Clean<Type> for hir::Ty {
             }
             TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
                 let mut def = Def::Err;
-                if let Some(ty) = cx.tcx.ast_ty_to_ty_cache.borrow().get(&self.id) {
-                    if let ty::TyProjection(proj) = ty.sty {
-                        def = Def::Trait(proj.trait_ref.def_id);
-                    }
+                let ty = hir_ty_to_ty(cx.tcx, self);
+                if let ty::TyProjection(proj) = ty.sty {
+                    def = Def::Trait(proj.trait_ref.def_id);
                 }
                 let trait_path = hir::Path {
                     span: self.span,
diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs
index 5879be08881..9e2d8516333 100644
--- a/src/librustdoc/core.rs
+++ b/src/librustdoc/core.rs
@@ -104,7 +104,8 @@ pub fn run_core(search_paths: SearchPaths,
                 externs: config::Externs,
                 input: Input,
                 triple: Option<String>,
-                maybe_sysroot: Option<PathBuf>) -> (clean::Crate, RenderInfo)
+                maybe_sysroot: Option<PathBuf>,
+                allow_warnings: bool) -> (clean::Crate, RenderInfo)
 {
     // Parse, resolve, and typecheck the given crate.
 
@@ -119,7 +120,7 @@ pub fn run_core(search_paths: SearchPaths,
         maybe_sysroot: maybe_sysroot,
         search_paths: search_paths,
         crate_types: vec![config::CrateTypeRlib],
-        lint_opts: vec![(warning_lint, lint::Allow)],
+        lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
         lint_cap: Some(lint::Allow),
         externs: externs,
         target_triple: triple.unwrap_or(config::host_triple().to_string()),
diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs
index 0f47265a1aa..5db82e23bbf 100644
--- a/src/librustdoc/html/format.rs
+++ b/src/librustdoc/html/format.rs
@@ -687,9 +687,9 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool,
             }
         }
         clean::Vector(ref t) if is_not_debug => {
-            primitive_link(f, PrimitiveType::Slice, &format!("["))?;
+            primitive_link(f, PrimitiveType::Slice, "[")?;
             fmt::Display::fmt(t, f)?;
-            primitive_link(f, PrimitiveType::Slice, &format!("]"))
+            primitive_link(f, PrimitiveType::Slice, "]")
         }
         clean::Vector(ref t) => write!(f, "[{:?}]", t),
         clean::FixedVector(ref t, ref s) if is_not_debug => {
diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs
index d6033a69da7..d08a7bde71c 100644
--- a/src/librustdoc/html/layout.rs
+++ b/src/librustdoc/html/layout.rs
@@ -137,7 +137,6 @@ r##"<!DOCTYPE html>
         window.rootPath = "{root_path}";
         window.currentCrate = "{krate}";
     </script>
-    <script src="{root_path}jquery.js"></script>
     <script src="{root_path}main.js"></script>
     <script defer src="{root_path}search-index.js"></script>
 </body>
diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs
index 85a28bbfbc6..ec4a23b0417 100644
--- a/src/librustdoc/html/markdown.rs
+++ b/src/librustdoc/html/markdown.rs
@@ -66,18 +66,47 @@ pub struct MarkdownHtml<'a>(pub &'a str, pub RenderType);
 /// A unit struct like `Markdown`, that renders only the first paragraph.
 pub struct MarkdownSummaryLine<'a>(pub &'a str);
 
-/// Returns Some(code) if `s` is a line that should be stripped from
-/// documentation but used in example code. `code` is the portion of
-/// `s` that should be used in tests. (None for lines that should be
-/// left as-is.)
-fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
+/// Controls whether a line will be hidden or shown in HTML output.
+///
+/// All lines are used in documentation tests.
+enum Line<'a> {
+    Hidden(&'a str),
+    Shown(&'a str),
+}
+
+impl<'a> Line<'a> {
+    fn for_html(self) -> Option<&'a str> {
+        match self {
+            Line::Shown(l) => Some(l),
+            Line::Hidden(_) => None,
+        }
+    }
+
+    fn for_code(self) -> &'a str {
+        match self {
+            Line::Shown(l) |
+            Line::Hidden(l) => l,
+        }
+    }
+}
+
+// FIXME: There is a minor inconsistency here. For lines that start with ##, we
+// have no easy way of removing a potential single space after the hashes, which
+// is done in the single # case. This inconsistency seems okay, if non-ideal. In
+// order to fix it we'd have to iterate to find the first non-# character, and
+// then reallocate to remove it; which would make us return a String.
+fn map_line(s: &str) -> Line {
     let trimmed = s.trim();
-    if trimmed == "#" {
-        Some("")
+    if trimmed.starts_with("##") {
+        Line::Shown(&trimmed[1..])
     } else if trimmed.starts_with("# ") {
-        Some(&trimmed[2..])
+        // # text
+        Line::Hidden(&trimmed[2..])
+    } else if trimmed == "#" {
+        // We cannot handle '#text' because it could be #[attr].
+        Line::Hidden("")
     } else {
-        None
+        Line::Shown(s)
     }
 }
 
@@ -148,9 +177,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
                 _ => {}
             }
         }
-        let lines = origtext.lines().filter(|l| {
-            stripped_filtered_line(*l).is_none()
-        });
+        let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
         let text = lines.collect::<Vec<&str>>().join("\n");
         PLAYGROUND.with(|play| {
             // insert newline to clearly separate it from the
@@ -160,9 +187,9 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
                 if url.is_empty() {
                     return None;
                 }
-                let test = origtext.lines().map(|l| {
-                    stripped_filtered_line(l).unwrap_or(l)
-                }).collect::<Vec<&str>>().join("\n");
+                let test = origtext.lines()
+                    .map(|l| map_line(l).for_code())
+                    .collect::<Vec<&str>>().join("\n");
                 let krate = krate.as_ref().map(|s| &**s);
                 let test = test::maketest(&test, krate, false,
                                         &Default::default());
@@ -543,9 +570,7 @@ pub fn render(w: &mut fmt::Formatter,
                 }
             };
 
-            let lines = origtext.lines().filter(|l| {
-                stripped_filtered_line(*l).is_none()
-            });
+            let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
             let text = lines.collect::<Vec<&str>>().join("\n");
             if rendered { return }
             PLAYGROUND.with(|play| {
@@ -556,9 +581,9 @@ pub fn render(w: &mut fmt::Formatter,
                     if url.is_empty() {
                         return None;
                     }
-                    let test = origtext.lines().map(|l| {
-                        stripped_filtered_line(l).unwrap_or(l)
-                    }).collect::<Vec<&str>>().join("\n");
+                    let test = origtext.lines()
+                        .map(|l| map_line(l).for_code())
+                        .collect::<Vec<&str>>().join("\n");
                     let krate = krate.as_ref().map(|s| &**s);
                     let test = test::maketest(&test, krate, false,
                                               &Default::default());
@@ -734,9 +759,7 @@ pub fn old_find_testable_code(doc: &str, tests: &mut ::test::Collector, position
             let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
             let text = str::from_utf8(text).unwrap();
-            let lines = text.lines().map(|l| {
-                stripped_filtered_line(l).unwrap_or(l)
-            });
+            let lines = text.lines().map(|l| map_line(l).for_code());
             let text = lines.collect::<Vec<&str>>().join("\n");
             let filename = tests.get_filename();
 
@@ -827,9 +850,7 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Sp
                     }
                 }
                 let offset = offset.unwrap_or(0);
-                let lines = test_s.lines().map(|l| {
-                    stripped_filtered_line(l).unwrap_or(l)
-                });
+                let lines = test_s.lines().map(|l| map_line(l).for_code());
                 let text = lines.collect::<Vec<&str>>().join("\n");
                 nb_lines += doc[prev_offset..offset].lines().count();
                 let line = tests.get_line() + (nb_lines - 1);
diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs
index 57d71e6c4e0..fa9315054a1 100644
--- a/src/librustdoc/html/render.rs
+++ b/src/librustdoc/html/render.rs
@@ -660,8 +660,6 @@ fn write_shared(cx: &Context,
     // Add all the static files. These may already exist, but we just
     // overwrite them anyway to make sure that they're fresh and up-to-date.
 
-    write(cx.dst.join("jquery.js"),
-          include_bytes!("static/jquery-2.1.4.min.js"))?;
     write(cx.dst.join("main.js"),
           include_bytes!("static/main.js"))?;
     write(cx.dst.join("rustdoc.css"),
diff --git a/src/librustdoc/html/static/COPYRIGHT.txt b/src/librustdoc/html/static/COPYRIGHT.txt
index 8773ce6bee9..c69861aa70a 100644
--- a/src/librustdoc/html/static/COPYRIGHT.txt
+++ b/src/librustdoc/html/static/COPYRIGHT.txt
@@ -27,11 +27,6 @@ included, and carry their own copyright notices and license terms:
     Licensed under the SIL Open Font License, Version 1.1.
     See Heuristica-LICENSE.txt.
 
-* jQuery (jquery-2.1.4.min.js):
-
-    Copyright 2005, 2015 jQuery Foundation, Inc.
-    Licensed under the MIT license (see LICENSE-MIT.txt).
-
 * rustdoc.css, main.js, and playpen.js:
 
     Copyright 2015 The Rust Developers.
diff --git a/src/librustdoc/html/static/jquery-2.1.4.min.js b/src/librustdoc/html/static/jquery-2.1.4.min.js
deleted file mode 100644
index 49990d6e145..00000000000
--- a/src/librustdoc/html/static/jquery-2.1.4.min.js
+++ /dev/null
@@ -1,4 +0,0 @@
-/*! jQuery v2.1.4 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
-!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b="length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){
-return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=l.createDocumentFragment(),b=a.appendChild(l.createElement("div")),c=l.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||l,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=l),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?Z:$):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=Z,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(g in a)this.on(g,b,c,a[g],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return n().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=$),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ia={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(oa(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qa[0].contentDocument,b.write(),b.close(),c=sa(a,b),qa.detach()),ra[a]=c),c}var ua=/^margin/,va=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wa=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)};function xa(a,b,c){var d,e,f,g,h=a.style;return c=c||wa(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),va.test(g)&&ua.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function ya(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d=l.documentElement,e=l.createElement("div"),f=l.createElement("div");if(f.style){f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===f.style.backgroundClip,e.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",e.appendChild(f);function g(){f.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",f.innerHTML="",d.appendChild(e);var g=a.getComputedStyle(f,null);b="1%"!==g.top,c="4px"===g.width,d.removeChild(e)}a.getComputedStyle&&n.extend(k,{pixelPosition:function(){return g(),b},boxSizingReliable:function(){return null==c&&g(),c},reliableMarginRight:function(){var b,c=f.appendChild(l.createElement("div"));return c.style.cssText=f.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",f.style.width="1px",d.appendChild(e),b=!parseFloat(a.getComputedStyle(c,null).marginRight),d.removeChild(e),f.removeChild(c),b}})}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var za=/^(none|table(?!-c[ea]).+)/,Aa=new RegExp("^("+Q+")(.*)$","i"),Ba=new RegExp("^([+-])=("+Q+")","i"),Ca={position:"absolute",visibility:"hidden",display:"block"},Da={letterSpacing:"0",fontWeight:"400"},Ea=["Webkit","O","Moz","ms"];function Fa(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Ea.length;while(e--)if(b=Ea[e]+c,b in a)return b;return d}function Ga(a,b,c){var d=Aa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Ha(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ia(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wa(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xa(a,b,f),(0>e||null==e)&&(e=a.style[b]),va.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Ha(a,b,c||(g?"border":"content"),d,f)+"px"}function Ja(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",ta(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xa(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Fa(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Ba.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Fa(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xa(a,b,d)),"normal"===e&&b in Da&&(e=Da[b]),""===c||c?(f=parseFloat(e),c===!0||n.isNumeric(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?za.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Ca,function(){return Ia(a,b,d)}):Ia(a,b,d):void 0},set:function(a,c,d){var e=d&&wa(a);return Ga(a,c,d?Ha(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=ya(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ua.test(a)||(n.cssHooks[a+b].set=Ga)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=wa(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Ja(this,!0)},hide:function(){return Ja(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?n(this).show():n(this).hide()})}});function Ka(a,b,c,d,e){return new Ka.prototype.init(a,b,c,d,e)}n.Tween=Ka,Ka.prototype={constructor:Ka,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ka.propHooks[this.prop];return a&&a.get?a.get(this):Ka.propHooks._default.get(this)},run:function(a){var b,c=Ka.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ka.propHooks._default.set(this),this}},Ka.prototype.init.prototype=Ka.prototype,Ka.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Ka.propHooks.scrollTop=Ka.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=Ka.prototype.init,n.fx.step={};var La,Ma,Na=/^(?:toggle|show|hide)$/,Oa=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pa=/queueHooks$/,Qa=[Va],Ra={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Oa.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Oa.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function Sa(){return setTimeout(function(){La=void 0}),La=n.now()}function Ta(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ua(a,b,c){for(var d,e=(Ra[b]||[]).concat(Ra["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Va(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?L.get(a,"olddisplay")||ta(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Na.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?ta(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ua(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wa(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xa(a,b,c){var d,e,f=0,g=Qa.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=La||Sa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:La||Sa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wa(k,j.opts.specialEasing);g>f;f++)if(d=Qa[f].call(j,a,k,j.opts))return d;return n.map(k,Ua,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(Xa,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Ra[c]=Ra[c]||[],Ra[c].unshift(b)},prefilter:function(a,b){b?Qa.unshift(a):Qa.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=Xa(this,n.extend({},a),f);(e||L.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pa.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Ta(b,!0),a,d,e)}}),n.each({slideDown:Ta("show"),slideUp:Ta("hide"),slideToggle:Ta("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(La=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),La=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ma||(Ma=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(Ma),Ma=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a=l.createElement("input"),b=l.createElement("select"),c=b.appendChild(l.createElement("option"));a.type="checkbox",k.checkOn=""!==a.value,k.optSelected=c.selected,b.disabled=!0,k.optDisabled=!c.disabled,a=l.createElement("input"),a.value="t",a.type="radio",k.radioValue="t"===a.value}();var Ya,Za,$a=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return J(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Za:Ya)),
-void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Za={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$a[b]||n.find.attr;$a[b]=function(a,b,d){var e,f;return d||(f=$a[b],$a[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$a[b]=f),e}});var _a=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_a.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ab=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ab," ").indexOf(b)>=0)return!0;return!1}});var bb=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var cb=n.now(),db=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&n.error("Invalid XML: "+a),b};var eb=/#.*$/,fb=/([?&])_=[^&]*/,gb=/^(.*?):[ \t]*([^\r\n]*)$/gm,hb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,ib=/^(?:GET|HEAD)$/,jb=/^\/\//,kb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,lb={},mb={},nb="*/".concat("*"),ob=a.location.href,pb=kb.exec(ob.toLowerCase())||[];function qb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function rb(a,b,c,d){var e={},f=a===mb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function sb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function tb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function ub(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ob,type:"GET",isLocal:hb.test(pb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":nb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?sb(sb(a,n.ajaxSettings),b):sb(n.ajaxSettings,a)},ajaxPrefilter:qb(lb),ajaxTransport:qb(mb),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=gb.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return c&&c.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||ob)+"").replace(eb,"").replace(jb,pb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=kb.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===pb[1]&&h[2]===pb[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(pb[3]||("http:"===pb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),rb(lb,k,b,v),2===t)return v;i=n.event&&k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!ib.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(db.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=fb.test(d)?d.replace(fb,"$1_="+cb++):d+(db.test(d)?"&":"?")+"_="+cb++)),k.ifModified&&(n.lastModified[d]&&v.setRequestHeader("If-Modified-Since",n.lastModified[d]),n.etag[d]&&v.setRequestHeader("If-None-Match",n.etag[d])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+nb+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=rb(mb,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=tb(k,v,f)),u=ub(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(n.etag[d]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var vb=/%20/g,wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&").replace(vb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Bb=0,Cb={},Db={0:200,1223:204},Eb=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Cb)Cb[a]()}),k.cors=!!Eb&&"withCredentials"in Eb,k.ajax=Eb=!!Eb,n.ajaxTransport(function(a){var b;return k.cors||Eb&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Bb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Cb[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Db[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Cb[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=n("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),l.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Fb=[],Gb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Fb.pop()||n.expando+"_"+cb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Gb.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Gb,"$1"+e):b.jsonp!==!1&&(b.url+=(db.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Fb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||l;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var Hb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Hb)return Hb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var Ib=a.document.documentElement;function Jb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Jb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Ib;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ib})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;n.fn[b]=function(e){return J(this,function(b,e,f){var g=Jb(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=ya(k.pixelPosition,function(a,c){return c?(c=xa(a,b),va.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Kb=a.jQuery,Lb=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Lb),b&&a.jQuery===n&&(a.jQuery=Kb),n},typeof b===U&&(a.jQuery=a.$=n),n});
diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js
index cf9408abf5e..fbc7615588e 100644
--- a/src/librustdoc/html/static/main.js
+++ b/src/librustdoc/html/static/main.js
@@ -37,10 +37,63 @@
                      "associatedconstant",
                      "union"];
 
+    function hasClass(elem, className) {
+        if (elem && className && elem.className) {
+            var elemClass = elem.className;
+            var start = elemClass.indexOf(className);
+            if (start == -1) {
+                return false;
+            } else if (elemClass.length == className.length) {
+                return true;
+            } else {
+                if (start > 0 && elemClass[start - 1] != ' ') {
+                    return false;
+                }
+                var end = start + className.length;
+                if (end < elemClass.length && elemClass[end] != ' ') {
+                    return false;
+                }
+                return true;
+            }
+        }
+        return false;
+    }
+
+    function addClass(elem, className) {
+        if (elem && className && !hasClass(elem, className)) {
+            if (elem.className && elem.className.length > 0) {
+                elem.className += ' ' + className;
+            } else {
+                elem.className = className;
+            }
+        }
+    }
+
+    function removeClass(elem, className) {
+        if (elem && className && elem.className) {
+            elem.className = (" " + elem.className + " ").replace(" " + className + " ", " ")
+                                                         .trim();
+        }
+    }
+
+    function onEach(arr, func) {
+        if (arr && arr.length > 0 && func) {
+            for (var i = 0; i < arr.length; i++) {
+                func(arr[i]);
+            }
+        }
+    }
+
+    function isHidden(elem) {
+        return (elem.offsetParent === null)
+    }
+
     // used for special search precedence
     var TY_PRIMITIVE = itemTypes.indexOf("primitive");
 
-    $('.js-only').removeClass('js-only');
+    onEach(document.getElementsByClassName('js-only'), function(e) {
+        removeClass(e, 'js-only');
+    });
 
     function getQueryStringParams() {
         var params = {};
@@ -65,18 +118,28 @@
             from = parseInt(match[1], 10);
             to = Math.min(50000, parseInt(match[2] || match[1], 10));
             from = Math.min(from, to);
-            if ($('#' + from).length === 0) {
+            var elem = document.getElementById(from);
+            if (!elem) {
                 return;
             }
-            if (ev === null) { $('#' + from)[0].scrollIntoView(); };
-            $('.line-numbers span').removeClass('line-highlighted');
+            if (ev === null) {
+                var x = document.getElementById(from);
+                if (x) {
+                    x.scrollIntoView();
+                }
+            };
+            onEach(document.getElementsByClassName('line-numbers'), function(e) {
+                onEach(e.getElementsByTagName('span'), function(i_e) {
+                    removeClass(i_e, 'line-highlighted');
+                });
+            })
             for (i = from; i <= to; ++i) {
-                $('#' + i).addClass('line-highlighted');
+                addClass(document.getElementById(i), 'line-highlighted');
             }
         }
     }
     highlightSourceLines(null);
-    $(window).on('hashchange', highlightSourceLines);
+    window.onhashchange = highlightSourceLines;
 
     // Gets the human-readable string for the virtual-key code of the
     // given KeyboardEvent, ev.
@@ -99,23 +162,25 @@
     }
 
     function handleShortcut(ev) {
-        if (document.activeElement.tagName == "INPUT")
+        if (document.activeElement.tagName === "INPUT")
             return;
 
         // Don't interfere with browser shortcuts
         if (ev.ctrlKey || ev.altKey || ev.metaKey)
             return;
 
+        var help = document.getElementById("help");
         switch (getVirtualKey(ev)) {
         case "Escape":
-            if (!$("#help").hasClass("hidden")) {
+            var search = document.getElementById("search");
+            if (!hasClass(help, "hidden")) {
                 ev.preventDefault();
-                $("#help").addClass("hidden");
-                $("body").removeClass("blur");
-            } else if (!$("#search").hasClass("hidden")) {
+                addClass(help, "hidden");
+                removeClass(document.body, "blur");
+            } else if (!hasClass(search, "hidden")) {
                 ev.preventDefault();
-                $("#search").addClass("hidden");
-                $("#main").removeClass("hidden");
+                addClass(search, "hidden");
+                removeClass(document.getElementById("main"), "hidden");
             }
             break;
 
@@ -131,42 +196,76 @@
             break;
 
         case "?":
-            if (ev.shiftKey && $("#help").hasClass("hidden")) {
+            if (ev.shiftKey && hasClass(help, "hidden")) {
                 ev.preventDefault();
-                $("#help").removeClass("hidden");
-                $("body").addClass("blur");
+                removeClass(help, "hidden");
+                addClass(document.body, "blur");
             }
             break;
         }
     }
 
-    $(document).on("keypress", handleShortcut);
-    $(document).on("keydown", handleShortcut);
-    $(document).on("click", function(ev) {
-        if (!$(ev.target).closest("#help > div").length) {
-            $("#help").addClass("hidden");
-            $("body").removeClass("blur");
-        }
-    });
+    document.onkeypress = handleShortcut;
+    document.onkeydown = handleShortcut;
+    document.onclick = function(ev) {
+        if (hasClass(ev.target, 'collapse-toggle')) {
+            collapseDocs(ev.target);
+        } else if (hasClass(ev.target.parentNode, 'collapse-toggle')) {
+            collapseDocs(ev.target.parentNode);
+        } else if (ev.target.tagName === 'SPAN' && hasClass(ev.target.parentNode, 'line-numbers')) {
+            var prev_id = 0;
+
+            function set_fragment(name) {
+                if (browserSupportsHistoryApi()) {
+                    history.replaceState(null, null, '#' + name);
+                    window.hashchange();
+                } else {
+                    location.replace('#' + name);
+                }
+            }
 
-    $('.version-selector').on('change', function() {
-        var i, match,
-            url = document.location.href,
-            stripped = '',
-            len = rootPath.match(/\.\.\//g).length + 1;
+            var cur_id = parseInt(ev.target.id, 10);
 
-        for (i = 0; i < len; ++i) {
-            match = url.match(/\/[^\/]*$/);
-            if (i < len - 1) {
-                stripped = match[0] + stripped;
+            if (ev.shiftKey && prev_id) {
+                if (prev_id > cur_id) {
+                    var tmp = prev_id;
+                    prev_id = cur_id;
+                    cur_id = tmp;
+                }
+
+                set_fragment(prev_id + '-' + cur_id);
+            } else {
+                prev_id = cur_id;
+
+                set_fragment(cur_id);
             }
-            url = url.substring(0, url.length - match[0].length);
+        } else if (!hasClass(document.getElementById("help"), "hidden")) {
+            addClass(document.getElementById("help"), "hidden");
+            removeClass(document.body, "blur");
         }
+    };
 
-        url += '/' + $('.version-selector').val() + stripped;
+    var x = document.getElementsByClassName('version-selector');
+    if (x.length > 0) {
+        x[0].onchange = function() {
+            var i, match,
+                url = document.location.href,
+                stripped = '',
+                len = rootPath.match(/\.\.\//g).length + 1;
 
-        document.location.href = url;
-    });
+            for (i = 0; i < len; ++i) {
+                match = url.match(/\/[^\/]*$/);
+                if (i < len - 1) {
+                    stripped = match[0] + stripped;
+                }
+                url = url.substring(0, url.length - match[0].length);
+            }
+
+            url += '/' + document.getElementsByClassName('version-selector')[0].value + stripped;
+
+            document.location.href = url;
+        };
+    }
 
     /**
      * A function to compute the Levenshtein distance between two strings
@@ -214,8 +313,8 @@
         // but only if the input bar is empty. This avoid the obnoxious issue
         // where you start trying to do a search, and the index loads, and
         // suddenly your search is gone!
-        if ($(".search-input")[0].value === "") {
-            $(".search-input")[0].value = params.search || '';
+        if (document.getElementsByClassName("search-input")[0].value === "") {
+            document.getElementsByClassName("search-input")[0].value = params.search || '';
         }
 
         /**
@@ -484,7 +583,8 @@
         }
 
         function getQuery() {
-            var matches, type, query, raw = $('.search-input').val();
+            var matches, type, query, raw =
+                document.getElementsByClassName('search-input')[0].value;
             query = raw;
 
             matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
@@ -502,54 +602,92 @@
         }
 
         function initSearchNav() {
-            var hoverTimeout, $results = $('.search-results .result');
+            var hoverTimeout;
 
-            $results.on('click', function() {
-                var dst = $(this).find('a')[0];
+            var click_func = function(e) {
+                var el = e.target;
+                // to retrieve the real "owner" of the event.
+                while (el.tagName !== 'TR') {
+                    el = el.parentNode;
+                }
+                var dst = e.target.getElementsByTagName('a');
+                if (dst.length < 1) {
+                    return;
+                }
+                dst = dst[0];
                 if (window.location.pathname === dst.pathname) {
-                    $('#search').addClass('hidden');
-                    $('#main').removeClass('hidden');
+                    addClass(document.getElementById('search'), 'hidden');
+                    removeClass(document.getElementById('main'), 'hidden');
                     document.location.href = dst.href;
                 }
-            }).on('mouseover', function() {
-                var $el = $(this);
+            };
+            var mouseover_func = function(e) {
+                var el = e.target;
+                // to retrieve the real "owner" of the event.
+                while (el.tagName !== 'TR') {
+                    el = el.parentNode;
+                }
                 clearTimeout(hoverTimeout);
                 hoverTimeout = setTimeout(function() {
-                    $results.removeClass('highlighted');
-                    $el.addClass('highlighted');
+                    onEach(document.getElementsByClassName('search-results'), function(e) {
+                        onEach(e.getElementsByClassName('result'), function(i_e) {
+                            removeClass(i_e, 'highlighted');
+                        });
+                    });
+                    addClass(el, 'highlighted');
                 }, 20);
+            };
+            onEach(document.getElementsByClassName('search-results'), function(e) {
+                onEach(e.getElementsByClassName('result'), function(i_e) {
+                    i_e.onclick = click_func;
+                    i_e.onmouseover = mouseover_func;
+                });
             });
 
-            $(document).off('keydown.searchnav');
-            $(document).on('keydown.searchnav', function(e) {
-                var $active = $results.filter('.highlighted');
+            var search_input = document.getElementsByClassName('search-input')[0];
+            search_input.onkeydown = null;
+            search_input.onkeydown = function(e) {
+                var actives = [];
+                onEach(document.getElementsByClassName('search-results'), function(e) {
+                    onEach(document.getElementsByClassName('highlighted'), function(e) {
+                        actives.push(e);
+                    });
+                });
 
                 if (e.which === 38) { // up
-                    if (!$active.length || !$active.prev()) {
+                    if (!actives.length || !actives[0].previousElementSibling) {
                         return;
                     }
 
-                    $active.prev().addClass('highlighted');
-                    $active.removeClass('highlighted');
+                    addClass(actives[0].previousElementSibling, 'highlighted');
+                    removeClass(actives[0], 'highlighted');
                 } else if (e.which === 40) { // down
-                    if (!$active.length) {
-                        $results.first().addClass('highlighted');
-                    } else if ($active.next().length) {
-                        $active.next().addClass('highlighted');
-                        $active.removeClass('highlighted');
+                    if (!actives.length) {
+                        var results = document.getElementsByClassName('search-results');
+                        if (results.length > 0) {
+                            var res = results[0].getElementsByClassName('result');
+                            if (res.length > 0) {
+                                addClass(res[0], 'highlighted');
+                            }
+                        }
+                    } else if (actives[0].nextElementSibling) {
+                        addClass(actives[0].nextElementSibling, 'highlighted');
+                        removeClass(actives[0], 'highlighted');
                     }
                 } else if (e.which === 13) { // return
-                    if ($active.length) {
-                        document.location.href = $active.find('a').prop('href');
+                    if (actives.length) {
+                        document.location.href = actives[0].getElementsByTagName('a')[0].href;
                     }
-                } else {
-                  $active.removeClass('highlighted');
+                } else if (actives.length > 0) {
+                    removeClass(actives[0], 'highlighted');
                 }
-            });
+            };
         }
 
         function escape(content) {
-            return $('<h1/>').text(content).html();
+            let h1 = document.createElement('h1');
+            h1.textContent = content;
+            return h1.innerHTML;
         }
 
         function showResults(results) {
@@ -619,10 +757,19 @@
             }
 
             output += "</p>";
-            $('#main.content').addClass('hidden');
-            $('#search.content').removeClass('hidden').html(output);
-            $('#search .desc').width($('#search').width() - 40 -
-                $('#search td:first-child').first().width());
+            addClass(document.getElementById('main'), 'hidden');
+            var search = document.getElementById('search');
+            removeClass(search, 'hidden');
+            search.innerHTML = output;
+            var tds = search.getElementsByTagName('td');
+            var td_width = 0;
+            if (tds.length > 0) {
+                td_width = tds[0].offsetWidth;
+            }
+            var width = search.offsetWidth - 40 - td_width;
+            onEach(search.getElementsByClassName('desc'), function(e) {
+                e.style.width = width + 'px';
+            });
             initSearchNav();
         }
 
@@ -645,17 +792,15 @@
             }
 
             // Update document title to maintain a meaningful browser history
-            $(document).prop("title", "Results for " + query.query + " - Rust");
+            document.title = "Results for " + query.query + " - Rust";
 
             // Because searching is incremental by character, only the most
             // recent search query is added to the browser history.
             if (browserSupportsHistoryApi()) {
                 if (!history.state && !params.search) {
-                    history.pushState(query, "", "?search=" +
-                                                encodeURIComponent(query.raw));
+                    history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
                 } else {
-                    history.replaceState(query, "", "?search=" +
-                                                encodeURIComponent(query.raw));
+                    history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
                 }
             }
 
@@ -744,49 +889,68 @@
 
         function startSearch() {
             var searchTimeout;
-            $(".search-input").on("keyup input",function() {
+            var callback = function() {
+                var search_input = document.getElementsByClassName('search-input');
+                if (search_input.length < 1) { return; }
+                search_input = search_input[0];
                 clearTimeout(searchTimeout);
-                if ($(this).val().length === 0) {
+                if (search_input.value.length === 0) {
                     if (browserSupportsHistoryApi()) {
                         history.replaceState("", "std - Rust", "?search=");
                     }
-                    $('#main.content').removeClass('hidden');
-                    $('#search.content').addClass('hidden');
+                    var main = document.getElementById('main');
+                    if (hasClass(main, 'content')) {
+                        removeClass(main, 'hidden');
+                    }
+                    var search_c = document.getElementById('search');
+                    if (hasClass(search_c, 'content')) {
+                        addClass(search_c, 'hidden');
+                    }
                 } else {
                     searchTimeout = setTimeout(search, 500);
                 }
-            });
-            $('.search-form').on('submit', function(e){
+            };
+            var search_input = document.getElementsByClassName("search-input")[0];
+            search_input.onkeyup = callback;
+            search_input.oninput = callback;
+            document.getElementsByClassName("search-form")[0].onsubmit = function(e){
                 e.preventDefault();
                 clearTimeout(searchTimeout);
                 search();
-            });
-            $('.search-input').on('change paste', function(e) {
+            };
+            search_input.onchange = function(e) {
                 // Do NOT e.preventDefault() here. It will prevent pasting.
                 clearTimeout(searchTimeout);
                 // zero-timeout necessary here because at the time of event handler execution the
                 // pasted content is not in the input field yet. Shouldn’t make any difference for
                 // change, though.
                 setTimeout(search, 0);
-            });
+            };
+            search_input.onpaste = search_input.onchange;
 
             // Push and pop states are used to add search results to the browser
             // history.
             if (browserSupportsHistoryApi()) {
                 // Store the previous <title> so we can revert back to it later.
-                var previousTitle = $(document).prop("title");
+                var previousTitle = document.title;
 
-                $(window).on('popstate', function(e) {
+                window.onpopstate = function(e) {
                     var params = getQueryStringParams();
                     // When browsing back from search results the main page
                     // visibility must be reset.
                     if (!params.search) {
-                        $('#main.content').removeClass('hidden');
-                        $('#search.content').addClass('hidden');
+                        var main = document.getElementById('main');
+                        if (hasClass(main, 'content')) {
+                            removeClass(main, 'hidden');
+                        }
+                        var search = document.getElementById('search');
+                        if (hasClass(main, 'content')) {
+                            addClass(main, 'hidden');
+                        }
                     }
                     // Revert to the previous title manually since the History
                     // API ignores the title parameter.
-                    $(document).prop("title", previousTitle);
+                    document.title = previousTitle;
                     // When browsing forward to search results the previous
                     // search will be repeated, so the currentResults are
                     // cleared to ensure the search is successful.
@@ -795,14 +959,14 @@
                     // perform the search. This will empty the bar if there's
                     // nothing there, which lets you really go back to a
                     // previous state with nothing in the bar.
-                    $('.search-input').val(params.search);
+                    document.getElementsByClassName('search-input')[0].value = params.search;
                     // Some browsers fire 'onpopstate' for every page load
                     // (Chrome), while others fire the event only when actually
                     // popping a state (Firefox), which is why search() is
                     // called both here and at the end of the startSearch()
                     // function.
                     search();
-                });
+                };
             }
             search();
         }
@@ -812,10 +976,12 @@
 
         // Draw a convenient sidebar of known crates if we have a listing
         if (rootPath === '../') {
-            var sidebar = $('.sidebar');
-            var div = $('<div>').attr('class', 'block crate');
-            div.append($('<h3>').text('Crates'));
-            var ul = $('<ul>').appendTo(div);
+            var sidebar = document.getElementsByClassName('sidebar')[0];
+            var div = document.createElement('div');
+            div.className = 'block crate';
+            div.innerHTML = '<h3>Crates</h3>';
+            var ul = document.createElement('ul');
+            div.appendChild(ul);
 
             var crates = [];
             for (var crate in rawSearchIndex) {
@@ -828,12 +994,17 @@
                 if (crates[i] === window.currentCrate) {
                     klass += ' current';
                 }
-                var link = $('<a>', {'href': '../' + crates[i] + '/index.html',
-                                     'title': rawSearchIndex[crates[i]].doc,
-                                     'class': klass}).text(crates[i]);
-                ul.append($('<li>').append(link));
+                var link = document.createElement('a');
+                link.href = '../' + crates[i] + '/index.html';
+                link.title = rawSearchIndex[crates[i]].doc;
+                link.className = klass;
+                link.textContent = crates[i];
+
+                var li = document.createElement('li');
+                li.appendChild(link);
+                ul.appendChild(li);
             }
-            sidebar.append(div);
+            sidebar.appendChild(div);
         }
     }
 
@@ -841,16 +1012,19 @@
 
     // delayed sidebar rendering.
     function initSidebarItems(items) {
-        var sidebar = $('.sidebar');
+        var sidebar = document.getElementsByClassName('sidebar')[0];
         var current = window.sidebarCurrent;
 
         function block(shortty, longty) {
             var filtered = items[shortty];
             if (!filtered) { return; }
 
-            var div = $('<div>').attr('class', 'block ' + shortty);
-            div.append($('<h3>').text(longty));
-            var ul = $('<ul>').appendTo(div);
+            var div = document.createElement('div');
+            div.className = 'block ' + shortty;
+            var h3 = document.createElement('h3');
+            h3.textContent = longty;
+            div.appendChild(h3);
+            var ul = document.createElement('ul');
 
             for (var i = 0; i < filtered.length; ++i) {
                 var item = filtered[i];
@@ -867,12 +1041,17 @@
                 } else {
                     path = shortty + '.' + name + '.html';
                 }
-                var link = $('<a>', {'href': current.relpath + path,
-                                     'title': desc,
-                                     'class': klass}).text(name);
-                ul.append($('<li>').append(link));
+                var link = document.createElement('a');
+                link.href = current.relpath + path;
+                link.title = desc;
+                link.className = klass;
+                link.textContent = name;
+                var li = document.createElement('li');
+                li.appendChild(link);
+                ul.appendChild(li);
             }
-            sidebar.append(div);
+            div.appendChild(ul);
+            sidebar.appendChild(div);
         }
 
         block("primitive", "Primitive Types");
@@ -890,21 +1069,25 @@
     window.initSidebarItems = initSidebarItems;
 
     window.register_implementors = function(imp) {
-        var list = $('#implementors-list');
+        var list = document.getElementById('implementors-list');
         var libs = Object.getOwnPropertyNames(imp);
         for (var i = 0; i < libs.length; ++i) {
             if (libs[i] === currentCrate) { continue; }
             var structs = imp[libs[i]];
             for (var j = 0; j < structs.length; ++j) {
-                var code = $('<code>').append(structs[j]);
-                $.each(code.find('a'), function(idx, a) {
-                    var href = $(a).attr('href');
+                var code = document.createElement('code');
+                code.innerHTML = structs[j];
+
+                var x = code.getElementsByTagName('a');
+                for (var i = 0; i < x.length; i++) {
+                    var href = x[i].href;
                     if (href && href.indexOf('http') !== 0) {
-                        $(a).attr('href', rootPath + href);
+                        x[i].href = rootPath + href;
                     }
-                });
-                var li = $('<li>').append(code);
-                list.append(li);
+                }
+                var li = document.createElement('li');
+                li.appendChild(code);
+                list.appendChild(li);
             }
         }
     };
@@ -922,146 +1105,186 @@
         return "\u2212"; // "\u2212" is '−' minus sign
     }
 
+    function onEveryMatchingChild(elem, className, func) {
+        if (elem && className && func) {
+            for (var i = 0; i < elem.childNodes.length; i++) {
+                if (hasClass(elem.childNodes[i], className)) {
+                    func(elem.childNodes[i]);
+                } else {
+                    onEveryMatchingChild(elem.childNodes[i], className, func);
+                }
+            }
+        }
+    }
+
     function toggleAllDocs() {
-        var toggle = $("#toggle-all-docs");
-        if (toggle.hasClass("will-expand")) {
-            toggle.removeClass("will-expand");
-            toggle.children(".inner").text(labelForToggleButton(false));
-            toggle.attr("title", "collapse all docs");
-            $(".docblock").show();
-            $(".toggle-label").hide();
-            $(".toggle-wrapper").removeClass("collapsed");
-            $(".collapse-toggle").children(".inner").text(labelForToggleButton(false));
+        var toggle = document.getElementById("toggle-all-docs");
+        if (hasClass(toggle, "will-expand")) {
+            removeClass(toggle, "will-expand");
+            onEveryMatchingChild(toggle, "inner", function(e) {
+                e.innerHTML = labelForToggleButton(false);
+            });
+            toggle.title = "collapse all docs";
+            onEach(document.getElementsByClassName("docblock"), function(e) {
+                e.style.display = 'block';
+            });
+            onEach(document.getElementsByClassName("toggle-label"), function(e) {
+                e.style.display = 'none';
+            });
+            onEach(document.getElementsByClassName("toggle-wrapper"), function(e) {
+                removeClass(e, "collapsed");
+            });
+            onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
+                onEveryMatchingChild(e, "inner", function(i_e) {
+                    i_e.innerHTML = labelForToggleButton(false);
+                });
+            });
         } else {
-            toggle.addClass("will-expand");
-            toggle.children(".inner").text(labelForToggleButton(true));
-            toggle.attr("title", "expand all docs");
-            $(".docblock").hide();
-            $(".toggle-label").show();
-            $(".toggle-wrapper").addClass("collapsed");
-            $(".collapse-toggle").children(".inner").text(labelForToggleButton(true));
+            addClass(toggle, "will-expand");
+            onEveryMatchingChild(toggle, "inner", function(e) {
+                e.innerHTML = labelForToggleButton(true);
+            });
+            toggle.title = "expand all docs";
+            onEach(document.getElementsByClassName("docblock"), function(e) {
+                e.style.display = 'none';
+            });
+            onEach(document.getElementsByClassName("toggle-label"), function(e) {
+                e.style.display = 'inline-block';
+            });
+            onEach(document.getElementsByClassName("toggle-wrapper"), function(e) {
+                addClass(e, "collapsed");
+            });
+            onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
+                onEveryMatchingChild(e, "inner", function(i_e) {
+                    i_e.innerHTML = labelForToggleButton(true);
+                });
+            });
         }
     }
 
-    function collapseDocs(toggle, animate) {
-        var relatedDoc = toggle.parent().next();
-        if (relatedDoc.is(".stability")) {
-            relatedDoc = relatedDoc.next();
+    function collapseDocs(toggle) {
+        if (!toggle || !toggle.parentNode) {
+            return;
         }
-        if (relatedDoc.is(".docblock")) {
-            if (relatedDoc.is(":visible")) {
-                if (animate === true) {
-                    relatedDoc.slideUp({
-                        duration: 'fast',
-                        easing: 'linear',
-                        complete: function() {
-                            toggle.children(".toggle-label").fadeIn();
-                            toggle.parent(".toggle-wrapper").addClass("collapsed");
-                            toggle.children(".inner").text(labelForToggleButton(true));
-                        },
-                    });
-                } else {
-                    relatedDoc.hide();
-                    toggle.children(".toggle-label").show();
-                    toggle.parent(".toggle-wrapper").addClass("collapsed");
-                    toggle.children(".inner").text(labelForToggleButton(true));
-                }
+        var relatedDoc = toggle.parentNode.nextElementSibling;
+        if (hasClass(relatedDoc, "stability")) {
+            relatedDoc = relatedDoc.nextElementSibling;
+        }
+        if (hasClass(relatedDoc, "docblock")) {
+            if (!isHidden(relatedDoc)) {
+                relatedDoc.style.display = 'none';
+                onEach(toggle.childNodes, function(e) {
+                    if (hasClass(e, 'toggle-label')) {
+                        e.style.display = 'inline-block';
+                    }
+                    if (hasClass(e, 'inner')) {
+                        e.innerHTML = labelForToggleButton(true);
+                    }
+                });
+                addClass(toggle.parentNode, 'collapsed');
             } else {
-                relatedDoc.slideDown({duration: 'fast', easing: 'linear'});
-                toggle.parent(".toggle-wrapper").removeClass("collapsed");
-                toggle.children(".inner").text(labelForToggleButton(false));
-                toggle.children(".toggle-label").hide();
+                relatedDoc.style.display = 'block';
+                removeClass(toggle.parentNode, 'collapsed');
+                onEach(toggle.childNodes, function(e) {
+                    if (hasClass(e, 'toggle-label')) {
+                        e.style.display = 'none';
+                    }
+                    if (hasClass(e, 'inner')) {
+                        e.innerHTML = labelForToggleButton(false);
+                    }
+                });
             }
         }
     }
 
-    $("#toggle-all-docs").on("click", toggleAllDocs);
+    var x = document.getElementById('toggle-all-docs');
+    if (x) {
+        x.onclick = toggleAllDocs;
+    }
 
-    $(document).on("click", ".collapse-toggle", function() {
-        collapseDocs($(this), true)
-    });
+    function insertAfter(newNode, referenceNode) {
+        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
+    }
 
-    $(function() {
-        var toggle = $("<a/>", {'href': 'javascript:void(0)', 'class': 'collapse-toggle'})
-            .html("[<span class='inner'></span>]");
-        toggle.children(".inner").text(labelForToggleButton(false));
+    var toggle = document.createElement('a');
+    toggle.href = 'javascript:void(0)';
+    toggle.className = 'collapse-toggle';
+    toggle.innerHTML = "[<span class='inner'>"+labelForToggleButton(false)+"</span>]";
 
-        $(".method, .impl-items > .associatedconstant").each(function() {
-            if ($(this).next().is(".docblock") ||
-                ($(this).next().is(".stability") && $(this).next().next().is(".docblock"))) {
-                    $(this).children().last().after(toggle.clone());
-            }
-        });
+    var func = function(e) {
+        var next = e.nextElementSibling;
+        if (!next) {
+            return;
+        }
+        if (hasClass(next, 'docblock') ||
+            (hasClass(next, 'stability') &&
+             hasClass(next.nextElementSibling, 'docblock'))) {
+            insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
+        }
+    }
+    onEach(document.getElementsByClassName('method'), func);
+    onEach(document.getElementsByClassName('impl-items'), function(e) {
+        onEach(e.getElementsByClassName('associatedconstant'), func);
+    });
 
-        var mainToggle =
-            $(toggle.clone()).append(
-                $('<span/>', {'class': 'toggle-label'})
-                    .css('display', 'none')
-                    .html('&nbsp;Expand&nbsp;description'));
-        var wrapper = $("<div class='toggle-wrapper'>").append(mainToggle);
-        $("#main > .docblock").before(wrapper);
-
-        $(".docblock.autohide").each(function() {
-            var wrap = $(this).prev();
-            if (wrap.is(".toggle-wrapper")) {
-                var toggle = wrap.children().first();
-                if ($(this).children().first().is("h3")) {
-                    toggle.children(".toggle-label")
-                          .text(" Show " + $(this).children().first().text());
-                }
-                $(this).hide();
-                wrap.addClass("collapsed");
-                toggle.children(".inner").text(labelForToggleButton(true));
-                toggle.children(".toggle-label").show();
-            }
-        });
+    var span = document.createElement('span');
+    span.className = 'toggle-label';
+    span.style.display = 'none';
+    span.innerHTML = '&nbsp;Expand&nbsp;description';
 
-        var mainToggle =
-            $(toggle).append(
-                $('<span/>', {'class': 'toggle-label'})
-                    .css('display', 'none')
-                    .html('&nbsp;Expand&nbsp;attributes'));
-        var wrapper = $("<div class='toggle-wrapper toggle-attributes'>").append(mainToggle);
-        $("#main > pre > .attributes").each(function() {
-            $(this).before(wrapper);
-            collapseDocs($($(this).prev().children()[0]), false);
-        });
-    });
+    var mainToggle = toggle.cloneNode(true);
+    mainToggle.appendChild(span);
 
-    $('pre.line-numbers').on('click', 'span', function() {
-        var prev_id = 0;
+    var wrapper = document.createElement('div');
+    wrapper.className = 'toggle-wrapper';
+    wrapper.appendChild(mainToggle);
 
-        function set_fragment(name) {
-            if (browserSupportsHistoryApi()) {
-                history.replaceState(null, null, '#' + name);
-                $(window).trigger('hashchange');
-            } else {
-                location.replace('#' + name);
-            }
+    onEach(document.getElementById('main').getElementsByClassName('docblock'), function(e) {
+        if (e.parentNode.id === "main") {
+            e.parentNode.insertBefore(wrapper, e);
         }
+    });
 
-        return function(ev) {
-            var cur_id = parseInt(ev.target.id, 10);
-
-            if (ev.shiftKey && prev_id) {
-                if (prev_id > cur_id) {
-                    var tmp = prev_id;
-                    prev_id = cur_id;
-                    cur_id = tmp;
+    onEach(document.getElementsByClassName('docblock'), function(e) {
+        if (hasClass(e, 'autohide')) {
+            var wrap = e.previousElementSibling;
+            if (wrap && hasClass(wrap, 'toggle-wrapper')) {
+                var toggle = wrap.childNodes[0];
+                if (e.childNodes[0].tagName === 'H3') {
+                    onEach(toggle.getElementsByClassName('toggle-label'), function(i_e) {
+                        i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
+                    });
                 }
-
-                set_fragment(prev_id + '-' + cur_id);
-            } else {
-                prev_id = cur_id;
-
-                set_fragment(cur_id);
+                e.style.display = 'none';
+                addClass(wrap, 'collapsed');
+                onEach(toggle.getElementsByClassName('inner'), function(e) {
+                    e.innerHTML = labelForToggleButton(true);
+                });
+                onEach(toggle.getElementsByClassName('toggle-label'), function(e) {
+                    e.style.display = 'block';
+                });
             }
-        };
-    }());
-
+        }
+    })
+
+    var span = document.createElement('span');
+    span.className = 'toggle-label';
+    span.style.display = 'none';
+    span.innerHTML = '&nbsp;Expand&nbsp;attributes';
+    toggle.appendChild(span);
+
+    var wrapper = document.createElement('div');
+    wrapper.className = 'toggle-wrapper toggle-attributes';
+    wrapper.appendChild(toggle);
+    onEach(document.getElementById('main').getElementsByTagName('pre'), function(e) {
+        onEach(e.getElementsByClassName('attributes'), function(i_e) {
+            i_e.parentNode.insertBefore(wrapper, i_e);
+            collapseDocs(i_e.previousSibling.childNodes[0]);
+        });
+    });
 }());
 
 // Sets the focus on the search bar at the top of the page
 function focusSearchBar() {
-    $('.search-input').focus();
+    document.getElementsByClassName('search-input')[0].focus();
 }
diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs
index 2a6134fde5c..1156fadf8c0 100644
--- a/src/librustdoc/lib.rs
+++ b/src/librustdoc/lib.rs
@@ -41,6 +41,7 @@ extern crate rustc_resolve;
 extern crate rustc_lint;
 extern crate rustc_back;
 extern crate rustc_metadata;
+extern crate rustc_typeck;
 extern crate serialize;
 #[macro_use] extern crate syntax;
 extern crate syntax_pos;
@@ -172,6 +173,7 @@ pub fn opts() -> Vec<RustcOptGroup> {
                          or `#![doc(html_playground_url=...)]`",
                         "URL")),
         unstable(optflag("", "enable-commonmark", "to enable commonmark doc rendering/testing")),
+        unstable(optflag("", "display-warnings", "to print code warnings when testing doc")),
     ]
 }
 
@@ -279,14 +281,16 @@ pub fn main_args(args: &[String]) -> isize {
     let crate_name = matches.opt_str("crate-name");
     let playground_url = matches.opt_str("playground-url");
     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
+    let display_warnings = matches.opt_present("display-warnings");
 
     match (should_test, markdown_input) {
         (true, true) => {
-            return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot, render_type)
+            return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot, render_type,
+                                  display_warnings)
         }
         (true, false) => {
             return test::run(input, cfgs, libs, externs, test_args, crate_name, maybe_sysroot,
-                             render_type)
+                             render_type, display_warnings)
         }
         (false, true) => return markdown::render(input,
                                                  output.unwrap_or(PathBuf::from("doc")),
@@ -388,13 +392,15 @@ where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
 
     let cr = PathBuf::from(cratefile);
     info!("starting to run rustc");
+    let display_warnings = matches.opt_present("display-warnings");
 
     let (tx, rx) = channel();
     rustc_driver::monitor(move || {
         use rustc::session::config::Input;
 
         let (mut krate, renderinfo) =
-            core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot);
+            core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot,
+                           display_warnings);
 
         info!("finished with rustc");
 
diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs
index b9ed0eeaef7..057ce69d9de 100644
--- a/src/librustdoc/markdown.rs
+++ b/src/librustdoc/markdown.rs
@@ -150,7 +150,7 @@ pub fn render(input: &str, mut output: PathBuf, matches: &getopts::Matches,
 /// Run any tests/code examples in the markdown file `input`.
 pub fn test(input: &str, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
             mut test_args: Vec<String>, maybe_sysroot: Option<PathBuf>,
-            render_type: RenderType) -> isize {
+            render_type: RenderType, display_warnings: bool) -> isize {
     let input_str = match load_string(input) {
         Ok(s) => s,
         Err(LoadStringError::ReadFail) => return 1,
@@ -166,6 +166,7 @@ pub fn test(input: &str, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
     old_find_testable_code(&input_str, &mut collector, DUMMY_SP);
     find_testable_code(&input_str, &mut collector, DUMMY_SP);
     test_args.insert(0, "rustdoctest".to_string());
-    testing::test_main(&test_args, collector.tests);
+    testing::test_main(&test_args, collector.tests,
+                       testing::Options::new().display_output(display_warnings));
     0
 }
diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs
index 5428b0663f3..d5237d629cf 100644
--- a/src/librustdoc/test.rs
+++ b/src/librustdoc/test.rs
@@ -58,7 +58,8 @@ pub fn run(input: &str,
            mut test_args: Vec<String>,
            crate_name: Option<String>,
            maybe_sysroot: Option<PathBuf>,
-           render_type: RenderType)
+           render_type: RenderType,
+           display_warnings: bool)
            -> isize {
     let input_path = PathBuf::from(input);
     let input = config::Input::File(input_path.clone());
@@ -127,7 +128,8 @@ pub fn run(input: &str,
     test_args.insert(0, "rustdoctest".to_string());
 
     testing::test_main(&test_args,
-                       collector.tests.into_iter().collect());
+                       collector.tests.into_iter().collect(),
+                       testing::Options::new().display_output(display_warnings));
     0
 }
 
diff --git a/src/libstd/build.rs b/src/libstd/build.rs
index 9fb83ad7598..f84662c3f86 100644
--- a/src/libstd/build.rs
+++ b/src/libstd/build.rs
@@ -43,11 +43,16 @@ fn main() {
         println!("cargo:rustc-link-lib=pthread");
     } else if target.contains("apple-darwin") {
         println!("cargo:rustc-link-lib=System");
+
+        // res_init and friends require -lresolv on macOS/iOS.
+        // See #41582 and http://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
+        println!("cargo:rustc-link-lib=resolv");
     } else if target.contains("apple-ios") {
         println!("cargo:rustc-link-lib=System");
         println!("cargo:rustc-link-lib=objc");
         println!("cargo:rustc-link-lib=framework=Security");
         println!("cargo:rustc-link-lib=framework=Foundation");
+        println!("cargo:rustc-link-lib=resolv");
     } else if target.contains("windows") {
         println!("cargo:rustc-link-lib=advapi32");
         println!("cargo:rustc-link-lib=ws2_32");
diff --git a/src/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs
index 9623706548b..a15269cc87c 100644
--- a/src/libstd/collections/hash/table.rs
+++ b/src/libstd/collections/hash/table.rs
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use alloc::heap::{EMPTY, allocate, deallocate};
+use alloc::heap::{allocate, deallocate};
 
 use cmp;
 use hash::{BuildHasher, Hash, Hasher};
@@ -33,6 +33,7 @@ use self::BucketState::*;
 type HashUint = usize;
 
 const EMPTY_BUCKET: HashUint = 0;
+const EMPTY: usize = 1;
 
 /// Special `Unique<HashUint>` that uses the lower bit of the pointer
 /// to expose a boolean tag.
@@ -49,24 +50,25 @@ impl TaggedHashUintPtr {
 
     #[inline]
     fn set_tag(&mut self, value: bool) {
-        let usize_ptr = &*self.0 as *const *mut HashUint as *mut usize;
+        let mut usize_ptr = self.0.as_ptr() as usize;
         unsafe {
             if value {
-                *usize_ptr |= 1;
+                usize_ptr |= 1;
             } else {
-                *usize_ptr &= !1;
+                usize_ptr &= !1;
             }
+            self.0 = Unique::new(usize_ptr as *mut HashUint)
         }
     }
 
     #[inline]
     fn tag(&self) -> bool {
-        (*self.0 as usize) & 1 == 1
+        (self.0.as_ptr() as usize) & 1 == 1
     }
 
     #[inline]
     fn ptr(&self) -> *mut HashUint {
-        (*self.0 as usize & !1) as *mut HashUint
+        (self.0.as_ptr() as usize & !1) as *mut HashUint
     }
 }
 
@@ -1112,10 +1114,12 @@ impl<'a, K, V> Iterator for Drain<'a, K, V> {
 
     #[inline]
     fn next(&mut self) -> Option<(SafeHash, K, V)> {
-        self.iter.next().map(|raw| unsafe {
-            (*self.table.as_mut_ptr()).size -= 1;
-            let (k, v) = ptr::read(raw.pair());
-            (SafeHash { hash: ptr::replace(&mut *raw.hash(), EMPTY_BUCKET) }, k, v)
+        self.iter.next().map(|raw| {
+            unsafe {
+                self.table.as_mut().size -= 1;
+                let (k, v) = ptr::read(raw.pair());
+                (SafeHash { hash: ptr::replace(&mut *raw.hash(), EMPTY_BUCKET) }, k, v)
+            }
         })
     }
 
diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs
index 6b1267d89b6..528d903b8b0 100644
--- a/src/libstd/fs.rs
+++ b/src/libstd/fs.rs
@@ -2412,7 +2412,7 @@ mod tests {
 
         let tmpdir = tmpdir();
         let unicode = tmpdir.path();
-        let unicode = unicode.join(&format!("test-각丁ー再见"));
+        let unicode = unicode.join("test-각丁ー再见");
         check!(fs::create_dir(&unicode));
         assert!(unicode.exists());
         assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
diff --git a/src/libstd/process.rs b/src/libstd/process.rs
index 23ebeb4b8e3..3896fc20a2d 100644
--- a/src/libstd/process.rs
+++ b/src/libstd/process.rs
@@ -148,8 +148,9 @@ impl fmt::Debug for Child {
     }
 }
 
-/// A handle to a child process's stdin. This struct is used in the [`stdin`]
-/// field on [`Child`].
+/// A handle to a child process's stdin.
+///
+/// This struct is used in the [`stdin`] field on [`Child`].
 ///
 /// [`Child`]: struct.Child.html
 /// [`stdin`]: struct.Child.html#structfield.stdin
@@ -190,8 +191,9 @@ impl fmt::Debug for ChildStdin {
     }
 }
 
-/// A handle to a child process's stdout. This struct is used in the [`stdout`]
-/// field on [`Child`].
+/// A handle to a child process's stdout.
+///
+/// This struct is used in the [`stdout`] field on [`Child`].
 ///
 /// [`Child`]: struct.Child.html
 /// [`stdout`]: struct.Child.html#structfield.stdout
diff --git a/src/libstd/sys/unix/thread_local.rs b/src/libstd/sys/unix/thread_local.rs
index d22118d4d79..2487f6bcaf7 100644
--- a/src/libstd/sys/unix/thread_local.rs
+++ b/src/libstd/sys/unix/thread_local.rs
@@ -38,3 +38,8 @@ pub unsafe fn destroy(key: Key) {
     let r = libc::pthread_key_delete(key);
     debug_assert_eq!(r, 0);
 }
+
+#[inline]
+pub fn requires_synchronized_create() -> bool {
+    false
+}
diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs
index 4daab31c28f..5e46069cf7d 100644
--- a/src/libstd/sys/windows/c.rs
+++ b/src/libstd/sys/windows/c.rs
@@ -14,8 +14,9 @@
 #![cfg_attr(test, allow(dead_code))]
 #![unstable(issue = "0", feature = "windows_c")]
 
-use os::raw::{c_int, c_uint, c_ulong, c_long, c_longlong, c_ushort,};
-use os::raw::{c_char, c_ulonglong};
+use os::raw::{c_int, c_uint, c_ulong, c_long, c_longlong, c_ushort, c_char};
+#[cfg(target_arch = "x86_64")]
+use os::raw::c_ulonglong;
 use libc::{wchar_t, size_t, c_void};
 use ptr;
 
@@ -45,7 +46,7 @@ pub type SIZE_T = usize;
 pub type WORD = u16;
 pub type CHAR = c_char;
 pub type HCRYPTPROV = LONG_PTR;
-pub type ULONG_PTR = c_ulonglong;
+pub type ULONG_PTR = usize;
 pub type ULONG = c_ulong;
 #[cfg(target_arch = "x86_64")]
 pub type ULONGLONG = u64;
@@ -935,7 +936,6 @@ extern "system" {
                           args: *const c_void)
                           -> DWORD;
     pub fn TlsAlloc() -> DWORD;
-    pub fn TlsFree(dwTlsIndex: DWORD) -> BOOL;
     pub fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID;
     pub fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL;
     pub fn GetLastError() -> DWORD;
diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs
index 597f05622a5..ad57f87dc1f 100644
--- a/src/libstd/sys/windows/thread_local.rs
+++ b/src/libstd/sys/windows/thread_local.rs
@@ -8,10 +8,11 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+use mem;
 use ptr;
+use sync::atomic::AtomicPtr;
+use sync::atomic::Ordering::SeqCst;
 use sys::c;
-use sys_common::mutex::Mutex;
-use sys_common;
 
 pub type Key = c::DWORD;
 pub type Dtor = unsafe extern fn(*mut u8);
@@ -34,8 +35,6 @@ pub type Dtor = unsafe extern fn(*mut u8);
 // * All TLS destructors are tracked by *us*, not the windows runtime. This
 //   means that we have a global list of destructors for each TLS key that
 //   we know about.
-// * When a TLS key is destroyed, we're sure to remove it from the dtor list
-//   if it's in there.
 // * When a thread exits, we run over the entire list and run dtors for all
 //   non-null keys. This attempts to match Unix semantics in this regard.
 //
@@ -50,13 +49,6 @@ pub type Dtor = unsafe extern fn(*mut u8);
 // [2]: https://github.com/ChromiumWebApps/chromium/blob/master/base
 //                        /threading/thread_local_storage_win.cc#L42
 
-// NB these are specifically not types from `std::sync` as they currently rely
-// on poisoning and this module needs to operate at a lower level than requiring
-// the thread infrastructure to be in place (useful on the borders of
-// initialization/destruction).
-static DTOR_LOCK: Mutex = Mutex::new();
-static mut DTORS: *mut Vec<(Key, Dtor)> = ptr::null_mut();
-
 // -------------------------------------------------------------------------
 // Native bindings
 //
@@ -85,81 +77,64 @@ pub unsafe fn get(key: Key) -> *mut u8 {
 }
 
 #[inline]
-pub unsafe fn destroy(key: Key) {
-    if unregister_dtor(key) {
-        // FIXME: Currently if a key has a destructor associated with it we
-        // can't actually ever unregister it. If we were to
-        // unregister it, then any key destruction would have to be
-        // serialized with respect to actually running destructors.
-        //
-        // We want to avoid a race where right before run_dtors runs
-        // some destructors TlsFree is called. Allowing the call to
-        // TlsFree would imply that the caller understands that *all
-        // known threads* are not exiting, which is quite a difficult
-        // thing to know!
-        //
-        // For now we just leak all keys with dtors to "fix" this.
-        // Note that source [2] above shows precedent for this sort
-        // of strategy.
-    } else {
-        let r = c::TlsFree(key);
-        debug_assert!(r != 0);
-    }
+pub unsafe fn destroy(_key: Key) {
+    rtabort!("can't destroy tls keys on windows")
+}
+
+#[inline]
+pub fn requires_synchronized_create() -> bool {
+    true
 }
 
 // -------------------------------------------------------------------------
 // Dtor registration
 //
-// These functions are associated with registering and unregistering
-// destructors. They're pretty simple, they just push onto a vector and scan
-// a vector currently.
+// Windows has no native support for running destructors so we manage our own
+// list of destructors to keep track of how to destroy keys. We then install a
+// callback later to get invoked whenever a thread exits, running all
+// appropriate destructors.
 //
-// FIXME: This could probably be at least a little faster with a BTree.
-
-unsafe fn init_dtors() {
-    if !DTORS.is_null() { return }
+// Currently unregistration from this list is not supported. A destructor can be
+// registered but cannot be unregistered. There's various simplifying reasons
+// for doing this, the big ones being:
+//
+// 1. Currently we don't even support deallocating TLS keys, so normal operation
+//    doesn't need to deallocate a destructor.
+// 2. There is no point in time where we know we can unregister a destructor
+//    because it could always be getting run by some remote thread.
+//
+// Typically processes have a statically known set of TLS keys which is pretty
+// small, and we'd want to keep this memory alive for the whole process anyway
+// really.
+//
+// Perhaps one day we can fold the `Box` here into a static allocation,
+// expanding the `StaticKey` structure to contain not only a slot for the TLS
+// key but also a slot for the destructor queue on windows. An optimization for
+// another day!
 
-    let dtors = box Vec::<(Key, Dtor)>::new();
+static DTORS: AtomicPtr<Node> = AtomicPtr::new(ptr::null_mut());
 
-    let res = sys_common::at_exit(move|| {
-        DTOR_LOCK.lock();
-        let dtors = DTORS;
-        DTORS = 1 as *mut _;
-        Box::from_raw(dtors);
-        assert!(DTORS as usize == 1); // can't re-init after destructing
-        DTOR_LOCK.unlock();
-    });
-    if res.is_ok() {
-        DTORS = Box::into_raw(dtors);
-    } else {
-        DTORS = 1 as *mut _;
-    }
+struct Node {
+    dtor: Dtor,
+    key: Key,
+    next: *mut Node,
 }
 
 unsafe fn register_dtor(key: Key, dtor: Dtor) {
-    DTOR_LOCK.lock();
-    init_dtors();
-    assert!(DTORS as usize != 0);
-    assert!(DTORS as usize != 1,
-            "cannot create new TLS keys after the main thread has exited");
-    (*DTORS).push((key, dtor));
-    DTOR_LOCK.unlock();
-}
+    let mut node = Box::new(Node {
+        key: key,
+        dtor: dtor,
+        next: ptr::null_mut(),
+    });
 
-unsafe fn unregister_dtor(key: Key) -> bool {
-    DTOR_LOCK.lock();
-    init_dtors();
-    assert!(DTORS as usize != 0);
-    assert!(DTORS as usize != 1,
-            "cannot unregister destructors after the main thread has exited");
-    let ret = {
-        let dtors = &mut *DTORS;
-        let before = dtors.len();
-        dtors.retain(|&(k, _)| k != key);
-        dtors.len() != before
-    };
-    DTOR_LOCK.unlock();
-    ret
+    let mut head = DTORS.load(SeqCst);
+    loop {
+        node.next = head;
+        match DTORS.compare_exchange(head, &mut *node, SeqCst, SeqCst) {
+            Ok(_) => return mem::forget(node),
+            Err(cur) => head = cur,
+        }
+    }
 }
 
 // -------------------------------------------------------------------------
@@ -196,16 +171,12 @@ unsafe fn unregister_dtor(key: Key) -> bool {
 // # Ok, what's up with running all these destructors?
 //
 // This will likely need to be improved over time, but this function
-// attempts a "poor man's" destructor callback system. To do this we clone a
-// local copy of the dtor list to start out with. This is our fudgy attempt
-// to not hold the lock while destructors run and not worry about the list
-// changing while we're looking at it.
-//
-// Once we've got a list of what to run, we iterate over all keys, check
-// their values, and then run destructors if the values turn out to be non
-// null (setting them to null just beforehand). We do this a few times in a
-// loop to basically match Unix semantics. If we don't reach a fixed point
-// after a short while then we just inevitably leak something most likely.
+// attempts a "poor man's" destructor callback system. Once we've got a list
+// of what to run, we iterate over all keys, check their values, and then run
+// destructors if the values turn out to be non null (setting them to null just
+// beforehand). We do this a few times in a loop to basically match Unix
+// semantics. If we don't reach a fixed point after a short while then we just
+// inevitably leak something most likely.
 //
 // # The article mentions weird stuff about "/INCLUDE"?
 //
@@ -259,25 +230,21 @@ unsafe extern "system" fn on_tls_callback(h: c::LPVOID,
 unsafe fn run_dtors() {
     let mut any_run = true;
     for _ in 0..5 {
-        if !any_run { break }
+        if !any_run {
+            break
+        }
         any_run = false;
-        let dtors = {
-            DTOR_LOCK.lock();
-            let ret = if DTORS as usize <= 1 {
-                Vec::new()
-            } else {
-                (*DTORS).iter().map(|s| *s).collect()
-            };
-            DTOR_LOCK.unlock();
-            ret
-        };
-        for &(key, dtor) in &dtors {
-            let ptr = c::TlsGetValue(key);
+        let mut cur = DTORS.load(SeqCst);
+        while !cur.is_null() {
+            let ptr = c::TlsGetValue((*cur).key);
+
             if !ptr.is_null() {
-                c::TlsSetValue(key, ptr::null_mut());
-                dtor(ptr as *mut _);
+                c::TlsSetValue((*cur).key, ptr::null_mut());
+                ((*cur).dtor)(ptr as *mut _);
                 any_run = true;
             }
+
+            cur = (*cur).next;
         }
     }
 }
diff --git a/src/libstd/sys_common/net.rs b/src/libstd/sys_common/net.rs
index 9239c18e597..a1897c8bd67 100644
--- a/src/libstd/sys_common/net.rs
+++ b/src/libstd/sys_common/net.rs
@@ -177,9 +177,22 @@ pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
     };
     let mut res = ptr::null_mut();
     unsafe {
-        cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints,
-                               &mut res))?;
-        Ok(LookupHost { original: res, cur: res })
+        match cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)) {
+            Ok(_) => {
+                Ok(LookupHost { original: res, cur: res })
+            },
+            #[cfg(unix)]
+            Err(e) => {
+                // The lookup failure could be caused by using a stale /etc/resolv.conf.
+                // See https://github.com/rust-lang/rust/issues/41570.
+                // We therefore force a reload of the nameserver information.
+                c::res_init();
+                Err(e)
+            },
+            // the cfg is needed here to avoid an "unreachable pattern" warning
+            #[cfg(not(unix))]
+            Err(e) => Err(e),
+        }
     }
 }
 
diff --git a/src/libstd/sys_common/thread_local.rs b/src/libstd/sys_common/thread_local.rs
index 25a9d5720d9..0ade90e64c3 100644
--- a/src/libstd/sys_common/thread_local.rs
+++ b/src/libstd/sys_common/thread_local.rs
@@ -61,6 +61,7 @@
 use sync::atomic::{self, AtomicUsize, Ordering};
 
 use sys::thread_local as imp;
+use sys_common::mutex::Mutex;
 
 /// A type for TLS keys that are statically allocated.
 ///
@@ -145,20 +146,6 @@ impl StaticKey {
     #[inline]
     pub unsafe fn set(&self, val: *mut u8) { imp::set(self.key(), val) }
 
-    /// Deallocates this OS TLS key.
-    ///
-    /// This function is unsafe as there is no guarantee that the key is not
-    /// currently in use by other threads or will not ever be used again.
-    ///
-    /// Note that this does *not* run the user-provided destructor if one was
-    /// specified at definition time. Doing so must be done manually.
-    pub unsafe fn destroy(&self) {
-        match self.key.swap(0, Ordering::SeqCst) {
-            0 => {}
-            n => { imp::destroy(n as imp::Key) }
-        }
-    }
-
     #[inline]
     unsafe fn key(&self) -> imp::Key {
         match self.key.load(Ordering::Relaxed) {
@@ -168,6 +155,24 @@ impl StaticKey {
     }
 
     unsafe fn lazy_init(&self) -> usize {
+        // Currently the Windows implementation of TLS is pretty hairy, and
+        // it greatly simplifies creation if we just synchronize everything.
+        //
+        // Additionally a 0-index of a tls key hasn't been seen on windows, so
+        // we just simplify the whole branch.
+        if imp::requires_synchronized_create() {
+            static INIT_LOCK: Mutex = Mutex::new();
+            INIT_LOCK.lock();
+            let mut key = self.key.load(Ordering::SeqCst);
+            if key == 0 {
+                key = imp::create(self.dtor) as usize;
+                self.key.store(key, Ordering::SeqCst);
+            }
+            INIT_LOCK.unlock();
+            assert!(key != 0);
+            return key
+        }
+
         // POSIX allows the key created here to be 0, but the compare_and_swap
         // below relies on using 0 as a sentinel value to check who won the
         // race to set the shared TLS key. As far as I know, there is no
@@ -227,7 +232,9 @@ impl Key {
 
 impl Drop for Key {
     fn drop(&mut self) {
-        unsafe { imp::destroy(self.key) }
+        // Right now Windows doesn't support TLS key destruction, but this also
+        // isn't used anywhere other than tests, so just leak the TLS key.
+        // unsafe { imp::destroy(self.key) }
     }
 }
 
diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs
index e37cc7e963e..04cd28df445 100644
--- a/src/libstd/thread/mod.rs
+++ b/src/libstd/thread/mod.rs
@@ -66,7 +66,7 @@
 //! let res = child.join();
 //! ```
 //!
-//! The [`join`] method returns a [`Result`] containing [`Ok`] of the final
+//! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
 //! value produced by the child thread, or [`Err`] of the value given to
 //! a call to [`panic!`] if the child panicked.
 //!
@@ -159,6 +159,7 @@
 //! [`panic!`]: ../../std/macro.panic.html
 //! [`Builder`]: ../../std/thread/struct.Builder.html
 //! [`thread::current`]: ../../std/thread/fn.current.html
+//! [`thread::Result`]: ../../std/thread/type.Result.html
 //! [`Thread`]: ../../std/thread/struct.Thread.html
 //! [`park`]: ../../std/thread/fn.park.html
 //! [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
@@ -457,6 +458,16 @@ pub fn yield_now() {
 
 /// Determines whether the current thread is unwinding because of panic.
 ///
+/// A common use of this feature is to poison shared resources when writing
+/// unsafe code, by checking `panicking` when the `drop` is called.
+///
+/// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
+/// already poison themselves when a thread panics while holding the lock.
+///
+/// This can also be used in multithreaded applications, in order to send a
+/// message to other threads warning that a thread has panicked (e.g. for
+/// monitoring purposes).
+///
 /// # Examples
 ///
 /// ```should_panic
@@ -485,6 +496,8 @@ pub fn yield_now() {
 ///     panic!()
 /// }
 /// ```
+///
+/// [Mutex]: ../../std/sync/struct.Mutex.html
 #[inline]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub fn panicking() -> bool {
@@ -715,21 +728,34 @@ struct Inner {
 #[stable(feature = "rust1", since = "1.0.0")]
 /// A handle to a thread.
 ///
-/// # Examples
-///
-/// ```
-/// use std::thread;
+/// You can use it to identify a thread (by name, for example). Most of the
+/// time, there is no need to directly create a `Thread` struct using the
+/// constructor, instead you should use a function like `spawn` to create
+/// new threads, see the docs of [`Builder`] and [`spawn`] for more.
 ///
-/// let handler = thread::Builder::new()
-///     .name("foo".into())
-///     .spawn(|| {
-///         let thread = thread::current();
-///         println!("thread name: {}", thread.name().unwrap());
-///     })
-///     .unwrap();
+/// # Examples
 ///
-/// handler.join().unwrap();
+/// ```no_run
+/// # // Note that this example isn't executed by default because it causes
+/// # // deadlocks on Windows unfortunately (see #25824)
+/// use std::thread::Builder;
+///
+/// for i in 0..5 {
+///     let thread_name = format!("thread_{}", i);
+///     Builder::new()
+///         .name(thread_name) // Now you can identify which thread panicked
+///                            // thanks to the handle's name
+///         .spawn(move || {
+///             if i == 3 {
+///                  panic!("I'm scared!!!");
+///             }
+///         })
+///         .unwrap();
+/// }
 /// ```
+/// [`Builder`]: ../../std/thread/struct.Builder.html
+/// [`spawn`]: ../../std/thread/fn.spawn.html
+
 pub struct Thread {
     inner: Arc<Inner>,
 }
@@ -851,9 +877,31 @@ impl fmt::Debug for Thread {
 // JoinHandle
 ////////////////////////////////////////////////////////////////////////////////
 
+/// A specialized [`Result`] type for threads.
+///
 /// Indicates the manner in which a thread exited.
 ///
 /// A thread that completes without panicking is considered to exit successfully.
+///
+/// # Examples
+///
+/// ```no_run
+/// use std::thread;
+/// use std::fs;
+///
+/// fn copy_in_thread() -> thread::Result<()> {
+///     thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
+/// }
+///
+/// fn main() {
+///     match copy_in_thread() {
+///         Ok(_) => println!("this is fine"),
+///         Err(_) => println!("thread panicked"),
+///     }
+/// }
+/// ```
+///
+/// [`Result`]: ../../std/result/enum.Result.html
 #[stable(feature = "rust1", since = "1.0.0")]
 pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
 
diff --git a/src/libstd/time/duration.rs b/src/libstd/time/duration.rs
index af7eaeb3106..55766ba3fed 100644
--- a/src/libstd/time/duration.rs
+++ b/src/libstd/time/duration.rs
@@ -84,7 +84,10 @@ impl Duration {
     /// ```
     /// use std::time::Duration;
     ///
-    /// let five_seconds = Duration::from_secs(5);
+    /// let duration = Duration::from_secs(5);
+    ///
+    /// assert_eq!(5, duration.as_secs());
+    /// assert_eq!(0, duration.subsec_nanos());
     /// ```
     #[stable(feature = "duration", since = "1.3.0")]
     #[inline]
@@ -99,7 +102,10 @@ impl Duration {
     /// ```
     /// use std::time::Duration;
     ///
-    /// let five_seconds = Duration::from_millis(5000);
+    /// let duration = Duration::from_millis(2569);
+    ///
+    /// assert_eq!(2, duration.as_secs());
+    /// assert_eq!(569000000, duration.subsec_nanos());
     /// ```
     #[stable(feature = "duration", since = "1.3.0")]
     #[inline]
@@ -119,9 +125,24 @@ impl Duration {
     /// ```
     /// use std::time::Duration;
     ///
-    /// let five_seconds = Duration::new(5, 0);
-    /// assert_eq!(five_seconds.as_secs(), 5);
+    /// let duration = Duration::new(5, 730023852);
+    /// assert_eq!(duration.as_secs(), 5);
+    /// ```
+    ///
+    /// To determine the total number of seconds represented by the `Duration`,
+    /// use `as_secs` in combination with [`subsec_nanos`]:
+    ///
     /// ```
+    /// use std::time::Duration;
+    ///
+    /// let duration = Duration::new(5, 730023852);
+    ///
+    /// assert_eq!(5.730023852,
+    ///            duration.as_secs() as f64
+    ///            + duration.subsec_nanos() as f64 * 1e-9);
+    /// ```
+    ///
+    /// [`subsec_nanos`]: #method.subsec_nanos
     #[stable(feature = "duration", since = "1.3.0")]
     #[inline]
     pub fn as_secs(&self) -> u64 { self.secs }
diff --git a/src/libstd_unicode/tables.rs b/src/libstd_unicode/tables.rs
index 7a5667b96a5..7173040350e 100644
--- a/src/libstd_unicode/tables.rs
+++ b/src/libstd_unicode/tables.rs
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// NOTE: The following code was generated by "src/etc/unicode.py", do not edit directly
+// NOTE: The following code was generated by "./unicode.py", do not edit directly
 
 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
 
diff --git a/src/etc/unicode.py b/src/libstd_unicode/unicode.py
index e5389c112e8..5f9def02c7d 100755
--- a/src/etc/unicode.py
+++ b/src/libstd_unicode/unicode.py
@@ -35,7 +35,7 @@ preamble = '''// Copyright 2012-2016 The Rust Project Developers. See the COPYRI
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// NOTE: The following code was generated by "src/etc/unicode.py", do not edit directly
+// NOTE: The following code was generated by "./unicode.py", do not edit directly
 
 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
 '''
diff --git a/src/libsyntax/Cargo.toml b/src/libsyntax/Cargo.toml
index 97d37266130..82e7cfa0032 100644
--- a/src/libsyntax/Cargo.toml
+++ b/src/libsyntax/Cargo.toml
@@ -11,7 +11,7 @@ crate-type = ["dylib"]
 [dependencies]
 serialize = { path = "../libserialize" }
 log = "0.3"
-rustc_bitflags = { path = "../librustc_bitflags" }
+bitflags = "0.8"
 syntax_pos = { path = "../libsyntax_pos" }
 rustc_errors = { path = "../librustc_errors" }
 rustc_data_structures = { path = "../librustc_data_structures" }
diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs
index 82492d97627..0980b73e80c 100644
--- a/src/libsyntax/attr.rs
+++ b/src/libsyntax/attr.rs
@@ -511,8 +511,7 @@ pub fn find_export_name_attr(diag: &Handler, attrs: &[Attribute]) -> Option<Symb
             } else {
                 struct_span_err!(diag, attr.span, E0558,
                                  "export_name attribute has invalid format")
-                    .span_label(attr.span,
-                                &format!("did you mean #[export_name=\"*\"]?"))
+                    .span_label(attr.span, "did you mean #[export_name=\"*\"]?")
                     .emit();
                 None
             }
diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs
index 8a88ec3a672..0c8be1d4f24 100644
--- a/src/libsyntax/codemap.rs
+++ b/src/libsyntax/codemap.rs
@@ -21,8 +21,8 @@ pub use syntax_pos::*;
 pub use syntax_pos::hygiene::{ExpnFormat, ExpnInfo, NameAndSpan};
 pub use self::ExpnFormat::*;
 
-use std::cell::RefCell;
-use std::path::{Path,PathBuf};
+use std::cell::{RefCell, Ref};
+use std::path::{Path, PathBuf};
 use std::rc::Rc;
 
 use std::env;
@@ -103,11 +103,18 @@ impl FileLoader for RealFileLoader {
 //
 
 pub struct CodeMap {
-    pub files: RefCell<Vec<Rc<FileMap>>>,
+    // The `files` field should not be visible outside of libsyntax so that we
+    // can do proper dependency tracking.
+    pub(super) files: RefCell<Vec<Rc<FileMap>>>,
     file_loader: Box<FileLoader>,
     // This is used to apply the file path remapping as specified via
     // -Zremap-path-prefix to all FileMaps allocated within this CodeMap.
     path_mapping: FilePathMapping,
+    // The CodeMap will invoke this callback whenever a specific FileMap is
+    // accessed. The callback starts out as a no-op but when the dependency
+    // graph becomes available later during the compilation process, it is
+    // be replaced with something that notifies the dep-tracking system.
+    dep_tracking_callback: RefCell<Box<Fn(&FileMap)>>,
 }
 
 impl CodeMap {
@@ -116,6 +123,7 @@ impl CodeMap {
             files: RefCell::new(Vec::new()),
             file_loader: Box::new(RealFileLoader),
             path_mapping: path_mapping,
+            dep_tracking_callback: RefCell::new(Box::new(|_| {})),
         }
     }
 
@@ -126,6 +134,7 @@ impl CodeMap {
             files: RefCell::new(Vec::new()),
             file_loader: file_loader,
             path_mapping: path_mapping,
+            dep_tracking_callback: RefCell::new(Box::new(|_| {})),
         }
     }
 
@@ -133,6 +142,10 @@ impl CodeMap {
         &self.path_mapping
     }
 
+    pub fn set_dep_tracking_callback(&self, cb: Box<Fn(&FileMap)>) {
+        *self.dep_tracking_callback.borrow_mut() = cb;
+    }
+
     pub fn file_exists(&self, path: &Path) -> bool {
         self.file_loader.file_exists(path)
     }
@@ -142,6 +155,19 @@ impl CodeMap {
         Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
     }
 
+    pub fn files(&self) -> Ref<Vec<Rc<FileMap>>> {
+        let files = self.files.borrow();
+        for file in files.iter() {
+            (self.dep_tracking_callback.borrow())(file);
+        }
+        files
+    }
+
+    /// Only use this if you do your own dependency tracking!
+    pub fn files_untracked(&self) -> Ref<Vec<Rc<FileMap>>> {
+        self.files.borrow()
+    }
+
     fn next_start_pos(&self) -> usize {
         let files = self.files.borrow();
         match files.last() {
@@ -170,6 +196,7 @@ impl CodeMap {
         let filemap = Rc::new(FileMap {
             name: filename,
             name_was_remapped: was_remapped,
+            crate_of_origin: 0,
             src: Some(Rc::new(src)),
             start_pos: Pos::from_usize(start_pos),
             end_pos: Pos::from_usize(end_pos),
@@ -204,6 +231,7 @@ impl CodeMap {
     pub fn new_imported_filemap(&self,
                                 filename: FileName,
                                 name_was_remapped: bool,
+                                crate_of_origin: u32,
                                 source_len: usize,
                                 mut file_local_lines: Vec<BytePos>,
                                 mut file_local_multibyte_chars: Vec<MultiByteChar>)
@@ -225,6 +253,7 @@ impl CodeMap {
         let filemap = Rc::new(FileMap {
             name: filename,
             name_was_remapped: name_was_remapped,
+            crate_of_origin: crate_of_origin,
             src: None,
             start_pos: start_pos,
             end_pos: end_pos,
@@ -282,6 +311,8 @@ impl CodeMap {
         let files = self.files.borrow();
         let f = (*files)[idx].clone();
 
+        (self.dep_tracking_callback.borrow())(&f);
+
         match f.lookup_line(pos) {
             Some(line) => Ok(FileMapAndLine { fm: f, line: line }),
             None => Err(f)
@@ -471,6 +502,7 @@ impl CodeMap {
     pub fn get_filemap(&self, filename: &str) -> Option<Rc<FileMap>> {
         for fm in self.files.borrow().iter() {
             if filename == fm.name {
+               (self.dep_tracking_callback.borrow())(&fm);
                 return Some(fm.clone());
             }
         }
@@ -481,6 +513,7 @@ impl CodeMap {
     pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
         let idx = self.lookup_filemap_idx(bpos);
         let fm = (*self.files.borrow())[idx].clone();
+        (self.dep_tracking_callback.borrow())(&fm);
         let offset = bpos - fm.start_pos;
         FileMapAndBytePos {fm: fm, pos: offset}
     }
@@ -491,6 +524,8 @@ impl CodeMap {
         let files = self.files.borrow();
         let map = &(*files)[idx];
 
+        (self.dep_tracking_callback.borrow())(map);
+
         // The number of extra bytes due to multibyte chars in the FileMap
         let mut total_extra_bytes = 0;
 
@@ -536,7 +571,7 @@ impl CodeMap {
     }
 
     pub fn count_lines(&self) -> usize {
-        self.files.borrow().iter().fold(0, |a, f| a + f.count_lines())
+        self.files().iter().fold(0, |a, f| a + f.count_lines())
     }
 }
 
diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs
index fda026fec64..f731c5abdd6 100644
--- a/src/libsyntax/ext/base.rs
+++ b/src/libsyntax/ext/base.rs
@@ -24,6 +24,7 @@ use ptr::P;
 use symbol::Symbol;
 use util::small_vector::SmallVector;
 
+use std::collections::HashMap;
 use std::path::PathBuf;
 use std::rc::Rc;
 use std::default::Default;
@@ -643,6 +644,7 @@ pub struct ExtCtxt<'a> {
     pub resolver: &'a mut Resolver,
     pub resolve_err_count: usize,
     pub current_expansion: ExpansionData,
+    pub expansions: HashMap<Span, Vec<String>>,
 }
 
 impl<'a> ExtCtxt<'a> {
@@ -662,6 +664,7 @@ impl<'a> ExtCtxt<'a> {
                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
                 directory_ownership: DirectoryOwnership::Owned,
             },
+            expansions: HashMap::new(),
         }
     }
 
@@ -765,6 +768,15 @@ impl<'a> ExtCtxt<'a> {
     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
         self.parse_sess.span_diagnostic.span_bug(sp, msg);
     }
+    pub fn trace_macros_diag(&self) {
+        for (sp, notes) in self.expansions.iter() {
+            let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, &"trace_macro");
+            for note in notes {
+                db.note(&note);
+            }
+            db.emit();
+        }
+    }
     pub fn bug(&self, msg: &str) -> ! {
         self.parse_sess.span_diagnostic.bug(msg);
     }
diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs
index 2db295d0136..a8aa103f80a 100644
--- a/src/libsyntax/ext/expand.rs
+++ b/src/libsyntax/ext/expand.rs
@@ -231,7 +231,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
             },
             _ => unreachable!(),
         };
-
+        self.cx.trace_macros_diag();
         krate
     }
 
@@ -1038,7 +1038,7 @@ impl<'feat> ExpansionConfig<'feat> {
         ExpansionConfig {
             crate_name: crate_name,
             features: None,
-            recursion_limit: 64,
+            recursion_limit: 1024,
             trace_mac: false,
             should_test: false,
             single_step: false,
diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs
index be979960725..f959ccc989e 100644
--- a/src/libsyntax/ext/tt/macro_rules.rs
+++ b/src/libsyntax/ext/tt/macro_rules.rs
@@ -27,8 +27,8 @@ use symbol::Symbol;
 use tokenstream::{TokenStream, TokenTree};
 
 use std::cell::RefCell;
-use std::collections::{HashMap};
-use std::collections::hash_map::{Entry};
+use std::collections::HashMap;
+use std::collections::hash_map::Entry;
 use std::rc::Rc;
 
 pub struct ParserAnyMacro<'a> {
@@ -85,7 +85,7 @@ impl TTMacroExpander for MacroRulesMacroExpander {
 }
 
 /// Given `lhses` and `rhses`, this is the new macro we create
-fn generic_extension<'cx>(cx: &'cx ExtCtxt,
+fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
                           sp: Span,
                           name: ast::Ident,
                           arg: TokenStream,
@@ -93,7 +93,9 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt,
                           rhses: &[quoted::TokenTree])
                           -> Box<MacResult+'cx> {
     if cx.trace_macros() {
-        println!("{}! {{ {} }}", name, arg);
+        let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
+        let mut values: &mut Vec<String> = cx.expansions.entry(sp).or_insert(vec![]);
+        values.push(format!("expands to `{}! {{ {} }}`", name, arg));
     }
 
     // Which arm's failure should we report? (the one furthest along)
diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs
index 86ee1c5336d..89c67b88cbd 100644
--- a/src/libsyntax/lib.rs
+++ b/src/libsyntax/lib.rs
@@ -24,20 +24,15 @@
        test(attr(deny(warnings))))]
 #![deny(warnings)]
 
-#![feature(associated_consts)]
-#![feature(const_fn)]
-#![feature(optin_builtin_traits)]
 #![feature(rustc_private)]
 #![feature(staged_api)]
-#![feature(str_escape)]
 #![feature(unicode)]
 #![feature(rustc_diagnostic_macros)]
-#![feature(specialization)]
 #![feature(i128_type)]
 
 extern crate serialize;
 #[macro_use] extern crate log;
-#[macro_use] #[no_link] extern crate rustc_bitflags;
+#[macro_use] extern crate bitflags;
 extern crate std_unicode;
 pub extern crate rustc_errors as errors;
 extern crate syntax_pos;
diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs
index c2e5763237d..ded1f0b599a 100644
--- a/src/libsyntax/parse/lexer/mod.rs
+++ b/src/libsyntax/parse/lexer/mod.rs
@@ -73,7 +73,7 @@ fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
 }
 
 impl<'a> StringReader<'a> {
-    fn next_token(&mut self) -> TokenAndSpan where Self: Sized {
+    fn next_token(&mut self) -> TokenAndSpan {
         let res = self.try_next_token();
         self.unwrap_or_abort(res)
     }
@@ -504,7 +504,7 @@ impl<'a> StringReader<'a> {
                     self.bump();
 
                     // line comments starting with "///" or "//!" are doc-comments
-                    let doc_comment = self.ch_is('/') || self.ch_is('!');
+                    let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
                     let start_bpos = self.pos - BytePos(2);
 
                     while !self.is_eof() {
diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs
index 9d8f3b3d039..fe3ca1cf230 100644
--- a/src/libsyntax/parse/mod.rs
+++ b/src/libsyntax/parse/mod.rs
@@ -261,10 +261,14 @@ pub fn char_lit(lit: &str) -> (char, isize) {
     }
 }
 
+pub fn escape_default(s: &str) -> String {
+    s.chars().map(char::escape_default).flat_map(|x| x).collect()
+}
+
 /// Parse a string representing a string literal into its final form. Does
 /// unescaping.
 pub fn str_lit(lit: &str) -> String {
-    debug!("parse_str_lit: given {}", lit.escape_default());
+    debug!("parse_str_lit: given {}", escape_default(lit));
     let mut res = String::with_capacity(lit.len());
 
     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
@@ -339,7 +343,7 @@ pub fn str_lit(lit: &str) -> String {
 /// Parse a string representing a raw string literal into its final form. The
 /// only operation this does is convert embedded CRLF into a single LF.
 pub fn raw_str_lit(lit: &str) -> String {
-    debug!("raw_str_lit: given {}", lit.escape_default());
+    debug!("raw_str_lit: given {}", escape_default(lit));
     let mut res = String::with_capacity(lit.len());
 
     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs
index d252963274e..ca1351e3b41 100644
--- a/src/libsyntax/parse/parser.rs
+++ b/src/libsyntax/parse/parser.rs
@@ -64,7 +64,7 @@ use std::path::{self, Path, PathBuf};
 use std::slice;
 
 bitflags! {
-    flags Restrictions: u8 {
+    pub flags Restrictions: u8 {
         const RESTRICTION_STMT_EXPR         = 1 << 0,
         const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
     }
@@ -602,10 +602,10 @@ impl<'a> Parser<'a> {
                 label_sp
             };
             if self.span.contains(sp) {
-                err.span_label(self.span, &label_exp);
+                err.span_label(self.span, label_exp);
             } else {
-                err.span_label(sp, &label_exp);
-                err.span_label(self.span, &"unexpected token");
+                err.span_label(sp, label_exp);
+                err.span_label(self.span, "unexpected token");
             }
             Err(err)
         }
@@ -1512,10 +1512,10 @@ impl<'a> Parser<'a> {
                 err.span_suggestion(sum_span, "try adding parentheses:", sum_with_parens);
             }
             TyKind::Ptr(..) | TyKind::BareFn(..) => {
-                err.span_label(sum_span, &"perhaps you forgot parentheses?");
+                err.span_label(sum_span, "perhaps you forgot parentheses?");
             }
             _ => {
-                err.span_label(sum_span, &"expected a path");
+                err.span_label(sum_span, "expected a path");
             },
         }
         err.emit();
@@ -2291,7 +2291,7 @@ impl<'a> Parser<'a> {
                     let e = if self.token.can_begin_expr()
                                && !(self.token == token::OpenDelim(token::Brace)
                                     && self.restrictions.contains(
-                                           Restrictions::RESTRICTION_NO_STRUCT_LITERAL)) {
+                                           RESTRICTION_NO_STRUCT_LITERAL)) {
                         Some(self.parse_expr()?)
                     } else {
                         None
@@ -2318,7 +2318,7 @@ impl<'a> Parser<'a> {
                         // This is a struct literal, unless we're prohibited
                         // from parsing struct literals here.
                         let prohibited = self.restrictions.contains(
-                            Restrictions::RESTRICTION_NO_STRUCT_LITERAL
+                            RESTRICTION_NO_STRUCT_LITERAL
                         );
                         if !prohibited {
                             return self.parse_struct_expr(lo, pth, attrs);
@@ -2556,7 +2556,7 @@ impl<'a> Parser<'a> {
                     let fstr = n.as_str();
                     let mut err = self.diagnostic().struct_span_err(self.prev_span,
                         &format!("unexpected token: `{}`", n));
-                    err.span_label(self.prev_span, &"unexpected token");
+                    err.span_label(self.prev_span, "unexpected token");
                     if fstr.chars().all(|x| "0123456789.".contains(x)) {
                         let float = match fstr.parse::<f64>().ok() {
                             Some(f) => f,
@@ -2700,6 +2700,19 @@ impl<'a> Parser<'a> {
                 let (span, e) = self.interpolated_or_expr_span(e)?;
                 (span, self.mk_unary(UnOp::Not, e))
             }
+            // Suggest `!` for bitwise negation when encountering a `~`
+            token::Tilde => {
+                self.bump();
+                let e = self.parse_prefix_expr(None);
+                let (span, e) = self.interpolated_or_expr_span(e)?;
+                let span_of_tilde = lo;
+                let mut err = self.diagnostic().struct_span_err(span_of_tilde,
+                        "`~` can not be used as a unary operator");
+                err.span_label(span_of_tilde, "did you mean `!`?");
+                err.help("use `!` instead of `~` if you meant to perform bitwise negation");
+                err.emit();
+                (span, self.mk_unary(UnOp::Not, e))
+            }
             token::BinOp(token::Minus) => {
                 self.bump();
                 let e = self.parse_prefix_expr(None);
@@ -2722,7 +2735,7 @@ impl<'a> Parser<'a> {
             token::Ident(..) if self.token.is_keyword(keywords::In) => {
                 self.bump();
                 let place = self.parse_expr_res(
-                    Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
+                    RESTRICTION_NO_STRUCT_LITERAL,
                     None,
                 )?;
                 let blk = self.parse_block()?;
@@ -2785,7 +2798,7 @@ impl<'a> Parser<'a> {
 
             let cur_op_span = self.span;
             let restrictions = if op.is_assign_like() {
-                self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
+                self.restrictions & RESTRICTION_NO_STRUCT_LITERAL
             } else {
                 self.restrictions
             };
@@ -2835,13 +2848,13 @@ impl<'a> Parser<'a> {
 
             let rhs = match op.fixity() {
                 Fixity::Right => self.with_res(
-                    restrictions - Restrictions::RESTRICTION_STMT_EXPR,
+                    restrictions - RESTRICTION_STMT_EXPR,
                     |this| {
                         this.parse_assoc_expr_with(op.precedence(),
                             LhsExpr::NotYetParsed)
                 }),
                 Fixity::Left => self.with_res(
-                    restrictions - Restrictions::RESTRICTION_STMT_EXPR,
+                    restrictions - RESTRICTION_STMT_EXPR,
                     |this| {
                         this.parse_assoc_expr_with(op.precedence() + 1,
                             LhsExpr::NotYetParsed)
@@ -2849,7 +2862,7 @@ impl<'a> Parser<'a> {
                 // We currently have no non-associative operators that are not handled above by
                 // the special cases. The code is here only for future convenience.
                 Fixity::None => self.with_res(
-                    restrictions - Restrictions::RESTRICTION_STMT_EXPR,
+                    restrictions - RESTRICTION_STMT_EXPR,
                     |this| {
                         this.parse_assoc_expr_with(op.precedence() + 1,
                             LhsExpr::NotYetParsed)
@@ -2959,7 +2972,7 @@ impl<'a> Parser<'a> {
         if self.token.can_begin_expr() {
             // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
             if self.token == token::OpenDelim(token::Brace) {
-                return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
+                return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
             }
             true
         } else {
@@ -2973,7 +2986,7 @@ impl<'a> Parser<'a> {
             return self.parse_if_let_expr(attrs);
         }
         let lo = self.prev_span;
-        let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
+        let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
         let thn = self.parse_block()?;
         let mut els: Option<P<Expr>> = None;
         let mut hi = thn.span;
@@ -2992,7 +3005,7 @@ impl<'a> Parser<'a> {
         self.expect_keyword(keywords::Let)?;
         let pat = self.parse_pat()?;
         self.expect(&token::Eq)?;
-        let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
+        let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
         let thn = self.parse_block()?;
         let (hi, els) = if self.eat_keyword(keywords::Else) {
             let expr = self.parse_else_expr()?;
@@ -3046,7 +3059,7 @@ impl<'a> Parser<'a> {
 
         let pat = self.parse_pat()?;
         self.expect_keyword(keywords::In)?;
-        let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
+        let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
         attrs.extend(iattrs);
 
@@ -3061,7 +3074,7 @@ impl<'a> Parser<'a> {
         if self.token.is_keyword(keywords::Let) {
             return self.parse_while_let_expr(opt_ident, span_lo, attrs);
         }
-        let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
+        let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
         attrs.extend(iattrs);
         let span = span_lo.to(body.span);
@@ -3075,7 +3088,7 @@ impl<'a> Parser<'a> {
         self.expect_keyword(keywords::Let)?;
         let pat = self.parse_pat()?;
         self.expect(&token::Eq)?;
-        let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
+        let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
         attrs.extend(iattrs);
         let span = span_lo.to(body.span);
@@ -3105,7 +3118,7 @@ impl<'a> Parser<'a> {
     fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
         let match_span = self.prev_span;
         let lo = self.prev_span;
-        let discriminant = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
+        let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
                                                None)?;
         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
             if self.token == token::Token::Semi {
@@ -3146,7 +3159,7 @@ impl<'a> Parser<'a> {
             guard = Some(self.parse_expr()?);
         }
         self.expect(&token::FatArrow)?;
-        let expr = self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None)?;
+        let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
 
         let require_comma =
             !classify::expr_is_simple_block(&expr)
@@ -3727,7 +3740,7 @@ impl<'a> Parser<'a> {
         self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
 
         // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
-        !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)
+        !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
     }
 
     fn is_union_item(&self) -> bool {
@@ -3799,7 +3812,7 @@ impl<'a> Parser<'a> {
                     self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
                 };
 
-                let expr = self.with_res(Restrictions::RESTRICTION_STMT_EXPR, |this| {
+                let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
                     let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
                     this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
                 })?;
@@ -3939,7 +3952,7 @@ impl<'a> Parser<'a> {
 
                     // Remainder are line-expr stmts.
                     let e = self.parse_expr_res(
-                        Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
+                        RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
                     Stmt {
                         id: ast::DUMMY_NODE_ID,
                         span: lo.to(e.span),
@@ -3952,7 +3965,7 @@ impl<'a> Parser<'a> {
 
     /// Is this expression a successfully-parsed statement?
     fn expr_is_complete(&mut self, e: &Expr) -> bool {
-        self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
+        self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
             !classify::expr_requires_semi_to_be_stmt(e)
     }
 
@@ -4779,7 +4792,7 @@ impl<'a> Parser<'a> {
             sp,
             &format!("missing `fn`, `type`, or `const` for {}-item declaration",
                      item_type));
-        err.span_label(sp, &"missing `fn`, `type`, or `const`");
+        err.span_label(sp, "missing `fn`, `type`, or `const`");
         err
     }
 
diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs
index a911c21ed98..0c7e8fda837 100644
--- a/src/libsyntax/print/pprust.rs
+++ b/src/libsyntax/print/pprust.rs
@@ -677,7 +677,7 @@ pub trait PrintState<'a> {
                     style: ast::StrStyle) -> io::Result<()> {
         let st = match style {
             ast::StrStyle::Cooked => {
-                (format!("\"{}\"", st.escape_default()))
+                (format!("\"{}\"", parse::escape_default(st)))
             }
             ast::StrStyle::Raw(n) => {
                 (format!("r{delim}\"{string}\"{delim}",
diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs
index 50380626d7f..91746a2edd9 100644
--- a/src/libsyntax/test.rs
+++ b/src/libsyntax/test.rs
@@ -442,7 +442,7 @@ We're going to be building a module that looks more or less like:
 mod __test {
   extern crate test (name = "test", vers = "...");
   fn main() {
-    test::test_main_static(&::os::args()[], tests)
+    test::test_main_static(&::os::args()[], tests, test::Options::new())
   }
 
   static tests : &'static [test::TestDescAndFn] = &[
@@ -478,7 +478,7 @@ fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
     //        pub fn main() {
     //            #![main]
     //            use std::slice::AsSlice;
-    //            test::test_main_static(::std::os::args().as_slice(), TESTS);
+    //            test::test_main_static(::std::os::args().as_slice(), TESTS, test::Options::new());
     //        }
 
     let sp = ignored_span(cx, DUMMY_SP);
diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs
index f46b4fcb715..eb86a8e1379 100644
--- a/src/libsyntax_pos/lib.rs
+++ b/src/libsyntax_pos/lib.rs
@@ -377,6 +377,8 @@ pub struct FileMap {
     pub name: FileName,
     /// True if the `name` field above has been modified by -Zremap-path-prefix
     pub name_was_remapped: bool,
+    /// Indicates which crate this FileMap was imported from.
+    pub crate_of_origin: u32,
     /// The complete source code
     pub src: Option<Rc<String>>,
     /// The start position of this source in the CodeMap
@@ -491,6 +493,10 @@ impl Decodable for FileMap {
             Ok(FileMap {
                 name: name,
                 name_was_remapped: name_was_remapped,
+                // `crate_of_origin` has to be set by the importer.
+                // This value matches up with rustc::hir::def_id::INVALID_CRATE.
+                // That constant is not available here unfortunately :(
+                crate_of_origin: ::std::u32::MAX - 1,
                 start_pos: start_pos,
                 end_pos: end_pos,
                 src: None,
diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs
index 5fdb0aa0641..35f2fbca69f 100644
--- a/src/libtest/lib.rs
+++ b/src/libtest/lib.rs
@@ -76,7 +76,7 @@ pub mod test {
     pub use {Bencher, TestName, TestResult, TestDesc, TestDescAndFn, TestOpts, TrFailed,
              TrFailedMsg, TrIgnored, TrOk, Metric, MetricMap, StaticTestFn, StaticTestName,
              DynTestName, DynTestFn, run_test, test_main, test_main_static, filter_tests,
-             parse_opts, StaticBenchFn, ShouldPanic};
+             parse_opts, StaticBenchFn, ShouldPanic, Options};
 }
 
 pub mod stats;
@@ -252,14 +252,34 @@ impl Clone for MetricMap {
     }
 }
 
+/// In case we want to add other options as well, just add them in this struct.
+#[derive(Copy, Clone, Debug)]
+pub struct Options {
+    display_output: bool,
+}
+
+impl Options {
+    pub fn new() -> Options {
+        Options {
+            display_output: false,
+        }
+    }
+
+    pub fn display_output(mut self, display_output: bool) -> Options {
+        self.display_output = display_output;
+        self
+    }
+}
+
 // The default console test runner. It accepts the command line
 // arguments and a vector of test_descs.
-pub fn test_main(args: &[String], tests: Vec<TestDescAndFn>) {
-    let opts = match parse_opts(args) {
+pub fn test_main(args: &[String], tests: Vec<TestDescAndFn>, options: Options) {
+    let mut opts = match parse_opts(args) {
         Some(Ok(o)) => o,
         Some(Err(msg)) => panic!("{:?}", msg),
         None => return,
     };
+    opts.options = options;
     if opts.list {
         if let Err(e) = list_tests_console(&opts, tests) {
             panic!("io error when listing tests: {:?}", e);
@@ -301,16 +321,17 @@ pub fn test_main_static(tests: &[TestDescAndFn]) {
                                }
                            })
                            .collect();
-    test_main(&args, owned_tests)
+    test_main(&args, owned_tests, Options::new())
 }
 
-#[derive(Copy, Clone)]
+#[derive(Copy, Clone, Debug)]
 pub enum ColorConfig {
     AutoColor,
     AlwaysColor,
     NeverColor,
 }
 
+#[derive(Debug)]
 pub struct TestOpts {
     pub list: bool,
     pub filter: Option<String>,
@@ -324,6 +345,7 @@ pub struct TestOpts {
     pub quiet: bool,
     pub test_threads: Option<usize>,
     pub skip: Vec<String>,
+    pub options: Options,
 }
 
 impl TestOpts {
@@ -342,6 +364,7 @@ impl TestOpts {
             quiet: false,
             test_threads: None,
             skip: vec![],
+            options: Options::new(),
         }
     }
 }
@@ -481,6 +504,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> {
         quiet: quiet,
         test_threads: test_threads,
         skip: matches.opt_strs("skip"),
+        options: Options::new(),
     };
 
     Some(Ok(test_opts))
@@ -521,7 +545,9 @@ struct ConsoleTestState<T> {
     measured: usize,
     metrics: MetricMap,
     failures: Vec<(TestDesc, Vec<u8>)>,
+    not_failures: Vec<(TestDesc, Vec<u8>)>,
     max_name_len: usize, // number of columns to fill when aligning names
+    options: Options,
 }
 
 impl<T: Write> ConsoleTestState<T> {
@@ -547,7 +573,9 @@ impl<T: Write> ConsoleTestState<T> {
             measured: 0,
             metrics: MetricMap::new(),
             failures: Vec::new(),
+            not_failures: Vec::new(),
             max_name_len: 0,
+            options: opts.options,
         })
     }
 
@@ -703,9 +731,38 @@ impl<T: Write> ConsoleTestState<T> {
         Ok(())
     }
 
+    pub fn write_outputs(&mut self) -> io::Result<()> {
+        self.write_plain("\nsuccesses:\n")?;
+        let mut successes = Vec::new();
+        let mut stdouts = String::new();
+        for &(ref f, ref stdout) in &self.not_failures {
+            successes.push(f.name.to_string());
+            if !stdout.is_empty() {
+                stdouts.push_str(&format!("---- {} stdout ----\n\t", f.name));
+                let output = String::from_utf8_lossy(stdout);
+                stdouts.push_str(&output);
+                stdouts.push_str("\n");
+            }
+        }
+        if !stdouts.is_empty() {
+            self.write_plain("\n")?;
+            self.write_plain(&stdouts)?;
+        }
+
+        self.write_plain("\nsuccesses:\n")?;
+        successes.sort();
+        for name in &successes {
+            self.write_plain(&format!("    {}\n", name))?;
+        }
+        Ok(())
+    }
+
     pub fn write_run_finish(&mut self) -> io::Result<bool> {
         assert!(self.passed + self.failed + self.ignored + self.measured == self.total);
 
+        if self.options.display_output {
+            self.write_outputs()?;
+        }
         let success = self.failed == 0;
         if !success {
             self.write_failures()?;
@@ -824,7 +881,10 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Resu
                 st.write_log_result(&test, &result)?;
                 st.write_result(&result)?;
                 match result {
-                    TrOk => st.passed += 1,
+                    TrOk => {
+                        st.passed += 1;
+                        st.not_failures.push((test, stdout));
+                    }
                     TrIgnored => st.ignored += 1,
                     TrMetrics(mm) => {
                         let tname = test.name;
@@ -901,6 +961,8 @@ fn should_sort_failures_before_printing_them() {
         max_name_len: 10,
         metrics: MetricMap::new(),
         failures: vec![(test_b, Vec::new()), (test_a, Vec::new())],
+        options: Options::new(),
+        not_failures: Vec::new(),
     };
 
     st.write_failures().unwrap();
diff --git a/src/llvm b/src/llvm
-Subproject 15745af7683844e43bdec966072b8e7b4477245
+Subproject cf85b5a8da7853c4de5cc57766da8b7988c0646
diff --git a/src/rust-installer b/src/rust-installer
-Subproject 4f994850808a572e2cc8d43f968893c8e942e9b
+Subproject 2e6417f6af5218a29a8ee72ed17af085560b9b9
diff --git a/src/rustllvm/llvm-rebuild-trigger b/src/rustllvm/llvm-rebuild-trigger
index 1006445ade6..d73d1c25e5b 100644
--- a/src/rustllvm/llvm-rebuild-trigger
+++ b/src/rustllvm/llvm-rebuild-trigger
@@ -1,4 +1,4 @@
 # If this file is modified, then llvm will be (optionally) cleaned and then rebuilt.
 # The actual contents of this file do not matter, but to trigger a change on the
 # build bots then the contents should be changed so git updates the mtime.
-2017-04-26
+2017-05-06
diff --git a/src/test/compile-fail/closure-no-fn.rs b/src/test/compile-fail/closure-no-fn-1.rs
index fe179e8a48f..10c99703a97 100644
--- a/src/test/compile-fail/closure-no-fn.rs
+++ b/src/test/compile-fail/closure-no-fn-1.rs
@@ -15,10 +15,4 @@ fn main() {
     let mut a = 0u8;
     let foo: fn(u8) -> u8 = |v: u8| { a += v; a };
     //~^ ERROR mismatched types
-    let b = 0u8;
-    let bar: fn() -> u8 = || { b };
-    //~^ ERROR mismatched types
-    let baz: fn() -> u8 = || { b } as fn() -> u8;
-    //~^ ERROR mismatched types
-    //~^^ ERROR non-scalar cast
 }
diff --git a/src/test/compile-fail/closure-no-fn-2.rs b/src/test/compile-fail/closure-no-fn-2.rs
new file mode 100644
index 00000000000..a6438bb5f24
--- /dev/null
+++ b/src/test/compile-fail/closure-no-fn-2.rs
@@ -0,0 +1,18 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Ensure that capturing closures are never coerced to fns
+// Especially interesting as non-capturing closures can be.
+
+fn main() {
+    let b = 0u8;
+    let bar: fn() -> u8 = || { b };
+    //~^ ERROR mismatched types
+}
diff --git a/src/test/compile-fail/closure-no-fn-3.rs b/src/test/compile-fail/closure-no-fn-3.rs
new file mode 100644
index 00000000000..85dbc899208
--- /dev/null
+++ b/src/test/compile-fail/closure-no-fn-3.rs
@@ -0,0 +1,18 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Ensure that capturing closures are never coerced to fns
+// Especially interesting as non-capturing closures can be.
+
+fn main() {
+    let b = 0u8;
+    let baz: fn() -> u8 = (|| { b }) as fn() -> u8;
+    //~^ ERROR non-scalar cast
+}
diff --git a/src/test/compile-fail/dep-graph-struct-signature.rs b/src/test/compile-fail/dep-graph-struct-signature.rs
index 7ed8b95f88b..3f568194e23 100644
--- a/src/test/compile-fail/dep-graph-struct-signature.rs
+++ b/src/test/compile-fail/dep-graph-struct-signature.rs
@@ -58,13 +58,15 @@ mod signatures {
         fn method(&self, x: u32) { }
     }
 
-    #[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
     struct WillChanges {
+        #[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
         x: WillChange,
+        #[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
         y: WillChange
     }
 
-    #[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
+    // The fields change, not the type itself.
+    #[rustc_then_this_would_need(ItemSignature)] //~ ERROR no path
     fn indirect(x: WillChanges) { }
 }
 
diff --git a/src/test/compile-fail/dep-graph-type-alias.rs b/src/test/compile-fail/dep-graph-type-alias.rs
index 4cc15e8b522..56636a00a31 100644
--- a/src/test/compile-fail/dep-graph-type-alias.rs
+++ b/src/test/compile-fail/dep-graph-type-alias.rs
@@ -23,15 +23,21 @@ fn main() { }
 #[rustc_if_this_changed]
 type TypeAlias = u32;
 
-#[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
+// The type alias directly affects the type of the field,
+// not the enclosing struct:
+#[rustc_then_this_would_need(ItemSignature)] //~ ERROR no path
 struct Struct {
+    #[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
     x: TypeAlias,
     y: u32
 }
 
-#[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
+#[rustc_then_this_would_need(ItemSignature)] //~ ERROR no path
 enum Enum {
-    Variant1(TypeAlias),
+    Variant1 {
+        #[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
+        t: TypeAlias
+    },
     Variant2(i32)
 }
 
diff --git a/src/test/compile-fail/dep-graph-variance-alias.rs b/src/test/compile-fail/dep-graph-variance-alias.rs
new file mode 100644
index 00000000000..9b621a13fc4
--- /dev/null
+++ b/src/test/compile-fail/dep-graph-variance-alias.rs
@@ -0,0 +1,32 @@
+// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that changing what a `type` points to does not go unnoticed
+// by the variance analysis.
+
+// compile-flags: -Z query-dep-graph
+
+#![feature(rustc_attrs)]
+#![allow(dead_code)]
+#![allow(unused_variables)]
+
+fn main() { }
+
+struct Foo<T> {
+    f: T
+}
+
+#[rustc_if_this_changed]
+type TypeAlias<T> = Foo<T>;
+
+#[rustc_then_this_would_need(ItemVariances)] //~ ERROR OK
+struct Use<T> {
+    x: TypeAlias<T>
+}
diff --git a/src/test/compile-fail/issue-3008-1.rs b/src/test/compile-fail/issue-3008-1.rs
index d3c15763eb0..7ca6d9301a6 100644
--- a/src/test/compile-fail/issue-3008-1.rs
+++ b/src/test/compile-fail/issue-3008-1.rs
@@ -8,9 +8,16 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-enum foo { foo_(bar) }
-enum bar { bar_none, bar_some(bar) }
-//~^ ERROR recursive type `bar` has infinite size
+enum Foo {
+    Foo_(Bar)
+}
+
+enum Bar {
+    //~^ ERROR recursive type `Bar` has infinite size
+    //~| NOTE recursive type has infinite size
+    BarNone,
+    BarSome(Bar)  //~ NOTE recursive without indirection
+}
 
 fn main() {
 }
diff --git a/src/test/compile-fail/issue-3008-2.rs b/src/test/compile-fail/issue-3008-2.rs
index 3bc8413cbca..061d1facda0 100644
--- a/src/test/compile-fail/issue-3008-2.rs
+++ b/src/test/compile-fail/issue-3008-2.rs
@@ -12,6 +12,7 @@ enum foo { foo_(bar) }
 struct bar { x: bar }
 //~^ ERROR E0072
 //~| NOTE recursive type has infinite size
+//~| NOTE recursive without indirection
 
 fn main() {
 }
diff --git a/src/test/compile-fail/issue-32326.rs b/src/test/compile-fail/issue-32326.rs
index afffe2a2c8d..70a7cd8b970 100644
--- a/src/test/compile-fail/issue-32326.rs
+++ b/src/test/compile-fail/issue-32326.rs
@@ -15,6 +15,8 @@
 enum Expr { //~ ERROR E0072
             //~| NOTE recursive type has infinite size
     Plus(Expr, Expr),
+    //~^ NOTE recursive without indirection
+    //~| NOTE recursive without indirection
     Literal(i64),
 }
 
diff --git a/src/test/compile-fail/issue-3779.rs b/src/test/compile-fail/issue-3779.rs
index 71e9325ab75..10f73dc0862 100644
--- a/src/test/compile-fail/issue-3779.rs
+++ b/src/test/compile-fail/issue-3779.rs
@@ -8,9 +8,11 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-struct S { //~ ERROR E0072
-           //~| NOTE recursive type has infinite size
+struct S {
+    //~^ ERROR E0072
+    //~| NOTE recursive type has infinite size
     element: Option<S>
+    //~^ NOTE recursive without indirection
 }
 
 fn main() {
diff --git a/src/test/compile-fail/issue-40000.rs b/src/test/compile-fail/issue-40000.rs
index 9be114ebcb6..3ccee0f12be 100644
--- a/src/test/compile-fail/issue-40000.rs
+++ b/src/test/compile-fail/issue-40000.rs
@@ -11,8 +11,7 @@
 #![feature(closure_to_fn_coercion)]
 
 fn main() {
-    let bar: fn(&mut u32) = |_| {}; //~ ERROR mismatched types
-    //~| expected concrete lifetime, found bound lifetime parameter
+    let bar: fn(&mut u32) = |_| {};
 
     fn foo(x: Box<Fn(&i32)>) {}
     let bar = Box::new(|x: &i32| {}) as Box<Fn(_)>;
diff --git a/src/test/compile-fail/issue-41255.rs b/src/test/compile-fail/issue-41255.rs
new file mode 100644
index 00000000000..a4585f7bac7
--- /dev/null
+++ b/src/test/compile-fail/issue-41255.rs
@@ -0,0 +1,55 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Matching against float literals should result in a linter error
+
+#![feature(slice_patterns)]
+#![feature(exclusive_range_pattern)]
+#![allow(unused)]
+#![forbid(illegal_floating_point_literal_pattern)]
+
+fn main() {
+    let x = 42.0;
+    match x {
+        5.0 => {}, //~ ERROR floating-point literals cannot be used
+                   //~| WARNING hard error
+        5.0f32 => {}, //~ ERROR floating-point literals cannot be used
+                      //~| WARNING hard error
+        -5.0 => {}, //~ ERROR floating-point literals cannot be used
+                    //~| WARNING hard error
+        1.0 .. 33.0 => {}, //~ ERROR floating-point literals cannot be used
+                           //~| WARNING hard error
+                           //~| ERROR floating-point literals cannot be used
+                           //~| WARNING hard error
+        39.0 ... 70.0 => {}, //~ ERROR floating-point literals cannot be used
+                             //~| WARNING hard error
+                             //~| ERROR floating-point literals cannot be used
+                             //~| WARNING hard error
+        _ => {},
+    };
+    let y = 5.0;
+    // Same for tuples
+    match (x, 5) {
+        (3.14, 1) => {}, //~ ERROR floating-point literals cannot be used
+                         //~| WARNING hard error
+                         //~| ERROR floating-point literals cannot be used
+                         //~| WARNING hard error
+        _ => {},
+    }
+    // Or structs
+    struct Foo { x: f32 };
+    match (Foo { x }) {
+        Foo { x: 2.0 } => {}, //~ ERROR floating-point literals cannot be used
+                              //~| WARNING hard error
+                              //~| ERROR floating-point literals cannot be used
+                              //~| WARNING hard error
+        _ => {},
+    }
+}
diff --git a/src/test/compile-fail/issue-41726.rs b/src/test/compile-fail/issue-41726.rs
new file mode 100644
index 00000000000..c8cd9209bce
--- /dev/null
+++ b/src/test/compile-fail/issue-41726.rs
@@ -0,0 +1,17 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::collections::HashMap;
+fn main() {
+    let things: HashMap<String, Vec<String>> = HashMap::new();
+    for src in things.keys() {
+        things[src.as_str()].sort(); //~ ERROR cannot borrow immutable
+    }
+}
diff --git a/src/test/compile-fail/issue-41742.rs b/src/test/compile-fail/issue-41742.rs
new file mode 100644
index 00000000000..067531e036a
--- /dev/null
+++ b/src/test/compile-fail/issue-41742.rs
@@ -0,0 +1,35 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::ops::{Index, IndexMut};
+
+struct S;
+struct H;
+
+impl S {
+    fn f(&mut self) {}
+}
+
+impl Index<u32> for H {
+    type Output = S;
+    fn index(&self, index: u32) -> &S {
+        unimplemented!()
+    }
+}
+
+impl IndexMut<u32> for H {
+    fn index_mut(&mut self, index: u32) -> &mut S {
+        unimplemented!()
+    }
+}
+
+fn main() {
+    H["?"].f(); //~ ERROR mismatched types
+}
diff --git a/src/test/compile-fail/non-exhaustive-match.rs b/src/test/compile-fail/non-exhaustive-match.rs
index 74e728d713b..13b62429f46 100644
--- a/src/test/compile-fail/non-exhaustive-match.rs
+++ b/src/test/compile-fail/non-exhaustive-match.rs
@@ -9,6 +9,7 @@
 // except according to those terms.
 
 #![feature(slice_patterns)]
+#![allow(illegal_floating_point_literal_pattern)]
 
 enum t { a, b, }
 
diff --git a/src/test/compile-fail/regions-adjusted-lvalue-op.rs b/src/test/compile-fail/regions-adjusted-lvalue-op.rs
new file mode 100644
index 00000000000..167c8630707
--- /dev/null
+++ b/src/test/compile-fail/regions-adjusted-lvalue-op.rs
@@ -0,0 +1,26 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// check that we link regions in mutable lvalue ops correctly - issue #41774
+
+struct Data(i32);
+
+trait OhNo {
+    fn oh_no(&mut self, other: &Vec<Data>) { loop {} }
+}
+
+impl OhNo for Data {}
+impl OhNo for [Data] {}
+
+fn main() {
+    let mut v = vec![Data(0)];
+    v[0].oh_no(&v); //~ ERROR cannot borrow `v` as immutable because
+    (*v).oh_no(&v); //~ ERROR cannot borrow `v` as immutable because
+}
diff --git a/src/test/compile-fail/type-recursive.rs b/src/test/compile-fail/type-recursive.rs
index 7b56c6c15eb..5dd76ce32c7 100644
--- a/src/test/compile-fail/type-recursive.rs
+++ b/src/test/compile-fail/type-recursive.rs
@@ -11,7 +11,7 @@
 struct t1 { //~ ERROR E0072
             //~| NOTE recursive type has infinite size
     foo: isize,
-    foolish: t1
+    foolish: t1  //~ NOTE recursive without indirection
 }
 
 fn main() { }
diff --git a/src/test/compile-fail/variance-regions-direct.rs b/src/test/compile-fail/variance-regions-direct.rs
index bf46edcfab8..cd047cc580f 100644
--- a/src/test/compile-fail/variance-regions-direct.rs
+++ b/src/test/compile-fail/variance-regions-direct.rs
@@ -60,7 +60,6 @@ struct Test6<'a, 'b:'a> { //~ ERROR [-, o]
 
 #[rustc_variance]
 struct Test7<'a> { //~ ERROR [*]
-    //~^ ERROR parameter `'a` is never used
     x: isize
 }
 
diff --git a/src/test/compile-fail/variance-regions-indirect.rs b/src/test/compile-fail/variance-regions-indirect.rs
index e28828f62e5..60d4d73fe88 100644
--- a/src/test/compile-fail/variance-regions-indirect.rs
+++ b/src/test/compile-fail/variance-regions-indirect.rs
@@ -16,7 +16,6 @@
 
 #[rustc_variance]
 enum Base<'a, 'b, 'c:'b, 'd> { //~ ERROR [+, -, o, *]
-    //~^ ERROR parameter `'d` is never used
     Test8A(extern "Rust" fn(&'a isize)),
     Test8B(&'b [isize]),
     Test8C(&'b mut &'c str),
@@ -24,19 +23,16 @@ enum Base<'a, 'b, 'c:'b, 'd> { //~ ERROR [+, -, o, *]
 
 #[rustc_variance]
 struct Derived1<'w, 'x:'y, 'y, 'z> { //~ ERROR [*, o, -, +]
-    //~^ ERROR parameter `'w` is never used
     f: Base<'z, 'y, 'x, 'w>
 }
 
 #[rustc_variance] // Combine - and + to yield o
 struct Derived2<'a, 'b:'a, 'c> { //~ ERROR [o, o, *]
-    //~^ ERROR parameter `'c` is never used
     f: Base<'a, 'a, 'b, 'c>
 }
 
 #[rustc_variance] // Combine + and o to yield o (just pay attention to 'a here)
 struct Derived3<'a:'b, 'b, 'c> { //~ ERROR [o, -, *]
-    //~^ ERROR parameter `'c` is never used
     f: Base<'a, 'b, 'a, 'c>
 }
 
diff --git a/src/test/compile-fail/variance-trait-bounds.rs b/src/test/compile-fail/variance-trait-bounds.rs
index 4c737a7594d..58fb785c48c 100644
--- a/src/test/compile-fail/variance-trait-bounds.rs
+++ b/src/test/compile-fail/variance-trait-bounds.rs
@@ -30,8 +30,7 @@ struct TestStruct<U,T:Setter<U>> { //~ ERROR [+, +]
 }
 
 #[rustc_variance]
-enum TestEnum<U,T:Setter<U>> {//~ ERROR [*, +]
-    //~^ ERROR parameter `U` is never used
+enum TestEnum<U,T:Setter<U>> { //~ ERROR [*, +]
     Foo(T)
 }
 
@@ -51,13 +50,11 @@ trait TestTrait3<U> { //~ ERROR [o, o]
 
 #[rustc_variance]
 struct TestContraStruct<U,T:Setter<U>> { //~ ERROR [*, +]
-    //~^ ERROR parameter `U` is never used
     t: T
 }
 
 #[rustc_variance]
 struct TestBox<U,T:Getter<U>+Setter<U>> { //~ ERROR [*, +]
-    //~^ ERROR parameter `U` is never used
     t: T
 }
 
diff --git a/src/test/incremental/remapped_paths_cc/auxiliary/extern_crate.rs b/src/test/incremental/remapped_paths_cc/auxiliary/extern_crate.rs
new file mode 100644
index 00000000000..09db90d618b
--- /dev/null
+++ b/src/test/incremental/remapped_paths_cc/auxiliary/extern_crate.rs
@@ -0,0 +1,24 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-tidy-linelength
+
+// aux-build:extern_crate.rs
+//[rpass1] compile-flags: -g
+//[rpass2] compile-flags: -g
+//[rpass3] compile-flags: -g -Zremap-path-prefix-from={{src-base}} -Zremap-path-prefix-to=/the/src
+
+#![feature(rustc_attrs)]
+#![crate_type="rlib"]
+
+#[inline(always)]
+pub fn inline_fn() {
+    println!("test");
+}
diff --git a/src/test/incremental/remapped_paths_cc/main.rs b/src/test/incremental/remapped_paths_cc/main.rs
new file mode 100644
index 00000000000..8a8c658accc
--- /dev/null
+++ b/src/test/incremental/remapped_paths_cc/main.rs
@@ -0,0 +1,42 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// revisions:rpass1 rpass2 rpass3
+// compile-flags: -Z query-dep-graph -g
+// aux-build:extern_crate.rs
+
+
+// This test case makes sure that we detect if paths emitted into debuginfo
+// are changed, even when the change happens in an external crate.
+
+#![feature(rustc_attrs)]
+
+#![rustc_partition_reused(module="main", cfg="rpass2")]
+#![rustc_partition_reused(module="main-some_mod", cfg="rpass2")]
+#![rustc_partition_reused(module="main", cfg="rpass3")]
+#![rustc_partition_translated(module="main-some_mod", cfg="rpass3")]
+
+extern crate extern_crate;
+
+#[rustc_clean(label="TransCrateItem", cfg="rpass2")]
+#[rustc_clean(label="TransCrateItem", cfg="rpass3")]
+fn main() {
+    some_mod::some_fn();
+}
+
+mod some_mod {
+    use extern_crate;
+
+    #[rustc_clean(label="TransCrateItem", cfg="rpass2")]
+    #[rustc_dirty(label="TransCrateItem", cfg="rpass3")]
+    pub fn some_fn() {
+        extern_crate::inline_fn();
+    }
+}
diff --git a/src/test/parse-fail/lex-bare-cr-string-literal-doc-comment.rs b/src/test/parse-fail/lex-bare-cr-string-literal-doc-comment.rs
index f8943057543..ac085d47511 100644
--- a/src/test/parse-fail/lex-bare-cr-string-literal-doc-comment.rs
+++ b/src/test/parse-fail/lex-bare-cr-string-literal-doc-comment.rs
@@ -21,6 +21,12 @@ pub fn bar() {}
 //~^^ ERROR: bare CR not allowed in block doc-comment
 
 fn main() {
+    //! doc comment with bare CR: '
'
+    //~^ ERROR: bare CR not allowed in doc-comment
+
+    /*! block doc comment with bare CR: '
' */
+    //~^ ERROR: bare CR not allowed in block doc-comment
+
     // the following string literal has a bare CR in it
     let _s = "foo
bar"; //~ ERROR: bare CR not allowed in string
 
diff --git a/src/test/run-make/tools.mk b/src/test/run-make/tools.mk
index 1db87d474bd..693573d53a4 100644
--- a/src/test/run-make/tools.mk
+++ b/src/test/run-make/tools.mk
@@ -72,6 +72,7 @@ else
 endif
 else
 ifeq ($(UNAME),Darwin)
+	EXTRACFLAGS := -lresolv
 else
 ifeq ($(UNAME),FreeBSD)
 	EXTRACFLAGS := -lm -lpthread -lgcc_s
diff --git a/src/test/run-make/trace-macros-flag/Makefile b/src/test/run-make/trace-macros-flag/Makefile
deleted file mode 100644
index 3338e394e0e..00000000000
--- a/src/test/run-make/trace-macros-flag/Makefile
+++ /dev/null
@@ -1,9 +0,0 @@
-# This test verifies that "-Z trace-macros"  works as it should. The traditional
-# "hello world" program provides a small example of this as not only println! is
-# listed, but also print! (since println! expands to this)
-
--include ../tools.mk
-
-all:
-	$(RUSTC) -Z trace-macros hello.rs > $(TMPDIR)/hello.out
-	diff -u $(TMPDIR)/hello.out hello.trace
diff --git a/src/test/run-make/trace-macros-flag/hello.trace b/src/test/run-make/trace-macros-flag/hello.trace
deleted file mode 100644
index cf733339ead..00000000000
--- a/src/test/run-make/trace-macros-flag/hello.trace
+++ /dev/null
@@ -1,2 +0,0 @@
-println! { "Hello, World!" }
-print! { concat ! ( "Hello, World!" , "\n" ) }
diff --git a/src/test/run-pass-fulldeps/auxiliary/issue_24106.rs b/src/test/run-pass-fulldeps/auxiliary/issue_24106.rs
new file mode 100644
index 00000000000..745fbbe769e
--- /dev/null
+++ b/src/test/run-pass-fulldeps/auxiliary/issue_24106.rs
@@ -0,0 +1,23 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type="lib"]
+
+enum E { E0 = 0, E1 = 1 }
+const E0_U8: u8 = E::E0 as u8;
+const E1_U8: u8 = E::E1 as u8;
+
+pub fn go<T>() {
+    match 0 {
+        E0_U8 => (),
+        E1_U8 => (),
+        _ => (),
+    }
+}
diff --git a/src/test/run-pass-fulldeps/issue_24106.rs b/src/test/run-pass-fulldeps/issue_24106.rs
new file mode 100644
index 00000000000..7cfd11537f4
--- /dev/null
+++ b/src/test/run-pass-fulldeps/issue_24106.rs
@@ -0,0 +1,17 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:issue_24106.rs
+
+extern crate issue_24106;
+
+fn main() {
+    issue_24106::go::<()>();
+}
diff --git a/src/test/run-pass/associated-const-type-parameters.rs b/src/test/run-pass/associated-const-type-parameters.rs
index e3d1761dfff..b276589f0c4 100644
--- a/src/test/run-pass/associated-const-type-parameters.rs
+++ b/src/test/run-pass/associated-const-type-parameters.rs
@@ -27,6 +27,12 @@ impl Foo for Def {
     const X: i32 = 97;
 }
 
+struct Proxy<T>(T);
+
+impl<T: Foo> Foo for Proxy<T> {
+    const X: i32 = T::X;
+}
+
 fn sub<A: Foo, B: Foo>() -> i32 {
     A::X - B::X
 }
@@ -38,4 +44,7 @@ fn main() {
     assert_eq!(97, Def::get_x());
     assert_eq!(-86, sub::<Abc, Def>());
     assert_eq!(86, sub::<Def, Abc>());
+    assert_eq!(-86, sub::<Proxy<Abc>, Def>());
+    assert_eq!(-86, sub::<Abc, Proxy<Def>>());
+    assert_eq!(86, sub::<Proxy<Def>, Proxy<Abc>>());
 }
diff --git a/src/test/run-pass/closure_to_fn_coercion-expected-types.rs b/src/test/run-pass/closure_to_fn_coercion-expected-types.rs
new file mode 100644
index 00000000000..7214ebfaf07
--- /dev/null
+++ b/src/test/run-pass/closure_to_fn_coercion-expected-types.rs
@@ -0,0 +1,17 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+// Ensure that we deduce expected argument types when a `fn()` type is expected (#41755)
+
+#![feature(closure_to_fn_coercion)]
+fn foo(f: fn(Vec<u32>) -> usize) { }
+
+fn main() {
+    foo(|x| x.len())
+}
diff --git a/src/test/run-pass/issue-22066.rs b/src/test/run-pass/issue-22066.rs
new file mode 100644
index 00000000000..2817ef77108
--- /dev/null
+++ b/src/test/run-pass/issue-22066.rs
@@ -0,0 +1,21 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub trait LineFormatter<'a> {
+    type Iter: Iterator<Item=&'a str> + 'a;
+    fn iter(&'a self, line: &'a str) -> Self::Iter;
+
+    fn dimensions(&'a self, line: &'a str) {
+        let iter: Self::Iter = self.iter(line);
+        <_ as IntoIterator>::into_iter(iter);
+    }
+}
+
+fn main() {}
\ No newline at end of file
diff --git a/src/test/run-pass/issue-41697.rs b/src/test/run-pass/issue-41697.rs
new file mode 100644
index 00000000000..d59b6a16562
--- /dev/null
+++ b/src/test/run-pass/issue-41697.rs
@@ -0,0 +1,50 @@
+// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// compile-flags:-Zdump-mir=NEVER_MATCHED
+
+// Regression test for #41697. Using dump-mir was triggering
+// artificial cycles: during type-checking, we had to get the MIR for
+// the constant expressions in `[u8; 2]`, which in turn would trigger
+// an attempt to get the item-path, which in turn would request the
+// types of the impl, which would trigger a cycle. We supressed this
+// cycle now by forcing mir-dump to avoid asking for types of an impl.
+
+#![feature(rustc_attrs)]
+
+use std::sync::Arc;
+
+trait Foo {
+    fn get(&self) -> [u8; 2];
+}
+
+impl Foo for [u8; 2] {
+    fn get(&self) -> [u8; 2] {
+        *self
+    }
+}
+
+struct Bar<T: ?Sized>(T);
+
+fn unsize_fat_ptr<'a>(x: &'a Bar<Foo + Send + 'a>) -> &'a Bar<Foo + 'a> {
+    x
+}
+
+fn unsize_nested_fat_ptr(x: Arc<Foo + Send>) -> Arc<Foo> {
+    x
+}
+
+fn main() {
+    let x: Box<Bar<Foo + Send>> = Box::new(Bar([1,2]));
+    assert_eq!(unsize_fat_ptr(&*x).0.get(), [1, 2]);
+
+    let x: Arc<Foo + Send> = Arc::new([3, 4]);
+    assert_eq!(unsize_nested_fat_ptr(x).get(), [3, 4]);
+}
diff --git a/src/test/run-pass/lex-bare-cr-nondoc-comment.rs b/src/test/run-pass/lex-bare-cr-nondoc-comment.rs
new file mode 100644
index 00000000000..ba949ca8881
--- /dev/null
+++ b/src/test/run-pass/lex-bare-cr-nondoc-comment.rs
@@ -0,0 +1,18 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-tidy-cr
+
+// nondoc comment with bare CR: '
'
+//// nondoc comment with bare CR: '
'
+/* block nondoc comment with bare CR: '
' */
+
+fn main() {
+}
diff --git a/src/test/rustdoc/issue-41783.rs b/src/test/rustdoc/issue-41783.rs
new file mode 100644
index 00000000000..3933b8bcbb8
--- /dev/null
+++ b/src/test/rustdoc/issue-41783.rs
@@ -0,0 +1,25 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// @has issue_41783/struct.Foo.html
+// @!has - 'space'
+// @!has - 'comment'
+// @has - '# <span class="ident">single'
+// @has - '#<span class="attribute"># <span class="ident">double</span>'
+// @has - '#<span class="attribute">#<span class="attribute"># <span class="ident">triple</span>'
+
+/// ```no_run
+/// # # space
+/// # comment
+/// ## single
+/// ### double
+/// #### triple
+/// ```
+pub struct Foo;
diff --git a/src/test/ui/did_you_mean/issue-41679.rs b/src/test/ui/did_you_mean/issue-41679.rs
new file mode 100644
index 00000000000..5091b9efc34
--- /dev/null
+++ b/src/test/ui/did_you_mean/issue-41679.rs
@@ -0,0 +1,13 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn main() {
+    let x = ~1;
+}
diff --git a/src/test/ui/did_you_mean/issue-41679.stderr b/src/test/ui/did_you_mean/issue-41679.stderr
new file mode 100644
index 00000000000..2abbbf65ba9
--- /dev/null
+++ b/src/test/ui/did_you_mean/issue-41679.stderr
@@ -0,0 +1,10 @@
+error: `~` can not be used as a unary operator
+  --> $DIR/issue-41679.rs:12:13
+   |
+12 |     let x = ~1;
+   |             ^ did you mean `!`?
+   |
+   = help: use `!` instead of `~` if you meant to perform bitwise negation
+
+error: aborting due to previous error
+
diff --git a/src/test/ui/issue-41652/auxiliary/issue_41652_b.rs b/src/test/ui/issue-41652/auxiliary/issue_41652_b.rs
new file mode 100644
index 00000000000..0b714432f16
--- /dev/null
+++ b/src/test/ui/issue-41652/auxiliary/issue_41652_b.rs
@@ -0,0 +1,16 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub trait Tr {
+    // Note: The function needs to be declared over multiple lines to reproduce
+    // the crash. DO NOT reformat.
+    fn f()
+        where Self: Sized;
+}
diff --git a/src/test/ui/issue-41652/issue_41652.rs b/src/test/ui/issue-41652/issue_41652.rs
new file mode 100644
index 00000000000..1874ee6cd3a
--- /dev/null
+++ b/src/test/ui/issue-41652/issue_41652.rs
@@ -0,0 +1,26 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:issue_41652_b.rs
+
+extern crate issue_41652_b;
+
+struct S;
+
+impl issue_41652_b::Tr for S {
+    fn f() {
+        3.f()
+        //~^ ERROR no method named `f` found for type `{integer}` in the current scope
+        //~| NOTE found the following associated functions
+        //~| NOTE candidate #1 is defined in the trait `issue_41652_b::Tr`
+    }
+}
+
+fn main() {}
diff --git a/src/test/ui/issue-41652/issue_41652.stderr b/src/test/ui/issue-41652/issue_41652.stderr
new file mode 100644
index 00000000000..4d33a99f6a3
--- /dev/null
+++ b/src/test/ui/issue-41652/issue_41652.stderr
@@ -0,0 +1,12 @@
+error: no method named `f` found for type `{integer}` in the current scope
+  --> $DIR/issue_41652.rs:19:11
+   |
+19 |         3.f()
+   |           ^
+   |
+   = note: found the following associated functions; to be used as methods, functions must have a `self` parameter
+note: candidate #1 is defined in the trait `issue_41652_b::Tr`
+   = help: to disambiguate the method call, write `issue_41652_b::Tr::f(3)` instead
+
+error: aborting due to previous error
+
diff --git a/src/test/run-make/trace-macros-flag/hello.rs b/src/test/ui/macros/trace-macro.rs
index 42d3d4c799d..34f674ae016 100644
--- a/src/test/run-make/trace-macros-flag/hello.rs
+++ b/src/test/ui/macros/trace-macro.rs
@@ -8,6 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+// compile-flags: -Z trace-macros
+
 fn main() {
     println!("Hello, World!");
 }
diff --git a/src/test/ui/macros/trace-macro.stderr b/src/test/ui/macros/trace-macro.stderr
new file mode 100644
index 00000000000..09117a4ca74
--- /dev/null
+++ b/src/test/ui/macros/trace-macro.stderr
@@ -0,0 +1,9 @@
+note: trace_macro
+  --> $DIR/trace-macro.rs:14:5
+   |
+14 |     println!("Hello, World!");
+   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^
+   |
+   = note: expands to `println! { "Hello, World!" }`
+   = note: expands to `print! { concat ! ( "Hello, World!" , "/n" ) }`
+
diff --git a/src/test/ui/span/E0072.stderr b/src/test/ui/span/E0072.stderr
index 5204390ef9d..1f6dd6b1d16 100644
--- a/src/test/ui/span/E0072.stderr
+++ b/src/test/ui/span/E0072.stderr
@@ -3,6 +3,9 @@ error[E0072]: recursive type `ListNode` has infinite size
    |
 11 | struct ListNode {
    | ^^^^^^^^^^^^^^^ recursive type has infinite size
+12 |     head: u8,
+13 |     tail: Option<ListNode>,
+   |     ---------------------- recursive without indirection
    |
    = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `ListNode` representable
 
diff --git a/src/test/ui/span/multiline-span-E0072.stderr b/src/test/ui/span/multiline-span-E0072.stderr
index 9c6816e7363..a06cbd04deb 100644
--- a/src/test/ui/span/multiline-span-E0072.stderr
+++ b/src/test/ui/span/multiline-span-E0072.stderr
@@ -6,6 +6,7 @@ error[E0072]: recursive type `ListNode` has infinite size
 14 | | {
 15 | |     head: u8,
 16 | |     tail: Option<ListNode>,
+   | |     ---------------------- recursive without indirection
 17 | | }
    | |_^ recursive type has infinite size
    |
diff --git a/src/test/ui/span/recursive-type-field.rs b/src/test/ui/span/recursive-type-field.rs
new file mode 100644
index 00000000000..6fef4d30f7a
--- /dev/null
+++ b/src/test/ui/span/recursive-type-field.rs
@@ -0,0 +1,28 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::rc::Rc;
+
+struct Foo<'a> {
+    bar: Bar<'a>,
+    b: Rc<Bar<'a>>,
+}
+
+struct Bar<'a> {
+    y: (Foo<'a>, Foo<'a>),
+    z: Option<Bar<'a>>,
+    a: &'a Foo<'a>,
+    c: &'a [Bar<'a>],
+    d: [Bar<'a>; 1],
+    e: Foo<'a>,
+    x: Bar<'a>,
+}
+
+fn main() {}
diff --git a/src/test/ui/span/recursive-type-field.stderr b/src/test/ui/span/recursive-type-field.stderr
new file mode 100644
index 00000000000..b4d0b5a6a25
--- /dev/null
+++ b/src/test/ui/span/recursive-type-field.stderr
@@ -0,0 +1,31 @@
+error[E0072]: recursive type `Foo` has infinite size
+  --> $DIR/recursive-type-field.rs:13:1
+   |
+13 | struct Foo<'a> {
+   | ^^^^^^^^^^^^^^ recursive type has infinite size
+14 |     bar: Bar<'a>,
+   |     ------------ recursive without indirection
+   |
+   = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable
+
+error[E0072]: recursive type `Bar` has infinite size
+  --> $DIR/recursive-type-field.rs:18:1
+   |
+18 | struct Bar<'a> {
+   | ^^^^^^^^^^^^^^ recursive type has infinite size
+19 |     y: (Foo<'a>, Foo<'a>),
+   |     --------------------- recursive without indirection
+20 |     z: Option<Bar<'a>>,
+   |     ------------------ recursive without indirection
+...
+23 |     d: [Bar<'a>; 1],
+   |     --------------- recursive without indirection
+24 |     e: Foo<'a>,
+   |     ---------- recursive without indirection
+25 |     x: Bar<'a>,
+   |     ---------- recursive without indirection
+   |
+   = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Bar` representable
+
+error: aborting due to 2 previous errors
+
diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs
index a8cb30da435..ba37863b1f6 100644
--- a/src/tools/build-manifest/src/main.rs
+++ b/src/tools/build-manifest/src/main.rs
@@ -116,10 +116,26 @@ struct Target {
     available: bool,
     url: Option<String>,
     hash: Option<String>,
+    xz_url: Option<String>,
+    xz_hash: Option<String>,
     components: Option<Vec<Component>>,
     extensions: Option<Vec<Component>>,
 }
 
+impl Target {
+    fn unavailable() -> Target {
+        Target {
+            available: false,
+            url: None,
+            hash: None,
+            xz_url: None,
+            xz_hash: None,
+            components: None,
+            extensions: None,
+        }
+    }
+}
+
 #[derive(RustcEncodable)]
 struct Component {
     pkg: String,
@@ -242,16 +258,12 @@ impl Builder {
             let digest = match self.digests.remove(&filename) {
                 Some(digest) => digest,
                 None => {
-                    pkg.target.insert(host.to_string(), Target {
-                        available: false,
-                        url: None,
-                        hash: None,
-                        components: None,
-                        extensions: None,
-                    });
+                    pkg.target.insert(host.to_string(), Target::unavailable());
                     continue
                 }
             };
+            let xz_filename = filename.replace(".tar.gz", ".tar.xz");
+            let xz_digest = self.digests.remove(&xz_filename);
             let mut components = Vec::new();
             let mut extensions = Vec::new();
 
@@ -293,8 +305,10 @@ impl Builder {
 
             pkg.target.insert(host.to_string(), Target {
                 available: true,
-                url: Some(self.url("rust", host)),
+                url: Some(self.url(&filename)),
                 hash: Some(digest),
+                xz_url: xz_digest.as_ref().map(|_| self.url(&xz_filename)),
+                xz_hash: xz_digest,
                 components: Some(components),
                 extensions: Some(extensions),
             });
@@ -312,21 +326,17 @@ impl Builder {
             let filename = self.filename(pkgname, name);
             let digest = match self.digests.remove(&filename) {
                 Some(digest) => digest,
-                None => {
-                    return (name.to_string(), Target {
-                        available: false,
-                        url: None,
-                        hash: None,
-                        components: None,
-                        extensions: None,
-                    })
-                }
+                None => return (name.to_string(), Target::unavailable()),
             };
+            let xz_filename = filename.replace(".tar.gz", ".tar.xz");
+            let xz_digest = self.digests.remove(&xz_filename);
 
             (name.to_string(), Target {
                 available: true,
-                url: Some(self.url(pkgname, name)),
+                url: Some(self.url(&filename)),
                 hash: Some(digest),
+                xz_url: xz_digest.as_ref().map(|_| self.url(&xz_filename)),
+                xz_hash: xz_digest,
                 components: None,
                 extensions: None,
             })
@@ -338,11 +348,11 @@ impl Builder {
         });
     }
 
-    fn url(&self, component: &str, target: &str) -> String {
+    fn url(&self, filename: &str) -> String {
         format!("{}/{}/{}",
                 self.s3_address,
                 self.date,
-                self.filename(component, target))
+                filename)
     }
 
     fn filename(&self, component: &str, target: &str) -> String {
diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs
index 4165ea685a5..6fc7f9f07ac 100644
--- a/src/tools/compiletest/src/main.rs
+++ b/src/tools/compiletest/src/main.rs
@@ -336,6 +336,7 @@ pub fn test_opts(config: &Config) -> test::TestOpts {
         test_threads: None,
         skip: vec![],
         list: false,
+        options: test::Options::new(),
     }
 }
 
diff --git a/src/tools/remote-test-client/src/main.rs b/src/tools/remote-test-client/src/main.rs
index 265354ff800..1a41b2c0f39 100644
--- a/src/tools/remote-test-client/src/main.rs
+++ b/src/tools/remote-test-client/src/main.rs
@@ -25,6 +25,8 @@ use std::process::{Command, Stdio};
 use std::thread;
 use std::time::Duration;
 
+const REMOTE_ADDR_ENV: &'static str = "TEST_DEVICE_ADDR";
+
 macro_rules! t {
     ($e:expr) => (match $e {
         Ok(e) => e,
@@ -56,7 +58,11 @@ fn spawn_emulator(target: &str,
                   server: &Path,
                   tmpdir: &Path,
                   rootfs: Option<PathBuf>) {
-    if target.contains("android") {
+    let device_address = env::var(REMOTE_ADDR_ENV).unwrap_or("127.0.0.1:12345".to_string());
+
+    if env::var(REMOTE_ADDR_ENV).is_ok() {
+        println!("Connecting to remote device {} ...", device_address);
+    } else if target.contains("android") {
         start_android_emulator(server);
     } else {
         let rootfs = rootfs.as_ref().expect("need rootfs on non-android");
@@ -66,7 +72,7 @@ fn spawn_emulator(target: &str,
     // Wait for the emulator to come online
     loop {
         let dur = Duration::from_millis(100);
-        if let Ok(mut client) = TcpStream::connect("127.0.0.1:12345") {
+        if let Ok(mut client) = TcpStream::connect(&device_address) {
             t!(client.set_read_timeout(Some(dur)));
             t!(client.set_write_timeout(Some(dur)));
             if client.write_all(b"ping").is_ok() {
@@ -162,7 +168,8 @@ fn start_qemu_emulator(rootfs: &Path, server: &Path, tmpdir: &Path) {
 }
 
 fn push(path: &Path) {
-    let client = t!(TcpStream::connect("127.0.0.1:12345"));
+    let device_address = env::var(REMOTE_ADDR_ENV).unwrap_or("127.0.0.1:12345".to_string());
+    let client = t!(TcpStream::connect(device_address));
     let mut client = BufWriter::new(client);
     t!(client.write_all(b"push"));
     send(path, &mut client);
@@ -178,7 +185,8 @@ fn push(path: &Path) {
 }
 
 fn run(files: String, args: Vec<String>) {
-    let client = t!(TcpStream::connect("127.0.0.1:12345"));
+    let device_address = env::var(REMOTE_ADDR_ENV).unwrap_or("127.0.0.1:12345".to_string());
+    let client = t!(TcpStream::connect(device_address));
     let mut client = BufWriter::new(client);
     t!(client.write_all(b"run "));
 
diff --git a/src/tools/remote-test-server/src/main.rs b/src/tools/remote-test-server/src/main.rs
index 308ccdbef77..ae13acd58bb 100644
--- a/src/tools/remote-test-server/src/main.rs
+++ b/src/tools/remote-test-server/src/main.rs
@@ -8,10 +8,10 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-/// This is a small server which is intended to run inside of an emulator. This
-/// server pairs with the `remote-test-client` program in this repository. The
-/// `remote-test-client` connects to this server over a TCP socket and performs
-/// work such as:
+/// This is a small server which is intended to run inside of an emulator or
+/// on a remote test device. This server pairs with the `remote-test-client`
+/// program in this repository. The `remote-test-client` connects to this
+/// server over a TCP socket and performs work such as:
 ///
 /// 1. Pushing shared libraries to the server
 /// 2. Running tests through the server
@@ -21,6 +21,7 @@
 /// basically custom format suiting our needs.
 
 use std::cmp;
+use std::env;
 use std::fs::{self, File, Permissions};
 use std::io::prelude::*;
 use std::io::{self, BufReader};
@@ -42,12 +43,54 @@ macro_rules! t {
 
 static TEST: AtomicUsize = ATOMIC_USIZE_INIT;
 
+struct Config {
+    pub remote: bool,
+    pub verbose: bool,
+}
+
+impl Config {
+    pub fn default() -> Config {
+        Config {
+            remote: false,
+            verbose: false,
+        }
+    }
+
+    pub fn parse_args() -> Config {
+        let mut config = Config::default();
+
+        let args = env::args().skip(1);
+        for argument in args {
+            match &argument[..] {
+                "remote" => {
+                    config.remote = true;
+                },
+                "verbose" | "-v" => {
+                    config.verbose = true;
+                }
+                arg => panic!("unknown argument: {}", arg),
+            }
+        }
+
+        config
+    }
+}
+
 fn main() {
     println!("starting test server");
+
+    let config = Config::parse_args();
+
+    let bind_addr = if cfg!(target_os = "android") || config.remote {
+        "0.0.0.0:12345"
+    } else {
+        "10.0.2.15:12345"
+    };
+
     let (listener, work) = if cfg!(target_os = "android") {
-        (t!(TcpListener::bind("0.0.0.0:12345")), "/data/tmp/work")
+        (t!(TcpListener::bind(bind_addr)), "/data/tmp/work")
     } else {
-        (t!(TcpListener::bind("10.0.2.15:12345")), "/tmp/work")
+        (t!(TcpListener::bind(bind_addr)), "/tmp/work")
     };
     println!("listening!");
 
diff --git a/src/tools/tidy/src/style.rs b/src/tools/tidy/src/style.rs
index d545a03aa5c..28a55a8763c 100644
--- a/src/tools/tidy/src/style.rs
+++ b/src/tools/tidy/src/style.rs
@@ -101,7 +101,7 @@ pub fn check(path: &Path, bad: &mut bool) {
            filename.starts_with(".#") {
             return
         }
-        if filename == "miniz.c" || filename.contains("jquery") {
+        if filename == "miniz.c" {
             return
         }