about summary refs log tree commit diff
diff options
context:
space:
mode:
authorEduard Burtescu <edy.burt@gmail.com>2016-08-30 14:24:14 +0300
committerEduard Burtescu <edy.burt@gmail.com>2016-09-20 20:07:16 +0300
commit91e7239db40372027a642bdbda19a6d593155a9f (patch)
treecf2599a98ef5b2ecbab405042d4184545887d4ff
parent97864d41a65d034fae21de35025e10151d765fef (diff)
rustc_metadata: combine DecodeContext and rbml::reader::Decoder.
-rw-r--r--src/librustc/middle/cstore.rs66
-rw-r--r--src/librustc/middle/region.rs17
-rw-r--r--src/librustc/ty/mod.rs16
-rw-r--r--src/librustc/ty/sty.rs32
-rw-r--r--src/librustc_metadata/astencode.rs478
-rw-r--r--src/librustc_metadata/common.rs53
-rw-r--r--src/librustc_metadata/decoder.rs122
-rw-r--r--src/librustc_metadata/encoder.rs26
-rw-r--r--src/librustc_metadata/lib.rs4
-rw-r--r--src/librustc_metadata/macros.rs46
-rw-r--r--src/librustc_metadata/rbml/reader.rs81
-rw-r--r--src/librustc_metadata/tls_context.rs84
12 files changed, 309 insertions, 716 deletions
diff --git a/src/librustc/middle/cstore.rs b/src/librustc/middle/cstore.rs
index 9dacb9062c1..c201c47ef5c 100644
--- a/src/librustc/middle/cstore.rs
+++ b/src/librustc/middle/cstore.rs
@@ -495,68 +495,4 @@ impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
 
 pub trait MacroLoader {
      fn load_crate(&mut self, extern_crate: &ast::Item, allows_macros: bool) -> Vec<LoadedMacro>;
-}
-
-/// Metadata encoding and decoding can make use of thread-local encoding and
-/// decoding contexts. These allow implementers of serialize::Encodable and
-/// Decodable to access information and datastructures that would otherwise not
-/// be available to them. For example, we can automatically translate def-id and
-/// span information during decoding because the decoding context knows which
-/// crate the data is decoded from. Or it allows to make ty::Ty decodable
-/// because the context has access to the TyCtxt that is needed for creating
-/// ty::Ty instances.
-///
-/// Note, however, that this only works for RBML-based encoding and decoding at
-/// the moment.
-pub mod tls {
-    use rbml::opaque::Decoder as OpaqueDecoder;
-    use std::cell::Cell;
-    use ty::{Ty, TyCtxt};
-    use ty::subst::Substs;
-    use hir::def_id::DefId;
-
-    /// Marker type used for the TLS slot.
-    /// The type context cannot be used directly because the TLS
-    /// in libstd doesn't allow types generic over lifetimes.
-    struct TlsPayload;
-
-    pub trait DecodingContext<'tcx> {
-        fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx>;
-        fn decode_ty(&self, decoder: &mut OpaqueDecoder) -> Ty<'tcx>;
-        fn decode_substs(&self, decoder: &mut OpaqueDecoder) -> &'tcx Substs<'tcx>;
-        fn translate_def_id(&self, def_id: DefId) -> DefId;
-    }
-
-    thread_local! {
-        static TLS_DECODING: Cell<Option<*const TlsPayload>> = Cell::new(None)
-    }
-
-    /// Execute f after pushing the given DecodingContext onto the TLS stack.
-    pub fn enter_decoding_context<'tcx, F, R>(dcx: &DecodingContext<'tcx>, f: F) -> R
-        where F: FnOnce(&DecodingContext<'tcx>) -> R
-    {
-        let tls_payload = dcx as *const _;
-        let tls_ptr = &tls_payload as *const _ as *const TlsPayload;
-        TLS_DECODING.with(|tls| {
-            let prev = tls.get();
-            tls.set(Some(tls_ptr));
-            let ret = f(dcx);
-            tls.set(prev);
-            ret
-        })
-    }
-
-    /// Execute f with access to the thread-local decoding context.
-    /// FIXME(eddyb) This is horribly unsound as it allows the
-    /// caler to pick any lifetime for 'tcx, including 'static.
-    pub fn with_decoding_context<'tcx, F, R>(f: F) -> R
-        where F: FnOnce(&DecodingContext<'tcx>) -> R,
-    {
-        unsafe {
-            TLS_DECODING.with(|tls| {
-                let tls = tls.get().unwrap();
-                f(*(tls as *mut &DecodingContext))
-            })
-        }
-    }
-}
+}
\ No newline at end of file
diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs
index fb99820f7c8..33110c61e8f 100644
--- a/src/librustc/middle/region.rs
+++ b/src/librustc/middle/region.rs
@@ -20,7 +20,6 @@ use dep_graph::DepNode;
 use hir::map as ast_map;
 use session::Session;
 use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
-use middle::cstore::InlinedItem;
 use ty;
 
 use std::cell::RefCell;
@@ -1256,19 +1255,3 @@ pub fn resolve_crate(sess: &Session, map: &ast_map::Map) -> RegionMaps {
     }
     return maps;
 }
-
-pub fn resolve_inlined_item(sess: &Session,
-                            region_maps: &RegionMaps,
-                            item: &InlinedItem) {
-    let mut visitor = RegionResolutionVisitor {
-        sess: sess,
-        region_maps: region_maps,
-        cx: Context {
-            root_id: None,
-            parent: ROOT_CODE_EXTENT,
-            var_parent: ROOT_CODE_EXTENT
-        },
-        terminating_scopes: NodeSet()
-    };
-    item.visit(&mut visitor);
-}
diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs
index 716b4672ec7..c49094cb688 100644
--- a/src/librustc/ty/mod.rs
+++ b/src/librustc/ty/mod.rs
@@ -21,7 +21,7 @@ pub use self::fold::TypeFoldable;
 use dep_graph::{self, DepNode};
 use hir::map as ast_map;
 use middle;
-use middle::cstore::{self, LOCAL_CRATE};
+use middle::cstore::LOCAL_CRATE;
 use hir::def::{Def, PathResolution, ExportMap};
 use hir::def_id::DefId;
 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
@@ -34,7 +34,7 @@ use util::common::MemoizationMap;
 use util::nodemap::NodeSet;
 use util::nodemap::FnvHashMap;
 
-use serialize::{self, Encodable, Encoder, Decodable, Decoder};
+use serialize::{self, Encodable, Encoder};
 use std::borrow::Cow;
 use std::cell::Cell;
 use std::hash::{Hash, Hasher};
@@ -1487,17 +1487,7 @@ impl<'tcx> Encodable for AdtDef<'tcx> {
     }
 }
 
-impl<'tcx> Decodable for AdtDef<'tcx> {
-    fn decode<D: Decoder>(d: &mut D) -> Result<AdtDef<'tcx>, D::Error> {
-        let def_id: DefId = Decodable::decode(d)?;
-
-        cstore::tls::with_decoding_context(|dcx| {
-            let def_id = dcx.translate_def_id(def_id);
-            Ok(dcx.tcx().lookup_adt_def(def_id))
-        })
-    }
-}
-
+impl<'tcx> serialize::UseSpecializedDecodable for AdtDef<'tcx> {}
 
 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
 pub enum AdtKind { Struct, Union, Enum }
diff --git a/src/librustc/ty/sty.rs b/src/librustc/ty/sty.rs
index 5f02b1be44a..5176fb665fb 100644
--- a/src/librustc/ty/sty.rs
+++ b/src/librustc/ty/sty.rs
@@ -10,7 +10,6 @@
 
 //! This module contains TypeVariants and its major components
 
-use middle::cstore;
 use hir::def_id::DefId;
 use middle::region;
 use ty::subst::Substs;
@@ -25,7 +24,7 @@ use syntax::abi;
 use syntax::ast::{self, Name};
 use syntax::parse::token::{keywords, InternedString};
 
-use serialize::{Decodable, Decoder, Encodable, Encoder};
+use serialize;
 
 use hir;
 
