@@ -119,11 +119,6 @@ impl OptimizationFinder<'b, 'tcx> {
119119 }
120120
121121 fn find_deref_of_address ( & mut self , rvalue : & Rvalue < ' tcx > , location : Location ) -> Option < ( ) > {
122- // FIXME(#78192): This optimization can result in unsoundness.
123- if !self . tcx . sess . opts . debugging_opts . unsound_mir_opts {
124- return None ;
125- }
126-
127122 // Look for the sequence
128123 //
129124 // _2 = &_1;
@@ -137,6 +132,8 @@ impl OptimizationFinder<'b, 'tcx> {
137132 _ => None ,
138133 } ?;
139134
135+ let mut dead_locals_seen = vec ! [ ] ;
136+
140137 let stmt_index = location. statement_index ;
141138 // Look behind for statement that assigns the local from a address of operator.
142139 // 6 is chosen as a heuristic determined by seeing the number of times
@@ -160,6 +157,11 @@ impl OptimizationFinder<'b, 'tcx> {
160157 BorrowKind :: Shared ,
161158 place_taken_address_of,
162159 ) => {
160+ // Make sure that the place has not been marked dead
161+ if dead_locals_seen. contains ( & place_taken_address_of. local ) {
162+ return None ;
163+ }
164+
163165 self . optimizations
164166 . unneeded_deref
165167 . insert ( location, * place_taken_address_of) ;
@@ -178,13 +180,19 @@ impl OptimizationFinder<'b, 'tcx> {
178180 // Inline asm can do anything, so bail out of the optimization.
179181 rustc_middle:: mir:: StatementKind :: LlvmInlineAsm ( _) => return None ,
180182
183+ // Remember `StorageDead`s, as the local being marked dead could be the
184+ // place RHS we are looking for, in which case we need to abort to avoid UB
185+ // using an uninitialized place
186+ rustc_middle:: mir:: StatementKind :: StorageDead ( dead) => {
187+ dead_locals_seen. push ( * dead)
188+ }
189+
181190 // Check that `local_being_deref` is not being used in a mutating way which can cause misoptimization.
182191 rustc_middle:: mir:: StatementKind :: Assign ( box ( _, _) )
183192 | rustc_middle:: mir:: StatementKind :: Coverage ( _)
184193 | rustc_middle:: mir:: StatementKind :: Nop
185194 | rustc_middle:: mir:: StatementKind :: FakeRead ( _, _)
186195 | rustc_middle:: mir:: StatementKind :: StorageLive ( _)
187- | rustc_middle:: mir:: StatementKind :: StorageDead ( _)
188196 | rustc_middle:: mir:: StatementKind :: Retag ( _, _)
189197 | rustc_middle:: mir:: StatementKind :: AscribeUserType ( _, _)
190198 | rustc_middle:: mir:: StatementKind :: SetDiscriminant { .. } => {
0 commit comments