]> git.lizzy.rs Git - rust.git/blob - src/common.rs
Fix a panic on type size overflow
[rust.git] / src / common.rs
1 use rustc_target::spec::{HasTargetSpec, Target};
2
3 use cranelift::codegen::ir::{Opcode, InstructionData, ValueDef};
4 use cranelift_module::Module;
5
6 use crate::prelude::*;
7
8 pub fn mir_var(loc: Local) -> Variable {
9     Variable::with_u32(loc.index() as u32)
10 }
11
12 pub fn pointer_ty(tcx: TyCtxt) -> types::Type {
13     match tcx.data_layout.pointer_size.bits() {
14         16 => types::I16,
15         32 => types::I32,
16         64 => types::I64,
17         bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits),
18     }
19 }
20
21 pub fn clif_type_from_ty<'tcx>(
22     tcx: TyCtxt<'tcx>,
23     ty: Ty<'tcx>,
24 ) -> Option<types::Type> {
25     Some(match ty.sty {
26         ty::Bool => types::I8,
27         ty::Uint(size) => match size {
28             UintTy::U8 => types::I8,
29             UintTy::U16 => types::I16,
30             UintTy::U32 => types::I32,
31             UintTy::U64 => types::I64,
32             UintTy::U128 => types::I128,
33             UintTy::Usize => pointer_ty(tcx),
34         },
35         ty::Int(size) => match size {
36             IntTy::I8 => types::I8,
37             IntTy::I16 => types::I16,
38             IntTy::I32 => types::I32,
39             IntTy::I64 => types::I64,
40             IntTy::I128 => types::I128,
41             IntTy::Isize => pointer_ty(tcx),
42         },
43         ty::Char => types::I32,
44         ty::Float(size) => match size {
45             FloatTy::F32 => types::F32,
46             FloatTy::F64 => types::F64,
47         },
48         ty::FnPtr(_) => pointer_ty(tcx),
49         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) | ty::Ref(_, ty, _) => {
50             if ty.is_sized(tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
51                 pointer_ty(tcx)
52             } else {
53                 return None;
54             }
55         }
56         ty::Param(_) => bug!("ty param {:?}", ty),
57         _ => return None,
58     })
59 }
60
61 pub fn codegen_select(bcx: &mut FunctionBuilder, cond: Value, lhs: Value, rhs: Value) -> Value {
62     let lhs_ty = bcx.func.dfg.value_type(lhs);
63     let rhs_ty = bcx.func.dfg.value_type(rhs);
64     assert_eq!(lhs_ty, rhs_ty);
65     if lhs_ty == types::I8 || lhs_ty == types::I16 {
66         // FIXME workaround for missing encoding for select.i8
67         let lhs = bcx.ins().uextend(types::I32, lhs);
68         let rhs = bcx.ins().uextend(types::I32, rhs);
69         let res = bcx.ins().select(cond, lhs, rhs);
70         bcx.ins().ireduce(lhs_ty, res)
71     } else {
72         bcx.ins().select(cond, lhs, rhs)
73     }
74 }
75
76 fn resolve_normal_value_imm(func: &Function, val: Value) -> Option<i64> {
77     if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
78         if let InstructionData::UnaryImm {
79             opcode: Opcode::Iconst,
80             imm,
81         } = func.dfg[inst] {
82             Some(imm.into())
83         } else {
84             None
85         }
86     } else {
87         None
88     }
89 }
90
91 fn resolve_128bit_value_imm(func: &Function, val: Value) -> Option<u128> {
92     let (lsb, msb) = if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
93         if let InstructionData::Binary {
94             opcode: Opcode::Iconcat,
95             args: [lsb, msb],
96         } = func.dfg[inst] {
97             (lsb, msb)
98         } else {
99             return None;
100         }
101     } else {
102         return None;
103     };
104
105     let lsb = resolve_normal_value_imm(func, lsb)? as u64 as u128;
106     let msb = resolve_normal_value_imm(func, msb)? as u64 as u128;
107
108     Some(msb << 64 | lsb)
109 }
110
111 pub fn resolve_value_imm(func: &Function, val: Value) -> Option<u128> {
112     if func.dfg.value_type(val) == types::I128 {
113         resolve_128bit_value_imm(func, val)
114     } else {
115         resolve_normal_value_imm(func, val).map(|imm| imm as u64 as u128)
116     }
117 }
118
119 pub fn type_min_max_value(ty: Type, signed: bool) -> (i64, i64) {
120     assert!(ty.is_int());
121     let min = match (ty, signed) {
122         (types::I8 , false)
123         | (types::I16, false)
124         | (types::I32, false)
125         | (types::I64, false) => 0i64,
126         (types::I8, true) => i8::min_value() as i64,
127         (types::I16, true) => i16::min_value() as i64,
128         (types::I32, true) => i32::min_value() as i64,
129         (types::I64, true) => i64::min_value(),
130         (types::I128, _) => unimplemented!(),
131         _ => unreachable!(),
132     };
133
134     let max = match (ty, signed) {
135         (types::I8, false) => u8::max_value() as i64,
136         (types::I16, false) => u16::max_value() as i64,
137         (types::I32, false) => u32::max_value() as i64,
138         (types::I64, false) => u64::max_value() as i64,
139         (types::I8, true) => i8::max_value() as i64,
140         (types::I16, true) => i16::max_value() as i64,
141         (types::I32, true) => i32::max_value() as i64,
142         (types::I64, true) => i64::max_value(),
143         (types::I128, _) => unimplemented!(),
144         _ => unreachable!(),
145     };
146
147     (min, max)
148 }
149
150 pub fn type_sign(ty: Ty<'_>) -> bool {
151     match ty.sty {
152         ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
153         ty::Int(..) => true,
154         ty::Float(..) => false, // `signed` is unused for floats
155         _ => panic!("{}", ty),
156     }
157 }
158
159 pub struct FunctionCx<'a, 'tcx: 'a, B: Backend> {
160     // FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
161     pub tcx: TyCtxt<'tcx>,
162     pub module: &'a mut Module<B>,
163     pub pointer_type: Type, // Cached from module
164
165     pub instance: Instance<'tcx>,
166     pub mir: &'tcx Body<'tcx>,
167
168     pub bcx: FunctionBuilder<'a>,
169     pub ebb_map: HashMap<BasicBlock, Ebb>,
170     pub local_map: HashMap<Local, CPlace<'tcx>>,
171
172     pub clif_comments: crate::pretty_clif::CommentWriter,
173     pub constants: &'a mut crate::constant::ConstantCx,
174     pub caches: &'a mut Caches<'tcx>,
175     pub source_info_set: indexmap::IndexSet<SourceInfo>,
176 }
177
178 impl<'a, 'tcx: 'a, B: Backend> LayoutOf for FunctionCx<'a, 'tcx, B> {
179     type Ty = Ty<'tcx>;
180     type TyLayout = TyLayout<'tcx>;
181
182     fn layout_of(&self, ty: Ty<'tcx>) -> TyLayout<'tcx> {
183         let ty = self.monomorphize(&ty);
184         self.tcx.layout_of(ParamEnv::reveal_all().and(&ty))
185             .unwrap_or_else(|e| if let layout::LayoutError::SizeOverflow(_) = e {
186                 self.tcx.sess.fatal(&e.to_string())
187             } else {
188                 bug!("failed to get layout for `{}`: {}", ty, e)
189             })
190     }
191 }
192
193 impl<'a, 'tcx, B: Backend + 'a> layout::HasTyCtxt<'tcx> for FunctionCx<'a, 'tcx, B> {
194     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
195         self.tcx
196     }
197 }
198
199 impl<'a, 'tcx, B: Backend + 'a> layout::HasDataLayout for FunctionCx<'a, 'tcx, B> {
200     fn data_layout(&self) -> &layout::TargetDataLayout {
201         &self.tcx.data_layout
202     }
203 }
204
205 impl<'a, 'tcx, B: Backend + 'a> layout::HasParamEnv<'tcx> for FunctionCx<'a, 'tcx, B> {
206     fn param_env(&self) -> ParamEnv<'tcx> {
207         ParamEnv::reveal_all()
208     }
209 }
210
211 impl<'a, 'tcx, B: Backend + 'a> HasTargetSpec for FunctionCx<'a, 'tcx, B> {
212     fn target_spec(&self) -> &Target {
213         &self.tcx.sess.target.target
214     }
215 }
216
217 impl<'a, 'tcx, B: Backend> BackendTypes for FunctionCx<'a, 'tcx, B> {
218     type Value = Value;
219     type BasicBlock = Ebb;
220     type Type = Type;
221     type Funclet = !;
222     type DIScope = !;
223 }
224
225 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
226     pub fn monomorphize<T>(&self, value: &T) -> T
227     where
228         T: TypeFoldable<'tcx>,
229     {
230         self.tcx.subst_and_normalize_erasing_regions(
231             self.instance.substs,
232             ty::ParamEnv::reveal_all(),
233             value,
234         )
235     }
236
237     pub fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
238         clif_type_from_ty(self.tcx, self.monomorphize(&ty))
239     }
240
241     pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
242         *self.ebb_map.get(&bb).unwrap()
243     }
244
245     pub fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
246         *self.local_map.get(&local).unwrap()
247     }
248
249     pub fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
250         let (index, _) = self.source_info_set.insert_full(source_info);
251         self.bcx.set_srcloc(SourceLoc::new(index as u32));
252     }
253 }