@@ -253,7 +252,7 @@ pub enum TypeVariants<'tcx> {
 /// closure C wind up influencing the decisions we ought to make for
 /// closure C (which would then require fixed point iteration to
 /// handle). Plus it fixes an ICE. :P
-#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
+#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable)]
 pub struct ClosureSubsts<'tcx> {
     /// Lifetime and type parameters from the enclosing function.
     /// These are separated out because trans wants to pass them around
@@ -266,23 +265,7 @@ pub struct ClosureSubsts<'tcx> {
     pub upvar_tys: &'tcx [Ty<'tcx>]
 }
 
-impl<'tcx> Encodable for ClosureSubsts<'tcx> {
-    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
-        (self.func_substs, self.upvar_tys).encode(s)
-    }
-}
-
-impl<'tcx> Decodable for ClosureSubsts<'tcx> {
-    fn decode<D: Decoder>(d: &mut D) -> Result<ClosureSubsts<'tcx>, D::Error> {
-        let (func_substs, upvar_tys) = Decodable::decode(d)?;
-        cstore::tls::with_decoding_context(|dcx| {
-            Ok(ClosureSubsts {
-                func_substs: func_substs,
-                upvar_tys: dcx.tcx().mk_type_list(upvar_tys)
-            })
-        })
-    }
-}
+impl<'tcx> serialize::UseSpecializedDecodable for ClosureSubsts<'tcx> {}
 
 #[derive(Clone, PartialEq, Eq, Hash)]
 pub struct TraitObject<'tcx> {
@@ -663,14 +646,7 @@ pub enum Region {
     ReErased,
 }
 
-impl<'tcx> Decodable for &'tcx Region {
-    fn decode<D: Decoder>(d: &mut D) -> Result<&'tcx Region, D::Error> {
-        let r = Decodable::decode(d)?;
-        cstore::tls::with_decoding_context(|dcx| {
-            Ok(dcx.tcx().mk_region(r))
-        })
-    }
-}
+impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Region {}
 
 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
 pub struct EarlyBoundRegion {
diff --git a/src/librustc_metadata/astencode.rs b/src/librustc_metadata/astencode.rs
index 3fd4d0cf272..673a31c55ab 100644
--- a/src/librustc_metadata/astencode.rs
+++ b/src/librustc_metadata/astencode.rs
@@ -13,7 +13,6 @@
 #![allow(unused_must_use)]
 
 use rustc::hir::map as ast_map;
-use rustc::session::Session;
 
 use rustc::hir;
 use rustc::hir::fold;
@@ -23,9 +22,9 @@ use rustc::hir::intravisit::{Visitor, IdRangeComputingVisitor, IdRange};
 use common as c;
 use cstore;
 use decoder;
-use encoder as e;
-use tydecode;
-use tyencode;
+
+use decoder::DecodeContext;
+use encoder::EncodeContext;
 
 use middle::cstore::{InlinedItem, InlinedItemRef};
 use rustc::ty::adjustment;
@@ -33,15 +32,12 @@ use rustc::ty::cast;
 use middle::const_qualif::ConstQualif;
 use rustc::hir::def::{self, Def};
 use rustc::hir::def_id::DefId;
-use middle::region;
-use rustc::ty::subst::Substs;
 use rustc::ty::{self, Ty, TyCtxt};
 
 use syntax::ast;
 use syntax::ptr::P;
 use syntax_pos;
 
-use std::cell::Cell;
 use std::io::SeekFrom;
 use std::io::prelude::*;
 
@@ -50,15 +46,6 @@ use rbml;
 use rustc_serialize::{Decodable, Decoder, DecoderHelpers};
 use rustc_serialize::{Encodable, EncoderHelpers};
 
-struct DecodeContext<'a, 'tcx: 'a> {
-    tcx: TyCtxt<'a, 'tcx, 'tcx>,
-    cdata: &'a cstore::CrateMetadata,
-    from_id_range: IdRange,
-    to_id_range: IdRange,
-    // Cache the last used filemap for translating spans as an optimization.
-    last_filemap_index: Cell<usize>,
-}
-
 trait tr {
     fn tr(&self, dcx: &DecodeContext) -> Self;
 }
