13
13
//! move analysis runs after promotion on broken MIR.
14
14
15
15
use either:: { Left , Right } ;
16
+ use rustc_data_structures:: fx:: FxHashSet ;
16
17
use rustc_hir as hir;
17
18
use rustc_middle:: mir;
18
19
use rustc_middle:: mir:: visit:: { MutVisitor , MutatingUseContext , PlaceContext , Visitor } ;
@@ -175,6 +176,12 @@ fn collect_temps_and_candidates<'tcx>(
175
176
struct Validator < ' a , ' tcx > {
176
177
ccx : & ' a ConstCx < ' a , ' tcx > ,
177
178
temps : & ' a mut IndexSlice < Local , TempState > ,
179
+ /// For backwards compatibility, we are promoting function calls in `const`/`static`
180
+ /// initializers. But we want to avoid evaluating code that might panic and that otherwise would
181
+ /// not have been evaluated, so we only promote such calls in basic blocks that are guaranteed
182
+ /// to execute. In other words, we only promote such calls in basic blocks that are definitely
183
+ /// not dead code. Here we cache the result of computing that set of basic blocks.
184
+ promotion_safe_blocks : Option < FxHashSet < BasicBlock > > ,
178
185
}
179
186
180
187
impl < ' a , ' tcx > std:: ops:: Deref for Validator < ' a , ' tcx > {
@@ -260,7 +267,9 @@ impl<'tcx> Validator<'_, 'tcx> {
260
267
self . validate_rvalue ( rhs)
261
268
}
262
269
Right ( terminator) => match & terminator. kind {
263
- TerminatorKind :: Call { func, args, .. } => self . validate_call ( func, args) ,
270
+ TerminatorKind :: Call { func, args, .. } => {
271
+ self . validate_call ( func, args, loc. block )
272
+ }
264
273
TerminatorKind :: Yield { .. } => Err ( Unpromotable ) ,
265
274
kind => {
266
275
span_bug ! ( terminator. source_info. span, "{:?} not promotable" , kind) ;
@@ -587,53 +596,103 @@ impl<'tcx> Validator<'_, 'tcx> {
587
596
Ok ( ( ) )
588
597
}
589
598
599
+ /// Computes the sets of blocks of this MIR that are definitely going to be executed
600
+ /// if the function returns successfully. That makes it safe to promote calls in them
601
+ /// that might fail.
602
+ fn promotion_safe_blocks ( body : & mir:: Body < ' tcx > ) -> FxHashSet < BasicBlock > {
603
+ let mut safe_blocks = FxHashSet :: default ( ) ;
604
+ let mut safe_block = START_BLOCK ;
605
+ loop {
606
+ safe_blocks. insert ( safe_block) ;
607
+ // Let's see if we can find another safe block.
608
+ safe_block = match body. basic_blocks [ safe_block] . terminator ( ) . kind {
609
+ TerminatorKind :: Goto { target } => target,
610
+ TerminatorKind :: Call { target : Some ( target) , .. }
611
+ | TerminatorKind :: Drop { target, .. } => {
612
+ // This calls a function or the destructor. `target` does not get executed if
613
+ // the callee loops or panics. But in both cases the const already fails to
614
+ // evaluate, so we are fine considering `target` a safe block for promotion.
615
+ target
616
+ }
617
+ TerminatorKind :: Assert { target, .. } => {
618
+ // Similar to above, we only consider successful execution.
619
+ target
620
+ }
621
+ _ => {
622
+ // No next safe block.
623
+ break ;
624
+ }
625
+ } ;
626
+ }
627
+ safe_blocks
628
+ }
629
+
630
+ /// Returns whether the block is "safe" for promotion, which means it cannot be dead code.
631
+ /// We use this to avoid promoting operations that can fail in dead code.
632
+ fn is_promotion_safe_block ( & mut self , block : BasicBlock ) -> bool {
633
+ let body = self . body ;
634
+ let safe_blocks =
635
+ self . promotion_safe_blocks . get_or_insert_with ( || Self :: promotion_safe_blocks ( body) ) ;
636
+ safe_blocks. contains ( & block)
637
+ }
638
+
590
639
fn validate_call (
591
640
& mut self ,
592
641
callee : & Operand < ' tcx > ,
593
642
args : & [ Spanned < Operand < ' tcx > > ] ,
643
+ block : BasicBlock ,
594
644
) -> Result < ( ) , Unpromotable > {
645
+ // Validate the operands. If they fail, there's no question -- we cannot promote.
646
+ self . validate_operand ( callee) ?;
647
+ for arg in args {
648
+ self . validate_operand ( & arg. node ) ?;
649
+ }
650
+
651
+ // Functions marked `#[rustc_promotable]` are explicitly allowed to be promoted, so we can
652
+ // accept them at this point.
595
653
let fn_ty = callee. ty ( self . body , self . tcx ) ;
654
+ if let ty:: FnDef ( def_id, _) = * fn_ty. kind ( ) {
655
+ if self . tcx . is_promotable_const_fn ( def_id) {
656
+ return Ok ( ( ) ) ;
657
+ }
658
+ }
596
659
597
- // Inside const/static items, we promote all (eligible) function calls.
598
- // Everywhere else, we require `#[rustc_promotable]` on the callee.
599
- let promote_all_const_fn = matches ! (
660
+ // Ideally, we'd stop here and reject the rest.
661
+ // But for backward compatibility, we have to accept some promotion in const/static
662
+ // initializers. Inline consts are explicitly excluded, they are more recent so we have no
663
+ // backwards compatibility reason to allow more promotion inside of them.
664
+ let promote_all_fn = matches ! (
600
665
self . const_kind,
601
666
Some ( hir:: ConstContext :: Static ( _) | hir:: ConstContext :: Const { inline: false } )
602
667
) ;
603
- if !promote_all_const_fn {
604
- if let ty:: FnDef ( def_id, _) = * fn_ty. kind ( ) {
605
- // Never promote runtime `const fn` calls of
606
- // functions without `#[rustc_promotable]`.
607
- if !self . tcx . is_promotable_const_fn ( def_id) {
608
- return Err ( Unpromotable ) ;
609
- }
610
- }
668
+ if !promote_all_fn {
669
+ return Err ( Unpromotable ) ;
611
670
}
612
-
671
+ // Make sure the callee is a `const fn`.
613
672
let is_const_fn = match * fn_ty. kind ( ) {
614
673
ty:: FnDef ( def_id, _) => self . tcx . is_const_fn_raw ( def_id) ,
615
674
_ => false ,
616
675
} ;
617
676
if !is_const_fn {
618
677
return Err ( Unpromotable ) ;
619
678
}
620
-
621
- self . validate_operand ( callee) ?;
622
- for arg in args {
623
- self . validate_operand ( & arg. node ) ?;
679
+ // The problem is, this may promote calls to functions that panic.
680
+ // We don't want to introduce compilation errors if there's a panic in a call in dead code.
681
+ // So we ensure that this is not dead code.
682
+ if !self . is_promotion_safe_block ( block) {
683
+ return Err ( Unpromotable ) ;
624
684
}
625
-
685
+ // This passed all checks, so let's accept.
626
686
Ok ( ( ) )
627
687
}
628
688
}
629
689
630
- // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
631
690
fn validate_candidates (
632
691
ccx : & ConstCx < ' _ , ' _ > ,
633
692
temps : & mut IndexSlice < Local , TempState > ,
634
693
candidates : & [ Candidate ] ,
635
694
) -> Vec < Candidate > {
636
- let mut validator = Validator { ccx, temps } ;
695
+ let mut validator = Validator { ccx, temps, promotion_safe_blocks : None } ;
637
696
638
697
candidates
639
698
. iter ( )
@@ -652,6 +711,10 @@ struct Promoter<'a, 'tcx> {
652
711
/// If true, all nested temps are also kept in the
653
712
/// source MIR, not moved to the promoted MIR.
654
713
keep_original : bool ,
714
+
715
+ /// If true, add the new const (the promoted) to the required_consts of the parent MIR.
716
+ /// This is initially false and then set by the visitor when it encounters a `Call` terminator.
717
+ add_to_required : bool ,
655
718
}
656
719
657
720
impl < ' a , ' tcx > Promoter < ' a , ' tcx > {
@@ -754,6 +817,10 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> {
754
817
TerminatorKind :: Call {
755
818
mut func, mut args, call_source : desugar, fn_span, ..
756
819
} => {
820
+ // This promoted involves a function call, so it may fail to evaluate.
821
+ // Let's make sure it is added to `required_consts` so that that failure cannot get lost.
822
+ self . add_to_required = true ;
823
+
757
824
self . visit_operand ( & mut func, loc) ;
758
825
for arg in & mut args {
759
826
self . visit_operand ( & mut arg. node , loc) ;
@@ -788,7 +855,7 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> {
788
855
789
856
fn promote_candidate ( mut self , candidate : Candidate , next_promoted_id : usize ) -> Body < ' tcx > {
790
857
let def = self . source . source . def_id ( ) ;
791
- let mut rvalue = {
858
+ let ( mut rvalue, promoted_op ) = {
792
859
let promoted = & mut self . promoted ;
793
860
let promoted_id = Promoted :: new ( next_promoted_id) ;
794
861
let tcx = self . tcx ;
@@ -798,11 +865,7 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> {
798
865
let args = tcx. erase_regions ( GenericArgs :: identity_for_item ( tcx, def) ) ;
799
866
let uneval = mir:: UnevaluatedConst { def, args, promoted : Some ( promoted_id) } ;
800
867
801
- Operand :: Constant ( Box :: new ( ConstOperand {
802
- span,
803
- user_ty : None ,
804
- const_ : Const :: Unevaluated ( uneval, ty) ,
805
- } ) )
868
+ ConstOperand { span, user_ty : None , const_ : Const :: Unevaluated ( uneval, ty) }
806
869
} ;
807
870
808
871
let blocks = self . source . basic_blocks . as_mut ( ) ;
@@ -835,22 +898,26 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> {
835
898
let promoted_ref = local_decls. push ( promoted_ref) ;
836
899
assert_eq ! ( self . temps. push( TempState :: Unpromotable ) , promoted_ref) ;
837
900
901
+ let promoted_operand = promoted_operand ( ref_ty, span) ;
838
902
let promoted_ref_statement = Statement {
839
903
source_info : statement. source_info ,
840
904
kind : StatementKind :: Assign ( Box :: new ( (
841
905
Place :: from ( promoted_ref) ,
842
- Rvalue :: Use ( promoted_operand ( ref_ty , span ) ) ,
906
+ Rvalue :: Use ( Operand :: Constant ( Box :: new ( promoted_operand ) ) ) ,
843
907
) ) ) ,
844
908
} ;
845
909
self . extra_statements . push ( ( loc, promoted_ref_statement) ) ;
846
910
847
- Rvalue :: Ref (
848
- tcx. lifetimes . re_erased ,
849
- * borrow_kind,
850
- Place {
851
- local : mem:: replace ( & mut place. local , promoted_ref) ,
852
- projection : List :: empty ( ) ,
853
- } ,
911
+ (
912
+ Rvalue :: Ref (
913
+ tcx. lifetimes . re_erased ,
914
+ * borrow_kind,
915
+ Place {
916
+ local : mem:: replace ( & mut place. local , promoted_ref) ,
917
+ projection : List :: empty ( ) ,
918
+ } ,
919
+ ) ,
920
+ promoted_operand,
854
921
)
855
922
} ;
856
923
@@ -862,6 +929,12 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> {
862
929
863
930
let span = self . promoted . span ;
864
931
self . assign ( RETURN_PLACE , rvalue, span) ;
932
+
933
+ // Now that we did promotion, we know whether we'll want to add this to `required_consts`.
934
+ if self . add_to_required {
935
+ self . source . required_consts . push ( promoted_op) ;
936
+ }
937
+
865
938
self . promoted
866
939
}
867
940
}
@@ -877,6 +950,14 @@ impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
877
950
* local = self . promote_temp ( * local) ;
878
951
}
879
952
}
953
+
954
+ fn visit_constant ( & mut self , constant : & mut ConstOperand < ' tcx > , _location : Location ) {
955
+ if constant. const_ . is_required_const ( ) {
956
+ self . promoted . required_consts . push ( * constant) ;
957
+ }
958
+
959
+ // Skipping `super_constant` as the visitor is otherwise only looking for locals.
960
+ }
880
961
}
881
962
882
963
fn promote_candidates < ' tcx > (
@@ -930,8 +1011,10 @@ fn promote_candidates<'tcx>(
930
1011
temps : & mut temps,
931
1012
extra_statements : & mut extra_statements,
932
1013
keep_original : false ,
1014
+ add_to_required : false ,
933
1015
} ;
934
1016
1017
+ // `required_consts` of the promoted itself gets filled while building the MIR body.
935
1018
let mut promoted = promoter. promote_candidate ( candidate, promotions. len ( ) ) ;
936
1019
promoted. source . promoted = Some ( promotions. next_index ( ) ) ;
937
1020
promotions. push ( promoted) ;
0 commit comments