1mod function_var;
2mod comparison;
3mod constructor;
4mod effect;
5mod index;
6
7use rustc_hir::{def::DefKind, def_id::DefId};
8use rustc_middle::{
9 mir::{Local, Operand},
10 ty::{Instance, InstanceKind, TyKind},
11};
12use z3::ast::Int;
13
14use super::super::state::{VmExecutor, VmValue};
15use super::RuleFlow;
16use self::comparison::ComparisonPlan;
17use self::index::BuiltinIndexPlan;
18use crate::vm::constructor_policy::ConstructorMirMode;
19use crate::compat::Spanned;
20use crate::def_ids::diagnostic_api;
21use crate::util::fn_info::{self, FnKind};
22use crate::util::mir_utils;
23use crate::analysis::dataflow::call_summary::{self, CallEffect};
24use crate::def_ids;
25use crate::contract::type_invariants::constructor_result_has_invariant;
26use crate::vm::constructor_policy::effective_constructor_mir_mode;
27
28#[derive(Clone, Copy)]
29struct CallSite<'a, 'z3, 'tcx> {
30 func: &'a Operand<'tcx>,
31 args: &'a [Spanned<Operand<'tcx>>],
32 arg_values: &'a [VmValue<'z3, 'tcx>],
33 arg_locals: &'a [Option<Local>],
34 callee: Option<DefId>,
35 destination: Local,
36 caller_def_id: DefId,
37}
38
39enum CallModel<'z3, 'tcx> {
40 Comparison(ComparisonPlan<'z3>),
41 UbCheck,
42 Drop(DropCall),
43 UnsupportedIntrinsic,
44 BuiltinIndex(BuiltinIndexPlan<'z3, 'tcx>),
45 PostconditionsOnly,
46 Summary(Vec<CallEffect>),
47 Constructor(DefId),
48 Inline(DefId),
49 Unknown,
50}
51
52#[derive(Clone, Copy)]
53enum DropCall {
54 Value,
55 Pointee,
56}
57
58#[derive(Clone, Copy, PartialEq, Eq)]
59enum CallFinish {
60 None,
61 MethodOnly,
62 Full,
63}
64
65impl CallModel<'_, '_> {
66 fn finish_policy(&self) -> CallFinish {
67 match self {
68 Self::Comparison(_) => CallFinish::MethodOnly,
69 Self::UbCheck | Self::Drop(_) | Self::UnsupportedIntrinsic => CallFinish::None,
70 _ => CallFinish::Full,
71 }
72 }
73
74 fn uses_summary_invariants(&self) -> bool {
75 match self {
76 Self::Summary(effects) => !effects.is_empty(),
77 Self::Constructor(_) => true,
78 _ => false,
79 }
80 }
81}
82
83pub(super) fn exec_call<'z3, 'tcx>(
84 state: &mut VmExecutor<'z3, 'tcx>,
85 func: &Operand<'tcx>,
86 args: &[Spanned<Operand<'tcx>>],
87 destination: Local,
88 caller_def_id: DefId,
89) -> RuleFlow {
90 let prior_result = state.local_value(destination).map(|value| value.z3_term.clone());
91 let arg_values: Vec<VmValue<'z3, 'tcx>> = args
92 .iter()
93 .map(|arg| state.value_of_operand(&arg.node))
94 .collect();
95 let caller_arg_locals: Vec<Option<Local>> = args
96 .iter()
97 .map(|a| a.node.place().map(|p| p.local))
98 .collect();
99 let callee = mir_utils::resolve_callee_def_id(state.tcx, caller_def_id, func);
100 if let Some((source, owner)) = callee
101 .and_then(|id| crate::analysis::alias::hazard::reconstructed_owner(state.tcx, id))
102 && let Some(value) = arg_values.get(source)
103 {
104 state.consume_ownership_share(value, owner, false);
105 }
106 let site = CallSite {
107 func,
108 args,
109 arg_values: &arg_values,
110 arg_locals: &caller_arg_locals,
111 callee,
112 destination,
113 caller_def_id,
114 };
115 let drop_call = if callee.is_some_and(|id| diagnostic_api::is_drop(state.tcx, id))
116 || callee.is_some_and(|id| state.tcx.def_path_str(id).contains("::ptr::drop_glue"))
117 {
118 Some(DropCall::Value)
119 } else if callee.is_some_and(|id| mir_utils::is_drop_in_place(state.tcx, id))
120 || def_ids::is_manually_drop_drop(state.tcx, callee)
121 {
122 Some(DropCall::Pointee)
123 } else {
124 None
125 };
126 if drop_call.is_none() {
127 for (arg, value) in args.iter().zip(&arg_values) {
128 if let Some(local) = arg.node.place().map(|place| place.local)
129 && let Some(alloc_id) = value.provenance_alloc_id()
130 {
131 state.record_memory_use(alloc_id, local);
132 }
133 }
134 }
135 if callee.is_some_and(|c| {
136 matches!(state.tcx.def_kind(c), DefKind::Fn | DefKind::AssocFn)
137 && matches!(
138 state
139 .tcx
140 .fn_sig(c)
141 .skip_binder()
142 .output()
143 .skip_binder()
144 .kind(),
145 TyKind::Never
146 )
147 }) {
148 return RuleFlow::Pruned;
149 }
150 let method_call = callee.and_then(|method| {
151 arg_values.first().and_then(|receiver| {
152 state.begin_method_call(
153 method,
154 receiver,
155 caller_arg_locals.first().copied().flatten(),
156 )
157 })
158 });
159
160 let model = state.select_call_model(&site, drop_call);
161 let finish_policy = model.finish_policy();
162 let summary_used = model.uses_summary_invariants();
163 if state.execute_call_model(model, &site) == RuleFlow::Pruned {
164 return RuleFlow::Pruned;
165 }
166 if finish_policy == CallFinish::None {
167 return RuleFlow::Continue;
168 }
169 if finish_policy == CallFinish::MethodOnly {
170 let result = state.local_value(destination).cloned();
171 state.finish_method_call(method_call, result.as_ref());
172 return RuleFlow::Continue;
173 }
174 state.finish_call(&site, prior_result.as_ref(), summary_used, method_call);
175 RuleFlow::Continue
176}
177
178impl<'z3, 'tcx> VmExecutor<'z3, 'tcx> {
179 fn select_call_model(
180 &self,
181 site: &CallSite<'_, 'z3, 'tcx>,
182 drop_call: Option<DropCall>,
183 ) -> CallModel<'z3, 'tcx> {
184 let CallSite {
185 func,
186 arg_values: args,
187 arg_locals,
188 callee,
189 destination,
190 caller_def_id,
191 ..
192 } = *site;
193 if let Some(plan) = self.prepare_comparison(callee, args, destination) {
194 return CallModel::Comparison(plan);
195 }
196 if callee.is_some_and(|id| crate::def_ids::other_api::is_ub_check(self.tcx, id)) {
197 return CallModel::UbCheck;
198 }
199 if let Some(drop_call) = drop_call {
200 return CallModel::Drop(drop_call);
201 }
202 if call_summary::effects::is_unmodeled_intrinsic(self.tcx, callee) {
203 return CallModel::UnsupportedIntrinsic;
204 }
205 let ctor_mode = callee
206 .filter(|id| fn_info::get_type(self.tcx, *id) == FnKind::Constructor)
207 .map(|id| effective_constructor_mir_mode(self.tcx, id, self.constructor_mir_mode));
208 let force_constructor_mir = matches!(ctor_mode, Some(ConstructorMirMode::True))
209 && callee.is_some_and(|id| self.tcx.is_mir_available(id));
210 if !force_constructor_mir {
211 if let Some(plan) = self.prepare_builtin_index(callee, args, arg_locals, destination) {
212 return CallModel::BuiltinIndex(plan);
213 }
214 if callee
215 .is_some_and(|id| crate::contract::ensures::has_slice_offset_ensures(self.tcx, id))
216 {
217 return CallModel::PostconditionsOnly;
218 }
219 if args
220 .first()
221 .is_some_and(|value| !self.vec_reallocation_targets(value).is_empty())
222 && call_summary::pointer_semantics::callsite_replaces_pointer_field(self.tcx, func)
223 {
224 return CallModel::Summary(vec![CallEffect::ReallocateVec { arg: 0 }]);
225 }
226 if let Some(effects) = call_summary::effects::lookup_effect(
227 self.tcx, caller_def_id, callee, func,
228 ) {
229 return CallModel::Summary(effects);
230 }
231 if let Some(effects) = call_summary::effects::effect_summary(self.tcx, func) {
232 return CallModel::Summary(effects);
233 }
234 }
235 if let Some(callee) = callee
236 && matches!(ctor_mode, Some(ConstructorMirMode::False))
237 {
238 CallModel::Constructor(callee)
239 } else if let Some(callee) = callee
240 && self.tcx.is_mir_available(callee)
241 {
242 CallModel::Inline(callee)
243 } else {
244 CallModel::Unknown
245 }
246 }
247
248 fn execute_call_model(
249 &mut self,
250 model: CallModel<'z3, 'tcx>,
251 site: &CallSite<'_, 'z3, 'tcx>,
252 ) -> RuleFlow {
253 let CallSite {
254 func,
255 args,
256 arg_values,
257 arg_locals,
258 callee,
259 destination,
260 caller_def_id,
261 } = *site;
262 match model {
263 CallModel::Comparison(plan) => {
264 self.apply_comparison(plan, destination);
265 RuleFlow::Continue
266 }
267 CallModel::UbCheck => {
268 let ty = self.body().local_decls[destination].ty;
269 self.set_local(destination, VmValue::new(Int::from_u64(self.z3_ctx, 0), ty));
270 RuleFlow::Continue
271 }
272 CallModel::Drop(DropCall::Value) => {
273 if let Some(Operand::Move(place)) = args.first().map(|arg| &arg.node) {
274 super::terminator::exec_drop(self, place);
275 }
276 RuleFlow::Continue
277 }
278 CallModel::Drop(DropCall::Pointee) => {
279 let dropped_data = if let Some(pointer) = arg_values.first()
280 && let Some(local) = self.find_local_by_address(&pointer.z3_term)
281 {
282 super::terminator::exec_drop(self, &rustc_middle::mir::Place::from(local))
283 } else {
284 false
285 };
286 if !dropped_data
287 && let Some(pointer) = arg_values.first()
288 && let Some(alloc_id) = pointer.provenance_alloc_id()
289 {
290 let local = arg_locals.first().copied().flatten().unwrap_or(destination);
291 self.record_memory_drop(alloc_id, local);
292 }
293 RuleFlow::Continue
294 }
295 CallModel::UnsupportedIntrinsic => {
296 let name = callee
297 .map(|id| self.tcx.def_path_str(id))
298 .unwrap_or_else(|| "<unresolved>".to_string());
299 self.record_unsupported(&format!("intrinsic {name}"));
300 RuleFlow::Continue
301 }
302 CallModel::BuiltinIndex(plan) => {
303 self.apply_builtin_index(plan, destination);
304 RuleFlow::Continue
305 }
306 CallModel::PostconditionsOnly => RuleFlow::Continue,
307 CallModel::Summary(effects) => {
308 for effect in &effects {
309 self.apply_call_effect(
310 effect,
311 arg_values,
312 arg_locals,
313 args,
314 destination,
315 func,
316 );
317 }
318 RuleFlow::Continue
319 }
320 CallModel::Constructor(callee) => {
321 let has_invariant = constructor_result_has_invariant(self.tcx, callee);
322 self.materialize_constructor_result(
323 destination,
324 arg_values,
325 args.first().map(|arg| &arg.node),
326 callee,
327 has_invariant,
328 );
329 RuleFlow::Continue
330 }
331 CallModel::Inline(callee) => {
332 let instance = mir_utils::resolve_callee_instance(self.tcx, caller_def_id, func)
333 .or_else(|| {
334 let Operand::Constant(constant) = func else {
335 return None;
336 };
337 let TyKind::FnDef(def_id, args) = constant.const_.ty().kind() else {
338 return None;
339 };
340 let args = args.skip_binder();
341 (*def_id == callee && self.tcx.trait_of_assoc(callee).is_none()).then_some(
342 Instance {
343 def: InstanceKind::Item(callee),
344 args,
345 },
346 )
347 })
348 .filter(|instance| {
349 matches!(instance.def, InstanceKind::Item(_))
350 && instance.def_id() == callee
351 && (instance
352 .args
353 .types()
354 .all(|ty| !mir_utils::ty_has_type_param(ty))
355 || self.path_state.inline.symbolic_generic_const_inline
356 || mir_utils::has_generic_const_call_argument(self.tcx, callee))
357 });
358 if self.exec_inline_call(
359 callee,
360 instance,
361 args,
362 arg_values,
363 arg_locals,
364 destination,
365 ) {
366 RuleFlow::Continue
367 } else {
368 RuleFlow::Pruned
369 }
370 }
371 CallModel::Unknown => {
372 if let Some(callee) = callee {
373 if self.tcx.trait_of_assoc(callee).is_some_and(|trait_id| {
374 crate::def_ids::lang_api::is_fn_trait(self.tcx, trait_id)
375 }) {
376 self.apply_function_var_effect(arg_values, arg_locals, destination, callee);
377 } else if !crate::def_ids::lang_api::is_panic_exit(self.tcx, callee) {
378 self.record_missing_mir(callee);
379 }
380 }
381 RuleFlow::Continue
382 }
383 }
384 }
385
386 fn finish_call(
387 &mut self,
388 site: &CallSite<'_, 'z3, 'tcx>,
389 prior_result: Option<&Int<'z3>>,
390 summary_used: bool,
391 method_call: Option<super::super::method_cache::MethodSnapshot<'z3, 'tcx>>,
392 ) {
393 self.finish_call_state(site, prior_result, summary_used, method_call.clone());
394 let mut alternatives = std::mem::take(&mut self.path_state.inline.pending_states);
395 for state in &mut alternatives {
396 state.finish_call_state(site, prior_result, summary_used, method_call.clone());
397 }
398 self.path_state.inline.pending_states = alternatives;
399 }
400
401 fn finish_call_state(
402 &mut self,
403 site: &CallSite<'_, 'z3, 'tcx>,
404 prior_result: Option<&Int<'z3>>,
405 summary_used: bool,
406 method_call: Option<super::super::method_cache::MethodSnapshot<'z3, 'tcx>>,
407 ) {
408 let callee = site.callee;
409 if let Some(owner) = callee
410 .and_then(|id| crate::analysis::alias::shared_owner::shared_raw_owner_type(self.tcx, id))
411 {
412 self.begin_ownership_transfer(site.destination, owner);
413 }
414 let arg_locals = site.arg_locals;
415 let destination = site.destination;
416 if let Some(callee) = callee {
417 self.assert_call_postconditions(callee, arg_locals, destination);
418 if self
419 .local_value(destination)
420 .is_some_and(|value| prior_result != Some(&value.z3_term))
421 {
422 self.assert_call_result_invariants(destination);
423 if summary_used {
424 self.assert_summary_result_type_invariants(callee, destination);
425 }
426 }
427 }
428 let result = self.local_value(destination).cloned();
429 self.finish_method_call(method_call, result.as_ref());
430 }
431}