@@ -66,7 +53,7 @@ trait tr {
 // ______________________________________________________________________
 // Top-level methods.
 
-pub fn encode_inlined_item(ecx: &mut e::EncodeContext, ii: InlinedItemRef) {
+pub fn encode_inlined_item(ecx: &mut EncodeContext, ii: InlinedItemRef) {
     let id = match ii {
         InlinedItemRef::Item(_, i) => i.id,
         InlinedItemRef::TraitItem(_, ti) => ti.id,
@@ -81,11 +68,16 @@ pub fn encode_inlined_item(ecx: &mut e::EncodeContext, ii: InlinedItemRef) {
     let id_range = inlined_item_id_range(&ii);
     assert_eq!(expected_id_range, id_range);
 
-    ecx.start_tag(c::tag_ast as usize);
-    id_range.encode(ecx);
-    ecx.start_tag(c::tag_tree as usize);
-    ecx.emit_opaque(|this| ii.encode(this));
+    ecx.start_tag(c::tag_ast);
+
+    ecx.start_tag(c::tag_id_range);
+    id_range.encode(&mut ecx.opaque());
     ecx.end_tag();
+
+    ecx.start_tag(c::tag_tree);
+    ii.encode(ecx);
+    ecx.end_tag();
+
     encode_side_tables_for_ii(ecx, &ii);
     ecx.end_tag();
 
@@ -121,37 +113,27 @@ pub fn decode_inlined_item<'a, 'tcx>(cdata: &cstore::CrateMetadata,
                                      orig_did: DefId)
                                      -> &'tcx InlinedItem {
     debug!("> Decoding inlined fn: {:?}", tcx.item_path_str(orig_did));
-    let mut ast_dsr = reader::Decoder::new(ast_doc);
-    let from_id_range = Decodable::decode(&mut ast_dsr).unwrap();
-    let to_id_range = reserve_id_range(&tcx.sess, from_id_range);
-    let dcx = &DecodeContext {
-        cdata: cdata,
-        tcx: tcx,
-        from_id_range: from_id_range,
-        to_id_range: to_id_range,
-        last_filemap_index: Cell::new(0)
-    };
-    let ii = ast_map::map_decoded_item(&dcx.tcx.map,
+    let id_range_doc = ast_doc.get(c::tag_id_range);
+    let from_id_range = IdRange::decode(&mut id_range_doc.opaque()).unwrap();
+    let mut dcx = DecodeContext::new(tcx, cdata, from_id_range,
+                                     ast_doc.get(c::tag_tree));
+    let ii = InlinedItem::decode(&mut dcx).unwrap();
+
+    let ii = ast_map::map_decoded_item(&tcx.map,
                                        parent_def_path,
                                        parent_did,
-                                       decode_ast(ast_doc),
-                                       dcx);
-    let name = match *ii {
-        InlinedItem::Item(_, ref i) => i.name,
-        InlinedItem::TraitItem(_, ref ti) => ti.name,
-        InlinedItem::ImplItem(_, ref ii) => ii.name
+                                       ii,
+                                       &dcx);
+
+    let item_node_id = match ii {
+        &InlinedItem::Item(_, ref i) => i.id,
+        &InlinedItem::TraitItem(_, ref ti) => ti.id,
+        &InlinedItem::ImplItem(_, ref ii) => ii.id
     };
-    debug!("Fn named: {}", name);
-    debug!("< Decoded inlined fn: {}::{}",
-            tcx.item_path_str(parent_did),
-            name);
-    region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, ii);
-    decode_side_tables(dcx, ast_doc);
-    copy_item_types(dcx, ii, orig_did);
-    if let InlinedItem::Item(_, ref i) = *ii {
-        debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<",
-               ::rustc::hir::print::item_to_string(&i));
-    }
+    let inlined_did = tcx.map.local_def_id(item_node_id);
+    tcx.register_item_type(inlined_did, tcx.lookup_item_type(orig_did));
+
+    decode_side_tables(&mut dcx, ast_doc);
 
     ii
 }
@@ -159,16 +141,6 @@ pub fn decode_inlined_item<'a, 'tcx>(cdata: &cstore::CrateMetadata,
 // ______________________________________________________________________
 // Enumerating the IDs which appear in an AST
 
-fn reserve_id_range(sess: &Session,
-                    from_id_range: IdRange) -> IdRange {
-    // Handle the case of an empty range:
-    if from_id_range.empty() { return from_id_range; }
-    let cnt = from_id_range.max - from_id_range.min;
-    let to_id_min = sess.reserve_node_ids(cnt);
-    let to_id_max = to_id_min + cnt;
-    IdRange { min: to_id_min, max: to_id_max }
-}
-
 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
     /// Translates an internal id, meaning a node id that is known to refer to some part of the
     /// item currently being inlined, such as a local variable or argument.  All naked node-ids
@@ -312,20 +284,9 @@ fn simplify_ast(ii: InlinedItemRef) -> (InlinedItem, IdRange) {
     (ii, fld.id_range)
 }
 
-fn decode_ast(item_doc: rbml::Doc) -> InlinedItem {
-    let chi_doc = item_doc.get(c::tag_tree as usize);
-    let mut rbml_r = reader::Decoder::new(chi_doc);
-    rbml_r.read_opaque(|decoder, _| Decodable::decode(decoder)).unwrap()
-}
-
 // ______________________________________________________________________
 // Encoding and decoding of ast::def
 
-fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> Def {
-    let def: Def = Decodable::decode(dsr).unwrap();
-    def.tr(dcx)
-}
-
 impl tr for Def {
     fn tr(&self, dcx: &DecodeContext) -> Def {
         match *self {
@@ -378,11 +339,9 @@ impl tr for Def {
 // ______________________________________________________________________
 // Encoding and decoding of freevar information
 
-impl<'a> reader::Decoder<'a> {
-    fn read_freevar_entry(&mut self, dcx: &DecodeContext)
-                          -> hir::Freevar {
-        let fv: hir::Freevar = Decodable::decode(self).unwrap();
-        fv.tr(dcx)
+impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
+    fn read_freevar_entry(&mut self) -> hir::Freevar {
+        hir::Freevar::decode(self).unwrap().tr(self)
     }
 }
 
@@ -398,7 +357,7 @@ impl tr for hir::Freevar {
 // ______________________________________________________________________
 // Encoding and decoding of MethodCallee
 
-impl<'a, 'tcx> e::EncodeContext<'a, 'tcx> {
+impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
     fn encode_method_callee(&mut self,
                             autoderef: u32,
                             method: &ty::MethodCallee<'tcx>) {
@@ -412,31 +371,29 @@ impl<'a, 'tcx> e::EncodeContext<'a, 'tcx> {
                 method.def_id.encode(this)
             });
             this.emit_struct_field("ty", 2, |this| {
-                Ok(this.emit_ty(method.ty))
+                method.ty.encode(this)
             });
             this.emit_struct_field("substs", 3, |this| {
-                Ok(this.emit_substs(&method.substs))
+                method.substs.encode(this)
             })
         }).unwrap();
     }
 }
 
-impl<'a, 'tcx> reader::Decoder<'a> {
-    fn read_method_callee<'b>(&mut self, dcx: &DecodeContext<'b, 'tcx>)
-                              -> (u32, ty::MethodCallee<'tcx>) {
-
+impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
+    fn read_method_callee(&mut self)  -> (u32, ty::MethodCallee<'tcx>) {
         self.read_struct("MethodCallee", 4, |this| {
             let autoderef = this.read_struct_field("autoderef", 0,
                                                    Decodable::decode).unwrap();
             Ok((autoderef, ty::MethodCallee {
                 def_id: this.read_struct_field("def_id", 1, |this| {
-                    DefId::decode(this).map(|d| d.tr(dcx))
+                    DefId::decode(this).map(|d| d.tr(this))
                 }).unwrap(),
                 ty: this.read_struct_field("ty", 2, |this| {
-                    Ok(this.read_ty(dcx))
+                    Ty::decode(this)
                 }).unwrap(),
                 substs: this.read_struct_field("substs", 3, |this| {
-                    Ok(this.read_substs(dcx))
+                    Decodable::decode(this)
                 }).unwrap()
             }))
         }).unwrap()
@@ -446,21 +403,7 @@ impl<'a, 'tcx> reader::Decoder<'a> {
 // ______________________________________________________________________
 // Encoding and decoding the side tables
 
-impl<'a, 'tcx> e::EncodeContext<'a, 'tcx> {
-    fn emit_region(&mut self, r: &'tcx ty::Region) {
-        let cx = self.ty_str_ctxt();
-        self.emit_opaque(|this| Ok(tyencode::enc_region(&mut this.cursor,
-                                                        &cx,
-                                                        r)));
-    }
-
-    fn emit_ty(&mut self, ty: Ty<'tcx>) {
-        let cx = self.ty_str_ctxt();
-        self.emit_opaque(|this| Ok(tyencode::enc_ty(&mut this.cursor,
-                                                    &cx,
-                                                    ty)));
-    }
-
+impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
     fn emit_upvar_capture(&mut self, capture: &ty::UpvarCapture<'tcx>) {
         use rustc_serialize::Encoder;
 
@@ -471,23 +414,14 @@ impl<'a, 'tcx> e::EncodeContext<'a, 'tcx> {
                 }
                 ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind, region }) => {
                     this.emit_enum_variant("ByRef", 2, 0, |this| {
-                        this.emit_enum_variant_arg(0,
-                            |this| kind.encode(this));
-                        this.emit_enum_variant_arg(1,
-                            |this| Ok(this.emit_region(region)))
+                        this.emit_enum_variant_arg(0, |this| kind.encode(this));
+                        this.emit_enum_variant_arg(1, |this| region.encode(this))
                     })
                 }
             }
         }).unwrap()
     }
 
-    fn emit_substs(&mut self, substs: &Substs<'tcx>) {
-        let cx = self.ty_str_ctxt();
-        self.emit_opaque(|this| Ok(tyencode::enc_substs(&mut this.cursor,
-                                                        &cx,
-                                                        substs)));
-    }
-
     fn emit_auto_adjustment(&mut self, adj: &adjustment::AutoAdjustment<'tcx>) {
         use rustc_serialize::Encoder;
 
@@ -518,7 +452,7 @@ impl<'a, 'tcx> e::EncodeContext<'a, 'tcx> {
 
                 adjustment::AdjustNeverToAny(ref ty) => {
                     this.emit_enum_variant("AdjustNeverToAny", 5, 1, |this| {
-                        this.emit_enum_variant_arg(0, |this| Ok(this.emit_ty(ty)))
+                        this.emit_enum_variant_arg(0, |this| ty.encode(this))
                     })
                 }
             }
@@ -532,8 +466,7 @@ impl<'a, 'tcx> e::EncodeContext<'a, 'tcx> {
             match autoref {
                 &adjustment::AutoPtr(r, m) => {
                     this.emit_enum_variant("AutoPtr", 0, 2, |this| {
-                        this.emit_enum_variant_arg(0,
-                            |this| Ok(this.emit_region(r)));
+                        this.emit_enum_variant_arg(0, |this| r.encode(this));
                         this.emit_enum_variant_arg(1, |this| m.encode(this))
                     })
                 }
@@ -562,24 +495,17 @@ impl<'a, 'tcx> e::EncodeContext<'a, 'tcx> {
             });
 
             this.emit_struct_field("unsize", 2, |this| {
-                this.emit_option(|this| {
-                    match auto_deref_ref.unsize {
-                        None => this.emit_option_none(),
-                        Some(target) => this.emit_option_some(|this| {
-                            Ok(this.emit_ty(target))
-                        })
-                    }
-                })
+                auto_deref_ref.unsize.encode(this)
             })
         });
     }
 
     fn tag<F>(&mut self,
-              tag_id: c::astencode_tag,
+              tag_id: usize,
               f: F) where
         F: FnOnce(&mut Self),
     {
-        self.start_tag(tag_id as usize);
+        self.start_tag(tag_id);
         f(self);
         self.end_tag();
     }
@@ -590,7 +516,7 @@ impl<'a, 'tcx> e::EncodeContext<'a, 'tcx> {
 }
 
 struct SideTableEncodingIdVisitor<'a, 'b:'a, 'tcx:'b> {
-    ecx: &'a mut e::EncodeContext<'b, 'tcx>,
+    ecx: &'a mut EncodeContext<'b, 'tcx>,
 }
 
 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for SideTableEncodingIdVisitor<'a, 'b, 'tcx> {
@@ -599,15 +525,15 @@ impl<'a, 'b, 'tcx, 'v> Visitor<'v> for SideTableEncodingIdVisitor<'a, 'b, 'tcx>
     }
 }
 
-fn encode_side_tables_for_ii(ecx: &mut e::EncodeContext, ii: &InlinedItem) {
-    ecx.start_tag(c::tag_table as usize);
+fn encode_side_tables_for_ii(ecx: &mut EncodeContext, ii: &InlinedItem) {
+    ecx.start_tag(c::tag_table);
     ii.visit(&mut SideTableEncodingIdVisitor {
         ecx: ecx
     });
     ecx.end_tag();
 }
 
-fn encode_side_tables_for_id(ecx: &mut e::EncodeContext, id: ast::NodeId) {
+fn encode_side_tables_for_id(ecx: &mut EncodeContext, id: ast::NodeId) {
     let tcx = ecx.tcx;
 
     debug!("Encoding side tables for id {}", id);
@@ -622,14 +548,14 @@ fn encode_side_tables_for_id(ecx: &mut e::EncodeContext, id: ast::NodeId) {
     if let Some(ty) = tcx.node_types().get(&id) {
         ecx.tag(c::tag_table_node_type, |ecx| {
             ecx.id(id);
-            ecx.emit_ty(*ty);
+            ty.encode(ecx);
         })
     }
 
     if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
         ecx.tag(c::tag_table_item_subst, |ecx| {
             ecx.id(id);
-            ecx.emit_substs(&item_substs.substs);
+            item_substs.substs.encode(ecx);
         })
     }
 
@@ -707,47 +633,8 @@ fn encode_side_tables_for_id(ecx: &mut e::EncodeContext, id: ast::NodeId) {
     }
 }
 
-impl<'a, 'tcx> reader::Decoder<'a> {
-    fn read_ty_encoded<'b, F, R>(&mut self, dcx: &DecodeContext<'b, 'tcx>, op: F) -> R
-        where F: for<'x> FnOnce(&mut tydecode::TyDecoder<'x,'tcx>) -> R
-    {
-        return self.read_opaque(|_, doc| {
-            debug!("read_ty_encoded({})", type_string(doc));
-            Ok(op(
-                &mut tydecode::TyDecoder::with_doc(
-                    dcx.tcx, dcx.cdata.cnum, doc,
-                    &mut |d| convert_def_id(dcx, d))))
-        }).unwrap();
-
-        fn type_string(doc: rbml::Doc) -> String {
-            let mut str = String::new();
-            for i in doc.start..doc.end {
-                str.push(doc.data[i] as char);
-            }
-            str
-        }
-    }
-    fn read_region<'b>(&mut self, dcx: &DecodeContext<'b, 'tcx>) -> &'tcx ty::Region {
-        // Note: regions types embed local node ids.  In principle, we
-        // should translate these node ids into the new decode
-        // context.  However, we do not bother, because region types
-        // are not used during trans. This also applies to read_ty.
-        return self.read_ty_encoded(dcx, |decoder| decoder.parse_region());
-    }
-    fn read_ty<'b>(&mut self, dcx: &DecodeContext<'b, 'tcx>) -> Ty<'tcx> {
-        return self.read_ty_encoded(dcx, |decoder| decoder.parse_ty());
-    }
-
-    fn read_substs<'b>(&mut self, dcx: &DecodeContext<'b, 'tcx>)
-                       -> &'tcx Substs<'tcx> {
-        self.read_opaque(|_, doc| {
-            Ok(tydecode::TyDecoder::with_doc(dcx.tcx, dcx.cdata.cnum, doc,
-                                             &mut |d| convert_def_id(dcx, d))
-               .parse_substs())
-        }).unwrap()
-    }
-    fn read_upvar_capture<'b>(&mut self, dcx: &DecodeContext<'b, 'tcx>)
-                              -> ty::UpvarCapture<'tcx> {
+impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
+    fn read_upvar_capture(&mut self) -> ty::UpvarCapture<'tcx> {
         self.read_enum("UpvarCapture", |this| {
             let variants = ["ByValue", "ByRef"];
             this.read_enum_variant(&variants, |this, i| {
@@ -757,15 +644,14 @@ impl<'a, 'tcx> reader::Decoder<'a> {
                         kind: this.read_enum_variant_arg(0,
                                   |this| Decodable::decode(this)).unwrap(),
                         region: this.read_enum_variant_arg(1,
-                                    |this| Ok(this.read_region(dcx))).unwrap()
+                                    |this| Decodable::decode(this)).unwrap()
                     }),
                     _ => bug!("bad enum variant for ty::UpvarCapture")
                 })
             })
         }).unwrap()
     }
