]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/intrinsicck.rs
Add riscv64gc-unknown-none-elf target
[rust.git] / src / librustc / middle / intrinsicck.rs
1 use crate::hir::def::Def;
2 use crate::hir::def_id::DefId;
3 use crate::ty::{self, Ty, TyCtxt};
4 use crate::ty::layout::{LayoutError, Pointer, SizeSkeleton, VariantIdx};
5 use crate::ty::query::Providers;
6
7 use rustc_target::spec::abi::Abi::RustIntrinsic;
8 use rustc_data_structures::indexed_vec::Idx;
9 use syntax_pos::Span;
10 use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
11 use crate::hir;
12
13 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
14     for &module in tcx.hir().krate().modules.keys() {
15         tcx.ensure().check_mod_intrinsics(tcx.hir().local_def_id(module));
16     }
17 }
18
19 fn check_mod_intrinsics<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
20     tcx.hir().visit_item_likes_in_module(
21         module_def_id,
22         &mut ItemVisitor { tcx }.as_deep_visitor()
23     );
24 }
25
26 pub fn provide(providers: &mut Providers<'_>) {
27     *providers = Providers {
28         check_mod_intrinsics,
29         ..*providers
30     };
31 }
32
33 struct ItemVisitor<'a, 'tcx: 'a> {
34     tcx: TyCtxt<'a, 'tcx, 'tcx>
35 }
36
37 struct ExprVisitor<'a, 'tcx: 'a> {
38     tcx: TyCtxt<'a, 'tcx, 'tcx>,
39     tables: &'tcx ty::TypeckTables<'tcx>,
40     param_env: ty::ParamEnv<'tcx>,
41 }
42
43 /// If the type is `Option<T>`, it will return `T`, otherwise
44 /// the type itself. Works on most `Option`-like types.
45 fn unpack_option_like<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
46                                 ty: Ty<'tcx>)
47                                 -> Ty<'tcx> {
48     let (def, substs) = match ty.sty {
49         ty::Adt(def, substs) => (def, substs),
50         _ => return ty
51     };
52
53     if def.variants.len() == 2 && !def.repr.c() && def.repr.int.is_none() {
54         let data_idx;
55
56         let one = VariantIdx::new(1);
57         let zero = VariantIdx::new(0);
58
59         if def.variants[zero].fields.is_empty() {
60             data_idx = one;
61         } else if def.variants[one].fields.is_empty() {
62             data_idx = zero;
63         } else {
64             return ty;
65         }
66
67         if def.variants[data_idx].fields.len() == 1 {
68             return def.variants[data_idx].fields[0].ty(tcx, substs);
69         }
70     }
71
72     ty
73 }
74
75 impl<'a, 'tcx> ExprVisitor<'a, 'tcx> {
76     fn def_id_is_transmute(&self, def_id: DefId) -> bool {
77         self.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
78         self.tcx.item_name(def_id) == "transmute"
79     }
80
81     fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
82         let sk_from = SizeSkeleton::compute(from, self.tcx, self.param_env);
83         let sk_to = SizeSkeleton::compute(to, self.tcx, self.param_env);
84
85         // Check for same size using the skeletons.
86         if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
87             if sk_from.same_size(sk_to) {
88                 return;
89             }
90
91             // Special-case transmutting from `typeof(function)` and
92             // `Option<typeof(function)>` to present a clearer error.
93             let from = unpack_option_like(self.tcx.global_tcx(), from);
94             if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (&from.sty, sk_to) {
95                 if size_to == Pointer.size(&self.tcx) {
96                     struct_span_err!(self.tcx.sess, span, E0591,
97                                      "can't transmute zero-sized type")
98                         .note(&format!("source type: {}", from))
99                         .note(&format!("target type: {}", to))
100                         .help("cast with `as` to a pointer instead")
101                         .emit();
102                     return;
103                 }
104             }
105         }
106
107         // Try to display a sensible error with as much information as possible.
108         let skeleton_string = |ty: Ty<'tcx>, sk| {
109             match sk {
110                 Ok(SizeSkeleton::Known(size)) => {
111                     format!("{} bits", size.bits())
112                 }
113                 Ok(SizeSkeleton::Pointer { tail, .. }) => {
114                     format!("pointer to `{}`", tail)
115                 }
116                 Err(LayoutError::Unknown(bad)) => {
117                     if bad == ty {
118                         "this type does not have a fixed size".to_owned()
119                     } else {
120                         format!("size can vary because of {}", bad)
121                     }
122                 }
123                 Err(err) => err.to_string()
124             }
125         };
126
127         let mut err = struct_span_err!(self.tcx.sess, span, E0512,
128                                        "cannot transmute between types of different sizes, \
129                                         or dependently-sized types");
130         if from == to {
131             err.note(&format!("`{}` does not have a fixed size", from));
132         } else {
133             err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
134                 .note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
135         }
136         err.emit()
137     }
138 }
139
140 impl<'a, 'tcx> Visitor<'tcx> for ItemVisitor<'a, 'tcx> {
141     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
142         NestedVisitorMap::None
143     }
144
145     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
146         let owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
147         let body = self.tcx.hir().body(body_id);
148         let param_env = self.tcx.param_env(owner_def_id);
149         let tables = self.tcx.typeck_tables_of(owner_def_id);
150         ExprVisitor { tcx: self.tcx, param_env, tables }.visit_body(body);
151         self.visit_body(body);
152     }
153 }
154
155 impl<'a, 'tcx> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
156     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
157         NestedVisitorMap::None
158     }
159
160     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
161         let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
162             self.tables.qpath_def(qpath, expr.hir_id)
163         } else {
164             Def::Err
165         };
166         if let Def::Fn(did) = def {
167             if self.def_id_is_transmute(did) {
168                 let typ = self.tables.node_id_to_type(expr.hir_id);
169                 let sig = typ.fn_sig(self.tcx);
170                 let from = sig.inputs().skip_binder()[0];
171                 let to = *sig.output().skip_binder();
172                 self.check_transmute(expr.span, from, to);
173             }
174         }
175
176         intravisit::walk_expr(self, expr);
177     }
178 }