-    fn read_auto_adjustment<'b>(&mut self, dcx: &DecodeContext<'b, 'tcx>)
-                                -> adjustment::AutoAdjustment<'tcx> {
+    fn read_auto_adjustment(&mut self) -> adjustment::AutoAdjustment<'tcx> {
         self.read_enum("AutoAdjustment", |this| {
             let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer",
                             "AdjustMutToConstPointer", "AdjustDerefRef",
@@ -778,13 +664,13 @@ impl<'a, 'tcx> reader::Decoder<'a> {
                     4 => {
                         let auto_deref_ref: adjustment::AutoDerefRef =
                             this.read_enum_variant_arg(0,
-                                |this| Ok(this.read_auto_deref_ref(dcx))).unwrap();
+                                |this| Ok(this.read_auto_deref_ref())).unwrap();
 
                         adjustment::AdjustDerefRef(auto_deref_ref)
                     }
                     5 => {
                         let ty: Ty<'tcx> = this.read_enum_variant_arg(0, |this| {
-                            Ok(this.read_ty(dcx))
+                            Ty::decode(this)
                         }).unwrap();
 
                         adjustment::AdjustNeverToAny(ty)
@@ -795,8 +681,7 @@ impl<'a, 'tcx> reader::Decoder<'a> {
         }).unwrap()
     }
 
-    fn read_auto_deref_ref<'b>(&mut self, dcx: &DecodeContext<'b, 'tcx>)
-                               -> adjustment::AutoDerefRef<'tcx> {
+    fn read_auto_deref_ref(&mut self) -> adjustment::AutoDerefRef<'tcx> {
         self.read_struct("AutoDerefRef", 2, |this| {
             Ok(adjustment::AutoDerefRef {
                 autoderefs: this.read_struct_field("autoderefs", 0, |this| {
@@ -805,27 +690,20 @@ impl<'a, 'tcx> reader::Decoder<'a> {
                 autoref: this.read_struct_field("autoref", 1, |this| {
                     this.read_option(|this, b| {
                         if b {
-                            Ok(Some(this.read_autoref(dcx)))
+                            Ok(Some(this.read_autoref()))
                         } else {
                             Ok(None)
                         }
                     })
                 }).unwrap(),
                 unsize: this.read_struct_field("unsize", 2, |this| {
-                    this.read_option(|this, b| {
-                        if b {
-                            Ok(Some(this.read_ty(dcx)))
-                        } else {
-                            Ok(None)
-                        }
-                    })
+                    Decodable::decode(this)
                 }).unwrap(),
             })
         }).unwrap()
     }
 
-    fn read_autoref<'b>(&mut self, dcx: &DecodeContext<'b, 'tcx>)
-                        -> adjustment::AutoRef<'tcx> {
+    fn read_autoref(&mut self) -> adjustment::AutoRef<'tcx> {
         self.read_enum("AutoRef", |this| {
             let variants = ["AutoPtr", "AutoUnsafe"];
             this.read_enum_variant(&variants, |this, i| {
@@ -833,7 +711,7 @@ impl<'a, 'tcx> reader::Decoder<'a> {
                     0 => {
                         let r: &'tcx ty::Region =
                             this.read_enum_variant_arg(0, |this| {
-                                Ok(this.read_region(dcx))
+                                Decodable::decode(this)
                             }).unwrap();
                         let m: hir::Mutability =
                             this.read_enum_variant_arg(1, |this| {
@@ -853,183 +731,77 @@ impl<'a, 'tcx> reader::Decoder<'a> {
             })
         }).unwrap()
     }
-
-    fn read_cast_kind<'b>(&mut self, _dcx: &DecodeContext<'b, 'tcx>)
-                          -> cast::CastKind
-    {
-        Decodable::decode(self).unwrap()
-    }
 }
 
-// Converts a def-id that appears in a type.  The correct
-// translation will depend on what kind of def-id this is.
-// This is a subtle point: type definitions are not
-// inlined into the current crate, so if the def-id names
-// a nominal type or type alias, then it should be
-// translated to refer to the source crate.
-//
-// However, *type parameters* are cloned along with the function
-// they are attached to.  So we should translate those def-ids
-// to refer to the new, cloned copy of the type parameter.
-// We only see references to free type parameters in the body of
-// an inlined function. In such cases, we need the def-id to
-// be a local id so that the TypeContents code is able to lookup
-// the relevant info in the ty_param_defs table.
-//
-// *Region parameters*, unfortunately, are another kettle of fish.
-// In such cases, def_id's can appear in types to distinguish
-// shadowed bound regions and so forth. It doesn't actually
-// matter so much what we do to these, since regions are erased
-// at trans time, but it's good to keep them consistent just in
-// case. We translate them with `tr_def_id()` which will map
-// the crate numbers back to the original source crate.
-//
-// Scopes will end up as being totally bogus. This can actually
-// be fixed though.
-//
-// Unboxed closures are cloned along with the function being
-// inlined, and all side tables use interned node IDs, so we
-// translate their def IDs accordingly.
-//
-// It'd be really nice to refactor the type repr to not include
-// def-ids so that all these distinctions were unnecessary.
-fn convert_def_id(dcx: &DecodeContext,
-                  did: DefId)
-                  -> DefId {
-    let r = dcx.tr_def_id(did);
-    debug!("convert_def_id(did={:?})={:?}", did, r);
-    return r;
-}
+fn decode_side_tables<'a, 'tcx>(dcx: &mut DecodeContext<'a, 'tcx>,
+                                ast_doc: rbml::Doc<'a>) {
+    for (tag, entry_doc) in reader::docs(ast_doc.get(c::tag_table)) {
+        dcx.rbml_r = reader::Decoder::new(entry_doc);
 
-fn decode_side_tables(dcx: &DecodeContext,
-                      ast_doc: rbml::Doc) {
-    let tbl_doc = ast_doc.get(c::tag_table as usize);
-    for (tag, entry_doc) in reader::docs(tbl_doc) {
-        let mut entry_dsr = reader::Decoder::new(entry_doc);
-        let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
+        let id0: ast::NodeId = Decodable::decode(dcx).unwrap();
         let id = dcx.tr_id(id0);
 
         debug!(">> Side table document with tag 0x{:x} \
                 found for id {} (orig {})",
                tag, id, id0);
-        let tag = tag as u32;
-        let decoded_tag: Option<c::astencode_tag> = c::astencode_tag::from_u32(tag);
-        match decoded_tag {
-            None => {
-                bug!("unknown tag found in side tables: {:x}", tag);
-            }
-            Some(value) => {
-                let val_dsr = &mut entry_dsr;
 
-                match value {
-                    c::tag_table_def => {
-                        let def = decode_def(dcx, val_dsr);
-                        dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution::new(def));
-                    }
-                    c::tag_table_node_type => {
-                        let ty = val_dsr.read_ty(dcx);
-                        debug!("inserting ty for node {}: {:?}",
-                               id,  ty);
-                        dcx.tcx.node_type_insert(id, ty);
-                    }
-                    c::tag_table_item_subst => {
-                        let item_substs = ty::ItemSubsts {
-                            substs: val_dsr.read_substs(dcx)
-                        };
-                        dcx.tcx.tables.borrow_mut().item_substs.insert(
-                            id, item_substs);
-                    }
-                    c::tag_table_freevars => {
-                        let fv_info = val_dsr.read_to_vec(|val_dsr| {
-                            Ok(val_dsr.read_freevar_entry(dcx))
-                        }).unwrap().into_iter().collect();
-                        dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
-                    }
-                    c::tag_table_upvar_capture_map => {
-                        let var_id: ast::NodeId = Decodable::decode(val_dsr).unwrap();
-                        let upvar_id = ty::UpvarId {
-                            var_id: dcx.tr_id(var_id),
-                            closure_expr_id: id
-                        };
-                        let ub = val_dsr.read_upvar_capture(dcx);
-                        dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub);
-                    }
-                    c::tag_table_method_map => {
-                        let (autoderef, method) = val_dsr.read_method_callee(dcx);
-                        let method_call = ty::MethodCall {
-                            expr_id: id,
-                            autoderef: autoderef
-                        };
-                        dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
-                    }
-                    c::tag_table_adjustments => {
-                        let adj =
-                            val_dsr.read_auto_adjustment(dcx);
-                        dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
-                    }
-                    c::tag_table_cast_kinds => {
-                        let cast_kind =
-                            val_dsr.read_cast_kind(dcx);
-                        dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
-                    }
-                    c::tag_table_const_qualif => {
-                        let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
-                        dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
-                    }
-                    _ => {
-                        bug!("unknown tag found in side tables: {:x}", tag);
-                    }
-                }
+        match tag {
+            c::tag_table_def => {
+                let def = Def::decode(dcx).unwrap().tr(dcx);
+                dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution::new(def));
             }
-        }
-
-        debug!(">< Side table doc loaded");
-    }
-}
-
-// copy the tcache entries from the original item to the new
-// inlined item
-fn copy_item_types(dcx: &DecodeContext, ii: &InlinedItem, orig_did: DefId) {
-    fn copy_item_type(dcx: &DecodeContext,
-                      inlined_id: ast::NodeId,
-                      remote_did: DefId) {
-        let inlined_did = dcx.tcx.map.local_def_id(inlined_id);
-        dcx.tcx.register_item_type(inlined_did,
-                                   dcx.tcx.lookup_item_type(remote_did));
-
-    }
-    // copy the entry for the item itself
-    let item_node_id = match ii {
-        &InlinedItem::Item(_, ref i) => i.id,
-        &InlinedItem::TraitItem(_, ref ti) => ti.id,
-        &InlinedItem::ImplItem(_, ref ii) => ii.id
-    };
-    copy_item_type(dcx, item_node_id, orig_did);
-
-    // copy the entries of inner items
-    if let &InlinedItem::Item(_, ref item) = ii {
-        match item.node {
-            hir::ItemEnum(ref def, _) => {
-                let orig_def = dcx.tcx.lookup_adt_def(orig_did);
-                for (i_variant, orig_variant) in
-                    def.variants.iter().zip(orig_def.variants.iter())
-                {
-                    debug!("astencode: copying variant {:?} => {:?}",
-                           orig_variant.did, i_variant.node.data.id());
-                    copy_item_type(dcx, i_variant.node.data.id(), orig_variant.did);
-                }
+            c::tag_table_node_type => {
+                let ty = Ty::decode(dcx).unwrap();
+                dcx.tcx.node_type_insert(id, ty);
             }
-            hir::ItemStruct(ref def, _) => {
-                if !def.is_struct() {
-                    let ctor_did = dcx.tcx.lookup_adt_def(orig_did)
-                        .struct_variant().did;
-                    debug!("astencode: copying ctor {:?} => {:?}", ctor_did,
-                           def.id());
-                    copy_item_type(dcx, def.id(), ctor_did);
-                }
+            c::tag_table_item_subst => {
+                let item_substs = ty::ItemSubsts {
+                    substs: Decodable::decode(dcx).unwrap()
+                };
+                dcx.tcx.tables.borrow_mut().item_substs.insert(
+                    id, item_substs);
+            }
+            c::tag_table_freevars => {
+                let fv_info = dcx.read_to_vec(|dcx| {
+                    Ok(dcx.read_freevar_entry())
+                }).unwrap().into_iter().collect();
+                dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
+            }
+            c::tag_table_upvar_capture_map => {
+                let var_id = ast::NodeId::decode(dcx).unwrap();
+                let upvar_id = ty::UpvarId {
+                    var_id: dcx.tr_id(var_id),
+                    closure_expr_id: id
+                };
+                let ub = dcx.read_upvar_capture();
+                dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub);
+            }
+            c::tag_table_method_map => {
+                let (autoderef, method) = dcx.read_method_callee();
+                let method_call = ty::MethodCall {
+                    expr_id: id,
+                    autoderef: autoderef
+                };
+                dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
+            }
+            c::tag_table_adjustments => {
+                let adj = dcx.read_auto_adjustment();
+                dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
+            }
+            c::tag_table_cast_kinds => {
+                let cast_kind = cast::CastKind::decode(dcx).unwrap();
+                dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
+            }
+            c::tag_table_const_qualif => {
+                let qualif = ConstQualif::decode(dcx).unwrap();
+                dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
+            }
+            _ => {
+                bug!("unknown tag found in side tables: {:x}", tag);
             }
-            _ => {}
         }
+
+        debug!(">< Side table doc loaded");
     }
 }
 
diff --git a/src/librustc_metadata/common.rs b/src/librustc_metadata/common.rs
index 29b9cc0d1d9..c18b417466f 100644
--- a/src/librustc_metadata/common.rs
+++ b/src/librustc_metadata/common.rs
@@ -10,8 +10,6 @@
 
 #![allow(non_camel_case_types, non_upper_case_globals)]
 
-pub use self::astencode_tag::*;
-
 // RBML enum definitions and utils shared by the encoder and decoder
 //
 // 0x00..0x1f: reserved for RBML generic type tags
@@ -97,33 +95,30 @@ pub const tag_items_data_item_reexport_def_id: usize = 0x47;
 pub const tag_items_data_item_reexport_name: usize = 0x48;
 
 // used to encode crate_ctxt side tables
-enum_from_u32! {
-    #[derive(Copy, Clone, PartialEq)]
-    #[repr(usize)]
-    pub enum astencode_tag { // Reserves 0x50 -- 0x6f
-        tag_ast = 0x50,
-
-        tag_tree = 0x51,
-
-        tag_mir = 0x52,
-
-        tag_table = 0x53,
-        // GAP 0x54, 0x55
-        tag_table_def = 0x56,
-        tag_table_node_type = 0x57,
-        tag_table_item_subst = 0x58,
-        tag_table_freevars = 0x59,
-        // GAP 0x5a, 0x5b, 0x5c, 0x5d, 0x5e
-        tag_table_method_map = 0x5f,
-        // GAP 0x60
-        tag_table_adjustments = 0x61,
-        // GAP 0x62, 0x63, 0x64, 0x65
-        tag_table_upvar_capture_map = 0x66,
-        // GAP 0x67, 0x68
-        tag_table_const_qualif = 0x69,
-        tag_table_cast_kinds = 0x6a,
-    }
-}
+pub const tag_ast: usize = 0x50;
+
+pub const tag_tree: usize = 0x51;
+
+pub const tag_mir: usize = 0x52;
+
+pub const tag_table: usize = 0x53;
+
+pub const tag_id_range: usize = 0x54;
+
+// GAP 0x55
+pub const tag_table_def: usize = 0x56;
+pub const tag_table_node_type: usize = 0x57;
+pub const tag_table_item_subst: usize = 0x58;
+pub const tag_table_freevars: usize = 0x59;
+// GAP 0x5a, 0x5b, 0x5c, 0x5d, 0x5e
+pub const tag_table_method_map: usize = 0x5f;
+// GAP 0x60
+pub const tag_table_adjustments: usize = 0x61;
+// GAP 0x62, 0x63, 0x64, 0x65
+pub const tag_table_upvar_capture_map: usize = 0x66;
+// GAP 0x67, 0x68
+pub const tag_table_const_qualif: usize = 0x69;
+pub const tag_table_cast_kinds: usize = 0x6a;
 
 pub const tag_item_trait_item_sort: usize = 0x70;
 
diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs
index b808aad1436..10c2747ab16 100644
--- a/src/librustc_metadata/decoder.rs
+++ b/src/librustc_metadata/decoder.rs
@@ -20,7 +20,6 @@ use common::*;
 use def_key;
 use encoder::def_to_u64;
 use index;
-use tls_context;
 use tydecode::TyDecoder;
 
 use rustc::hir::def_id::CRATE_DEF_INDEX;
@@ -29,15 +28,17 @@ use rustc::hir::map as hir_map;
 use rustc::hir::map::DefKey;
 use rustc::util::nodemap::FnvHashMap;
 use rustc::hir;
+use rustc::hir::intravisit::IdRange;
 use rustc::session::config::PanicStrategy;
 
 use middle::cstore::{InlinedItem, LinkagePreference};
-use middle::cstore::{DefLike, DlDef, DlField, DlImpl, tls};
+use middle::cstore::{DefLike, DlDef, DlField, DlImpl};
 use rustc::hir::def::Def;
 use rustc::hir::def_id::{DefId, DefIndex};
 use middle::lang_items;
 use rustc::ty::{ImplContainer, TraitContainer};
 use rustc::ty::{self, AdtKind, Ty, TyCtxt, TypeFoldable, VariantKind};
+use rustc::ty::subst::Substs;
 
 use rustc_const_math::ConstInt;
 
@@ -47,12 +48,13 @@ use rustc::mir::repr::Location;
 
 use std::cell::Cell;
 use std::io;
+use std::ops::{Deref, DerefMut};
 use std::rc::Rc;
 use std::str;
 
 use rbml::reader;
 use rbml;
-use rustc_serialize::Decodable;
+use rustc_serialize::{Decodable, Decoder, SpecializedDecoder};
 use syntax::attr;
 use syntax::parse::token;
 use syntax::ast;
@@ -60,6 +62,106 @@ use syntax::codemap;
 use syntax::print::pprust;
 use syntax_pos::{self, Span, BytePos, NO_EXPANSION};
 
+pub struct DecodeContext<'a, 'tcx: 'a> {
+    pub rbml_r: rbml::reader::Decoder<'a>,
+    pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
+    pub cdata: &'a cstore::CrateMetadata,
+    pub from_id_range: IdRange,
+    pub to_id_range: IdRange,
+    // Cache the last used filemap for translating spans as an optimization.
+    pub last_filemap_index: Cell<usize>,
+}
+
+impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
+    pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
+               cdata: &'a cstore::CrateMetadata,
+               from_id_range: IdRange,
+               doc: rbml::Doc<'a>)
+               -> DecodeContext<'a, 'tcx> {
+        // Handle the case of an empty range:
+        let to_id_range = if from_id_range.empty() {
+            from_id_range
+        } else {
+            let cnt = from_id_range.max - from_id_range.min;
+            let to_id_min = tcx.sess.reserve_node_ids(cnt);
+            let to_id_max = to_id_min + cnt;
+            IdRange { min: to_id_min, max: to_id_max }
+        };
+
+        DecodeContext {
+            rbml_r: reader::Decoder::new(doc),
+            cdata: cdata,
+            tcx: tcx,
+            from_id_range: from_id_range,
+            to_id_range: to_id_range,
+            last_filemap_index: Cell::new(0)
+        }
+    }
+
+    fn read_ty_encoded<F, R>(&mut self, op: F) -> R
+        where F: for<'x> FnOnce(&mut TyDecoder<'x,'tcx>) -> R
+    {
+        self.read_opaque(|this, doc| {
+            Ok(op(&mut TyDecoder::with_doc(
+                this.tcx, this.cdata.cnum, doc,
+                &mut |d| this.tr_def_id(d))))
+        }).unwrap()
+    }
+}
+
+impl<'a, 'tcx> Deref for DecodeContext<'a, 'tcx> {
+    type Target = rbml::reader::Decoder<'a>;
+    fn deref(&self) -> &Self::Target {
+        &self.rbml_r
+    }
+}
+
+impl<'a, 'tcx> DerefMut for DecodeContext<'a, 'tcx> {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.rbml_r
+    }
+}
+
+// FIXME(#36588) These impls are horribly unsound as they allow
+// the caller to pick any lifetime for 'tcx, including 'static,
+// by using the unspecialized proxies to them.
+
+impl<'a, 'tcx> SpecializedDecoder<Ty<'tcx>> for DecodeContext<'a, 'tcx> {
+    fn specialized_decode(&mut self) -> Result<Ty<'tcx>, Self::Error> {
+        Ok(self.read_ty_encoded(|d| d.parse_ty()))
+    }
+}
+
+impl<'a, 'tcx> SpecializedDecoder<&'tcx Substs<'tcx>> for DecodeContext<'a, 'tcx> {
+    fn specialized_decode(&mut self) -> Result<&'tcx Substs<'tcx>, Self::Error> {
+        Ok(self.read_ty_encoded(|d| d.parse_substs()))
+    }
+}
+
+impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Region> for DecodeContext<'a, 'tcx> {
+    fn specialized_decode(&mut self) -> Result<&'tcx ty::Region, Self::Error> {
+        let r = ty::Region::decode(self)?;
+        Ok(self.tcx.mk_region(r))
+    }
+}
+
+impl<'a, 'tcx> SpecializedDecoder<ty::ClosureSubsts<'tcx>> for DecodeContext<'a, 'tcx> {
+    fn specialized_decode(&mut self) -> Result<ty::ClosureSubsts<'tcx>, Self::Error> {
+        Ok(ty::ClosureSubsts {
+            func_substs: Decodable::decode(this)?,
+            upvar_tys: this.tcx.mk_type_list(Decodable::decode(this)?)
+        })
+    }
+}
+
+impl<'a, 'tcx> SpecializedDecoder<ty::AdtDef<'tcx>> for DecodeContext<'a, 'tcx> {
+    fn specialized_decode(&mut self) -> Result<ty::AdtDef<'tcx>, Self::Error> {
+        let def_id = DefId::decode(self)?;
+        let def_id = translate_def_id(self.cdata, def_id);
+        Ok(self.tcx.lookup_adt_def(def_id))
+    }
+}
+
 pub type Cmd<'a> = &'a CrateMetadata;
 
 impl CrateMetadata {
@@ -796,17 +898,13 @@ pub fn maybe_get_item_mir<'a, 'tcx>(cdata: Cmd,
     let item_doc = cdata.lookup_item(id);
 
     return reader::maybe_get_doc(item_doc, tag_mir as usize).map(|mir_doc| {
-        let dcx = tls_context::DecodingContext {
-            crate_metadata: cdata,
-            tcx: tcx,
-        };
-        let mut decoder = reader::Decoder::new(mir_doc);
+        let mut dcx = DecodeContext::new(tcx, cdata,
+                                         IdRange { min: 0, max: 0 },
+                                         mir_doc);
 
-        let mut mir = tls::enter_decoding_context(&dcx, |_| {
-            Decodable::decode(&mut decoder)
-        }).unwrap();
+        let mut mir = Decodable::decode(&mut dcx).unwrap();
 
-        assert!(decoder.position() == mir_doc.end);
+        assert!(dcx.rbml_r.position() == mir_doc.end);
 
         let mut def_id_and_span_translator = MirDefIdAndSpanTranslator {
             crate_metadata: cdata,
diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs
index 3197d52e14d..0f7765713c3 100644
--- a/src/librustc_metadata/encoder.rs
+++ b/src/librustc_metadata/encoder.rs
@@ -35,7 +35,7 @@ use rustc::mir::mir_map::MirMap;
 use rustc::session::config::{self, PanicStrategy, CrateTypeRustcMacro};
 use rustc::util::nodemap::{FnvHashMap, NodeSet};
 
-use rustc_serialize::{Encodable, SpecializedEncoder, SpecializedDecoder};
+use rustc_serialize::{Encodable, SpecializedEncoder};
 use std::cell::RefCell;
 use std::io::prelude::*;
 use std::io::{Cursor, SeekFrom};
@@ -97,30 +97,6 @@ impl<'a, 'tcx> SpecializedEncoder<&'tcx Substs<'tcx>> for EncodeContext<'a, 'tcx
     }
 }
 
-/// FIXME(#31844) This is horribly unsound as it allows the
-/// caller to pick any lifetime for 'tcx, including 'static.
-impl<'a, 'tcx> SpecializedDecoder<Ty<'tcx>> for ::rbml::reader::Decoder<'a> {
-    fn specialized_decode(&mut self) -> Result<Ty<'tcx>, Self::Error> {
-        self.read_opaque(|opaque_decoder, _| {
-            ::middle::cstore::tls::with_decoding_context(|dcx| {
-                Ok(dcx.decode_ty(opaque_decoder))
-            })
-        })
-    }
-}
-
-/// FIXME(#31844) This is horribly unsound as it allows the
-/// caller to pick any lifetime for 'tcx, including 'static.
-impl<'a, 'tcx> SpecializedDecoder<&'tcx Substs<'tcx>> for ::rbml::reader::Decoder<'a> {
-    fn specialized_decode(&mut self) -> Result<&'tcx Substs<'tcx>, Self::Error> {
-        self.read_opaque(|opaque_decoder, _| {
-            ::middle::cstore::tls::with_decoding_context(|dcx| {
-                Ok(dcx.decode_substs(opaque_decoder))
-            })
-        })
-    }
-}
-
 fn encode_name(ecx: &mut EncodeContext, name: Name) {
     ecx.wr_tagged_str(tag_paths_data_name, &name.as_str());
 }
diff --git a/src/librustc_metadata/lib.rs b/src/librustc_metadata/lib.rs
index d9d103beaf0..428b33f2bfa 100644
--- a/src/librustc_metadata/lib.rs
+++ b/src/librustc_metadata/lib.rs
@@ -61,9 +61,6 @@ pub mod rbml {
 
 pub use rustc::middle;
 
-#[macro_use]
-mod macros;
-
 pub mod diagnostics;
 
 pub mod astencode;
@@ -80,6 +77,5 @@ pub mod cstore;
 pub mod index;
 pub mod loader;
 pub mod macro_import;
-pub mod tls_context;
 
 __build_diagnostic_array! { librustc_metadata, DIAGNOSTICS }
diff --git a/src/librustc_metadata/macros.rs b/src/librustc_metadata/macros.rs
deleted file mode 100644
index ed764ebd9f9..00000000000
--- a/src/librustc_metadata/macros.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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.
-
-macro_rules! enum_from_u32 {
-    ($(#[$attr:meta])* pub enum $name:ident {
-        $($variant:ident = $e:expr,)*
-    }) => {
-        $(#[$attr])*
-        pub enum $name {
-            $($variant = $e),*
-        }
-
-        impl $name {
-            pub fn from_u32(u: u32) -> Option<$name> {
-                $(if u == $name::$variant as u32 {
-                    return Some($name::$variant)
-                })*
-                None
-            }
-        }
-    };
-    ($(#[$attr:meta])* pub enum $name:ident {
-        $($variant:ident,)*
-    }) => {
-        $(#[$attr])*
-        pub enum $name {
-            $($variant,)*
-        }
-
-        impl $name {
-            pub fn from_u32(u: u32) -> Option<$name> {
-                $(if u == $name::$variant as u32 {
-                    return Some($name::$variant)
-                })*
-                None
-            }
-        }
-    }
-}
diff --git a/src/librustc_metadata/rbml/reader.rs b/src/librustc_metadata/rbml/reader.rs
index 7878d8af989..02acfef612a 100644
--- a/src/librustc_metadata/rbml/reader.rs
+++ b/src/librustc_metadata/rbml/reader.rs
@@ -555,20 +555,6 @@ impl<'doc> Decoder<'doc> {
         Ok(r_doc)
     }
 
-    fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
-    {
-        let d = self.next_doc(exp_tag)?;
-        let old_parent = self.parent;
-        let old_pos = self.pos;
-        self.parent = d;
-        self.pos = d.start;
-        let r = f(self)?;
-        self.parent = old_parent;
-        self.pos = old_pos;
-        Ok(r)
-    }
-
     fn _next_sub(&mut self) -> DecodeResult<usize> {
         // empty vector/map optimization
         if self.parent.is_empty() {
@@ -670,14 +656,6 @@ impl<'doc> Decoder<'doc> {
         Ok(r)
     }
 
-    pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R>
-        where F: FnOnce(&mut opaque::Decoder, Doc) -> DecodeResult<R>
-    {
-        let doc = self.next_doc(EsOpaque)?;
-        let result = op(&mut doc.opaque(), doc)?;
-        Ok(result)
-    }
-
     pub fn position(&self) -> usize {
         self.pos
     }
@@ -687,7 +665,30 @@ impl<'doc> Decoder<'doc> {
     }
 }
 
-impl<'doc> serialize::Decoder for Decoder<'doc> {
+impl<'doc, 'tcx> ::decoder::DecodeContext<'doc, 'tcx> {
+    pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R>
+        where F: FnOnce(&mut Self, Doc) -> DecodeResult<R>
+    {
+        let doc = self.next_doc(EsOpaque)?;
+        op(self, doc)
+    }
+
+    fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
+    {
+        let d = self.next_doc(exp_tag)?;
+        let old_parent = self.parent;
+        let old_pos = self.pos;
+        self.parent = d;
+        self.pos = d.start;
+        let r = f(self)?;
+        self.parent = old_parent;
+        self.pos = old_pos;
+        Ok(r)
+    }
+}
+
+impl<'doc, 'tcx> serialize::Decoder for ::decoder::DecodeContext<'doc, 'tcx> {
     type Error = Error;
     fn read_nil(&mut self) -> DecodeResult<()> {
         Ok(())
@@ -757,7 +758,7 @@ impl<'doc> serialize::Decoder for Decoder<'doc> {
 
     // Compound types:
     fn read_enum<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_enum({})", name);
 
@@ -775,7 +776,7 @@ impl<'doc> serialize::Decoder for Decoder<'doc> {
     }
 
     fn read_enum_variant<T, F>(&mut self, _: &[&str], mut f: F) -> DecodeResult<T>
-        where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
+        where F: FnMut(&mut Self, usize) -> DecodeResult<T>
     {
         debug!("read_enum_variant()");
         let idx = self._next_sub()?;
@@ -785,14 +786,14 @@ impl<'doc> serialize::Decoder for Decoder<'doc> {
     }
 
     fn read_enum_variant_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_enum_variant_arg(idx={})", idx);
         f(self)
     }
 
     fn read_enum_struct_variant<T, F>(&mut self, _: &[&str], mut f: F) -> DecodeResult<T>
-        where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
+        where F: FnMut(&mut Self, usize) -> DecodeResult<T>
     {
         debug!("read_enum_struct_variant()");
         let idx = self._next_sub()?;
@@ -806,28 +807,28 @@ impl<'doc> serialize::Decoder for Decoder<'doc> {
                                             idx: usize,
                                             f: F)
                                             -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_enum_struct_variant_arg(name={}, idx={})", name, idx);
         f(self)
     }
 
     fn read_struct<T, F>(&mut self, name: &str, _: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_struct(name={})", name);
         f(self)
     }
 
     fn read_struct_field<T, F>(&mut self, name: &str, idx: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_struct_field(name={}, idx={})", name, idx);
         f(self)
     }
 
     fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_tuple()");
         self.read_seq(move |d, len| {
@@ -843,28 +844,28 @@ impl<'doc> serialize::Decoder for Decoder<'doc> {
     }
 
     fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_tuple_arg(idx={})", idx);
         self.read_seq_elt(idx, f)
     }
 
     fn read_tuple_struct<T, F>(&mut self, name: &str, len: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_tuple_struct(name={})", name);
         self.read_tuple(len, f)
     }
 
     fn read_tuple_struct_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_tuple_struct_arg(idx={})", idx);
         self.read_tuple_arg(idx, f)
     }
 
     fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T>
-        where F: FnMut(&mut Decoder<'doc>, bool) -> DecodeResult<T>
+        where F: FnMut(&mut Self, bool) -> DecodeResult<T>
     {
         debug!("read_option()");
         self.read_enum("Option", move |this| {
@@ -879,7 +880,7 @@ impl<'doc> serialize::Decoder for Decoder<'doc> {
     }
 
     fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>, usize) -> DecodeResult<T>
+        where F: FnOnce(&mut Self, usize) -> DecodeResult<T>
     {
         debug!("read_seq()");
         self.push_doc(EsVec, move |d| {
@@ -890,14 +891,14 @@ impl<'doc> serialize::Decoder for Decoder<'doc> {
     }
 
     fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_seq_elt(idx={})", idx);
         self.push_doc(EsVecElt, f)
     }
 
     fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>, usize) -> DecodeResult<T>
+        where F: FnOnce(&mut Self, usize) -> DecodeResult<T>
     {
         debug!("read_map()");
         self.push_doc(EsMap, move |d| {
@@ -908,14 +909,14 @@ impl<'doc> serialize::Decoder for Decoder<'doc> {
     }
 
     fn read_map_elt_key<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_map_elt_key(idx={})", idx);
         self.push_doc(EsMapKey, f)
     }
 
     fn read_map_elt_val<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
-        where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
+        where F: FnOnce(&mut Self) -> DecodeResult<T>
     {
         debug!("read_map_elt_val(idx={})", idx);
         self.push_doc(EsMapVal, f)
diff --git a/src/librustc_metadata/tls_context.rs b/src/librustc_metadata/tls_context.rs
deleted file mode 100644
index da6d04fc0ef..00000000000
--- a/src/librustc_metadata/tls_context.rs
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2012-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.
-
-// This module provides implementations for the thread-local encoding and
-// decoding context traits in rustc::middle::cstore::tls.
-
-use rbml::opaque::Decoder as OpaqueDecoder;
-use rustc::middle::cstore::tls;
-use rustc::hir::def_id::DefId;
-use rustc::ty::subst::Substs;
-use rustc::ty::{Ty, TyCtxt};
-
-use decoder::{self, Cmd};
-use tydecode::TyDecoder;
-
-pub struct DecodingContext<'a, 'tcx: 'a> {
-    pub crate_metadata: Cmd<'a>,
-    pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
-}
-
-impl<'a, 'tcx: 'a> tls::DecodingContext<'tcx> for DecodingContext<'a, 'tcx> {
-
-    fn tcx<'s>(&'s self) -> TyCtxt<'s, 'tcx, 'tcx> {
-        self.tcx
-    }
-
-    fn decode_ty(&self, decoder: &mut OpaqueDecoder) -> Ty<'tcx> {
-        let def_id_convert = &mut |did| {
-            decoder::translate_def_id(self.crate_metadata, did)
-        };
-
-        let starting_position = decoder.position();
-
-        let mut ty_decoder = TyDecoder::new(
-            self.crate_metadata.data.as_slice(),
-            self.crate_metadata.cnum,
-            starting_position,
-            self.tcx,
-            def_id_convert);
-
-        let ty = ty_decoder.parse_ty();
-
-        let end_position = ty_decoder.position();
-
-        // We can just reuse the tydecode implementation for parsing types, but
-        // we have to make sure to leave the rbml reader at the position just
-        // after the type.
-        decoder.advance(end_position - starting_position);
-        ty
-    }
-
-    fn decode_substs(&self, decoder: &mut OpaqueDecoder) -> &'tcx Substs<'tcx> {
-        let def_id_convert = &mut |did| {
-            decoder::translate_def_id(self.crate_metadata, did)
-        };
-
-        let starting_position = decoder.position();
-
-        let mut ty_decoder = TyDecoder::new(
-            self.crate_metadata.data.as_slice(),
-            self.crate_metadata.cnum,
-            starting_position,
-            self.tcx,
-            def_id_convert);
-
-        let substs = ty_decoder.parse_substs();
-
-        let end_position = ty_decoder.position();
-
-        decoder.advance(end_position - starting_position);
-        substs
-    }
-
-    fn translate_def_id(&self, def_id: DefId) -> DefId {
-        decoder::translate_def_id(self.crate_metadata, def_id)
-    }
-}